var pft=Object.defineProperty;var mft=(r,e,t)=>e in r?pft(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var gft=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Xe=(r,e,t)=>mft(r,typeof e!="symbol"?e+"":e,t);var s4i=gft((Ap,Sp)=>{function ONe(r,e){for(var t=0;ti[n]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))i(n);new MutationObserver(n=>{for(const s of n)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&i(a)}).observe(document,{childList:!0,subtree:!0});function t(n){const s={};return n.integrity&&(s.integrity=n.integrity),n.referrerPolicy&&(s.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?s.credentials="include":n.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(n){if(n.ep)return;n.ep=!0;const s=t(n);fetch(n.href,s)}})();var Ri=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qx(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function LNe(r){if(r.__esModule)return r;var e=r.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(r).forEach(function(i){var n=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return r[i]}})}),t}var Tge={exports:{}},NNe=function(e,t){return function(){for(var n=new Array(arguments.length),s=0;s"u"}function vft(r){return r!==null&&!eZ(r)&&r.constructor!==null&&!eZ(r.constructor)&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}var FNe=q6("ArrayBuffer");function yft(r){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&FNe(r.buffer),e}function xft(r){return typeof r=="string"}function bft(r){return typeof r=="number"}function BNe(r){return r!==null&&typeof r=="object"}function HY(r){if(Rge(r)!=="object")return!1;var e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}var Cft=q6("Date"),Aft=q6("File"),Sft=q6("Blob"),Eft=q6("FileList");function Pge(r){return Mge.call(r)==="[object Function]"}function Tft(r){return BNe(r)&&Pge(r.pipe)}function Mft(r){var e="[object FormData]";return r&&(typeof FormData=="function"&&r instanceof FormData||Mge.call(r)===e||Pge(r.toString)&&r.toString()===e)}var Rft=q6("URLSearchParams");function Ift(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function Pft(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function wge(r,e){if(!(r===null||typeof r>"u"))if(typeof r!="object"&&(r=[r]),Ige(r))for(var t=0,i=r.length;t0;)s=i[n],a[s]||(e[s]=r[s],a[s]=!0);r=Object.getPrototypeOf(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e}function Nft(r,e,t){r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;var i=r.indexOf(e,t);return i!==-1&&i===t}function Fft(r){if(!r)return null;var e=r.length;if(eZ(e))return null;for(var t=new Array(e);e-- >0;)t[e]=r[e];return t}var Bft=function(r){return function(e){return r&&e instanceof r}}(typeof Uint8Array<"u"&&Object.getPrototypeOf(Uint8Array)),bh={isArray:Ige,isArrayBuffer:FNe,isBuffer:vft,isFormData:Mft,isArrayBufferView:yft,isString:xft,isNumber:bft,isObject:BNe,isPlainObject:HY,isUndefined:eZ,isDate:Cft,isFile:Aft,isBlob:Sft,isFunction:Pge,isStream:Tft,isURLSearchParams:Rft,isStandardBrowserEnv:Pft,forEach:wge,merge:mue,extend:wft,trim:Ift,stripBOM:Dft,inherits:Oft,toFlatObject:Lft,kindOf:Rge,kindOfTest:q6,endsWith:Nft,toArray:Fft,isTypedArray:Bft,isFileList:Eft},CI=bh;function S6e(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var kNe=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(CI.isURLSearchParams(t))n=t.toString();else{var s=[];CI.forEach(t,function(l,c){l===null||typeof l>"u"||(CI.isArray(l)?c=c+"[]":l=[l],CI.forEach(l,function(h){CI.isDate(h)?h=h.toISOString():CI.isObject(h)&&(h=JSON.stringify(h)),s.push(S6e(c)+"="+S6e(h))}))}),n=s.join("&")}if(n){var a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+n}return e},kft=bh;function EJ(){this.handlers=[]}EJ.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};EJ.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};EJ.prototype.forEach=function(e){kft.forEach(this.handlers,function(i){i!==null&&e(i)})};var Uft=EJ,zft=bh,Vft=function(e,t){zft.forEach(e,function(n,s){s!==t&&s.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[s])})},UNe=bh;function Z5(r,e,t,i,n){Error.call(this),this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),n&&(this.response=n)}UNe.inherits(Z5,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 zNe=Z5.prototype,VNe={};["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(r){VNe[r]={value:r}});Object.defineProperties(Z5,VNe);Object.defineProperty(zNe,"isAxiosError",{value:!0});Z5.from=function(r,e,t,i,n,s){var a=Object.create(zNe);return UNe.toFlatObject(r,a,function(l){return l!==Error.prototype}),Z5.call(a,r.message,e,t,i,n),a.name=r.name,s&&Object.assign(a,s),a};var Xw=Z5,GNe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Lm=bh;function Gft(r,e){e=e||new FormData;var t=[];function i(s){return s===null?"":Lm.isDate(s)?s.toISOString():Lm.isArrayBuffer(s)||Lm.isTypedArray(s)?typeof Blob=="function"?new Blob([s]):Buffer.from(s):s}function n(s,a){if(Lm.isPlainObject(s)||Lm.isArray(s)){if(t.indexOf(s)!==-1)throw Error("Circular reference detected in "+a);t.push(s),Lm.forEach(s,function(l,c){if(!Lm.isUndefined(l)){var u=a?a+"."+c:c,h;if(l&&!a&&typeof l=="object"){if(Lm.endsWith(c,"{}"))l=JSON.stringify(l);else if(Lm.endsWith(c,"[]")&&(h=Lm.toArray(l))){h.forEach(function(d){!Lm.isUndefined(d)&&e.append(u,i(d))});return}}n(l,u)}}),t.pop()}else e.append(a,i(s))}return n(r),e}var WNe=Gft,Zne,E6e;function Wft(){if(E6e)return Zne;E6e=1;var r=Xw;return Zne=function(t,i,n){var s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):i(new r("Request failed with status code "+n.status,[r.ERR_BAD_REQUEST,r.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))},Zne}var qne,T6e;function Kft(){if(T6e)return qne;T6e=1;var r=bh;return qne=r.isStandardBrowserEnv()?function(){return{write:function(i,n,s,a,o,l){var c=[];c.push(i+"="+encodeURIComponent(n)),r.isNumber(s)&&c.push("expires="+new Date(s).toGMTString()),r.isString(a)&&c.push("path="+a),r.isString(o)&&c.push("domain="+o),l===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(i){var n=document.cookie.match(new RegExp("(^|;\\s*)("+i+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(i){this.write(i,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),qne}var Hft=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},jft=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},$ft=Hft,Xft=jft,KNe=function(e,t){return e&&!$ft(t)?Xft(e,t):t},Jne,M6e;function Yft(){if(M6e)return Jne;M6e=1;var r=bh,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 Jne=function(i){var n={},s,a,o;return i&&r.forEach(i.split(` `),function(c){if(o=c.indexOf(":"),s=r.trim(c.substr(0,o)).toLowerCase(),a=r.trim(c.substr(o+1)),s){if(n[s]&&e.indexOf(s)>=0)return;s==="set-cookie"?n[s]=(n[s]?n[s]:[]).concat([a]):n[s]=n[s]?n[s]+", "+a:a}}),n},Jne}var ese,R6e;function Qft(){if(R6e)return ese;R6e=1;var r=bh;return ese=r.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a"),n;function s(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 n=s(window.location.href),function(o){var l=r.isString(o)?s(o):o;return l.protocol===n.protocol&&l.host===n.host}}():function(){return function(){return!0}}(),ese}var tse,I6e;function TJ(){if(I6e)return tse;I6e=1;var r=Xw,e=bh;function t(i){r.call(this,i??"canceled",r.ERR_CANCELED),this.name="CanceledError"}return e.inherits(t,r,{__CANCEL__:!0}),tse=t,tse}var ise,P6e;function Zft(){return P6e||(P6e=1,ise=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}),ise}var rse,w6e;function D6e(){if(w6e)return rse;w6e=1;var r=bh,e=Wft(),t=Kft(),i=kNe,n=KNe,s=Yft(),a=Qft(),o=GNe,l=Xw,c=TJ(),u=Zft();return rse=function(d){return new Promise(function(p,g){var m=d.data,_=d.headers,y=d.responseType,v;function x(){d.cancelToken&&d.cancelToken.unsubscribe(v),d.signal&&d.signal.removeEventListener("abort",v)}r.isFormData(m)&&r.isStandardBrowserEnv()&&delete _["Content-Type"];var b=new XMLHttpRequest;if(d.auth){var C=d.auth.username||"",A=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";_.Authorization="Basic "+btoa(C+":"+A)}var E=n(d.baseURL,d.url);b.open(d.method.toUpperCase(),i(E,d.params,d.paramsSerializer),!0),b.timeout=d.timeout;function P(){if(b){var R="getAllResponseHeaders"in b?s(b.getAllResponseHeaders()):null,I=!y||y==="text"||y==="json"?b.responseText:b.response,D={data:I,status:b.status,statusText:b.statusText,headers:R,config:d,request:b};e(function(z){p(z),x()},function(z){g(z),x()},D),b=null}}if("onloadend"in b?b.onloadend=P:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(P)},b.onabort=function(){b&&(g(new l("Request aborted",l.ECONNABORTED,d,b)),b=null)},b.onerror=function(){g(new l("Network Error",l.ERR_NETWORK,d,b,b)),b=null},b.ontimeout=function(){var I=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",D=d.transitional||o;d.timeoutErrorMessage&&(I=d.timeoutErrorMessage),g(new l(I,D.clarifyTimeoutError?l.ETIMEDOUT:l.ECONNABORTED,d,b)),b=null},r.isStandardBrowserEnv()){var w=(d.withCredentials||a(E))&&d.xsrfCookieName?t.read(d.xsrfCookieName):void 0;w&&(_[d.xsrfHeaderName]=w)}"setRequestHeader"in b&&r.forEach(_,function(I,D){typeof m>"u"&&D.toLowerCase()==="content-type"?delete _[D]:b.setRequestHeader(D,I)}),r.isUndefined(d.withCredentials)||(b.withCredentials=!!d.withCredentials),y&&y!=="json"&&(b.responseType=d.responseType),typeof d.onDownloadProgress=="function"&&b.addEventListener("progress",d.onDownloadProgress),typeof d.onUploadProgress=="function"&&b.upload&&b.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(v=function(R){b&&(g(!R||R&&R.type?new c:R),b.abort(),b=null)},d.cancelToken&&d.cancelToken.subscribe(v),d.signal&&(d.signal.aborted?v():d.signal.addEventListener("abort",v))),m||(m=null);var M=u(E);if(M&&["http","https","file"].indexOf(M)===-1){g(new l("Unsupported protocol "+M+":",l.ERR_BAD_REQUEST,d));return}b.send(m)})},rse}var nse,O6e;function qft(){return O6e||(O6e=1,nse=null),nse}var Ou=bh,L6e=Vft,N6e=Xw,Jft=GNe,ept=WNe,tpt={"Content-Type":"application/x-www-form-urlencoded"};function F6e(r,e){!Ou.isUndefined(r)&&Ou.isUndefined(r["Content-Type"])&&(r["Content-Type"]=e)}function ipt(){var r;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(r=D6e()),r}function rpt(r,e,t){if(Ou.isString(r))try{return(e||JSON.parse)(r),Ou.trim(r)}catch(i){if(i.name!=="SyntaxError")throw i}return(0,JSON.stringify)(r)}var MJ={transitional:Jft,adapter:ipt(),transformRequest:[function(e,t){if(L6e(t,"Accept"),L6e(t,"Content-Type"),Ou.isFormData(e)||Ou.isArrayBuffer(e)||Ou.isBuffer(e)||Ou.isStream(e)||Ou.isFile(e)||Ou.isBlob(e))return e;if(Ou.isArrayBufferView(e))return e.buffer;if(Ou.isURLSearchParams(e))return F6e(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i=Ou.isObject(e),n=t&&t["Content-Type"],s;if((s=Ou.isFileList(e))||i&&n==="multipart/form-data"){var a=this.env&&this.env.FormData;return ept(s?{"files[]":e}:e,a&&new a)}else if(i||n==="application/json")return F6e(t,"application/json"),rpt(e);return e}],transformResponse:[function(e){var t=this.transitional||MJ.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,s=!i&&this.responseType==="json";if(s||n&&Ou.isString(e)&&e.length)try{return JSON.parse(e)}catch(a){if(s)throw a.name==="SyntaxError"?N6e.from(a,N6e.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:qft()},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Ou.forEach(["delete","get","head"],function(e){MJ.headers[e]={}});Ou.forEach(["post","put","patch"],function(e){MJ.headers[e]=Ou.merge(tpt)});var Dge=MJ,npt=bh,spt=Dge,apt=function(e,t,i){var n=this||spt;return npt.forEach(i,function(a){e=a.call(n,e,t)}),e},sse,B6e;function HNe(){return B6e||(B6e=1,sse=function(e){return!!(e&&e.__CANCEL__)}),sse}var k6e=bh,ase=apt,opt=HNe(),lpt=Dge,cpt=TJ();function ose(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new cpt}var upt=function(e){ose(e),e.headers=e.headers||{},e.data=ase.call(e,e.data,e.headers,e.transformRequest),e.headers=k6e.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),k6e.forEach(["delete","get","head","post","put","patch","common"],function(n){delete e.headers[n]});var t=e.adapter||lpt.adapter;return t(e).then(function(n){return ose(e),n.data=ase.call(e,n.data,n.headers,e.transformResponse),n},function(n){return opt(n)||(ose(e),n&&n.response&&(n.response.data=ase.call(e,n.response.data,n.response.headers,e.transformResponse))),Promise.reject(n)})},tp=bh,jNe=function(e,t){t=t||{};var i={};function n(u,h){return tp.isPlainObject(u)&&tp.isPlainObject(h)?tp.merge(u,h):tp.isPlainObject(h)?tp.merge({},h):tp.isArray(h)?h.slice():h}function s(u){if(tp.isUndefined(t[u])){if(!tp.isUndefined(e[u]))return n(void 0,e[u])}else return n(e[u],t[u])}function a(u){if(!tp.isUndefined(t[u]))return n(void 0,t[u])}function o(u){if(tp.isUndefined(t[u])){if(!tp.isUndefined(e[u]))return n(void 0,e[u])}else return n(void 0,t[u])}function l(u){if(u in t)return n(e[u],t[u]);if(u in e)return n(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 tp.forEach(Object.keys(e).concat(Object.keys(t)),function(h){var d=c[h]||s,f=d(h);tp.isUndefined(f)&&d!==l||(i[h]=f)}),i},lse,U6e;function $Ne(){return U6e||(U6e=1,lse={version:"0.27.2"}),lse}var hpt=$Ne().version,Vy=Xw,Oge={};["object","boolean","number","function","string","symbol"].forEach(function(r,e){Oge[r]=function(i){return typeof i===r||"a"+(e<1?"n ":" ")+r}});var z6e={};Oge.transitional=function(e,t,i){function n(s,a){return"[Axios v"+hpt+"] Transitional option '"+s+"'"+a+(i?". "+i:"")}return function(s,a,o){if(e===!1)throw new Vy(n(a," has been removed"+(t?" in "+t:"")),Vy.ERR_DEPRECATED);return t&&!z6e[a]&&(z6e[a]=!0,console.warn(n(a," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(s,a,o):!0}};function dpt(r,e,t){if(typeof r!="object")throw new Vy("options must be an object",Vy.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(r),n=i.length;n-- >0;){var s=i[n],a=e[s];if(a){var o=r[s],l=o===void 0||a(o,s,r);if(l!==!0)throw new Vy("option "+s+" must be "+l,Vy.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Vy("Unknown option "+s,Vy.ERR_BAD_OPTION)}}var fpt={assertOptions:dpt,validators:Oge},XNe=bh,ppt=kNe,V6e=Uft,G6e=upt,RJ=jNe,mpt=KNe,YNe=fpt,AI=YNe.validators;function q5(r){this.defaults=r,this.interceptors={request:new V6e,response:new V6e}}q5.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=RJ(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&&YNe.assertOptions(i,{silentJSONParsing:AI.transitional(AI.boolean),forcedJSONParsing:AI.transitional(AI.boolean),clarifyTimeoutError:AI.transitional(AI.boolean)},!1);var n=[],s=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(t)===!1||(s=s&&f.synchronous,n.unshift(f.fulfilled,f.rejected))});var a=[];this.interceptors.response.forEach(function(f){a.push(f.fulfilled,f.rejected)});var o;if(!s){var l=[G6e,void 0];for(Array.prototype.unshift.apply(l,n),l=l.concat(a),o=Promise.resolve(t);l.length;)o=o.then(l.shift(),l.shift());return o}for(var c=t;n.length;){var u=n.shift(),h=n.shift();try{c=u(c)}catch(d){h(d);break}}try{o=G6e(c)}catch(d){return Promise.reject(d)}for(;a.length;)o=o.then(a.shift(),a.shift());return o};q5.prototype.getUri=function(e){e=RJ(this.defaults,e);var t=mpt(e.baseURL,e.url);return ppt(t,e.params,e.paramsSerializer)};XNe.forEach(["delete","get","head","options"],function(e){q5.prototype[e]=function(t,i){return this.request(RJ(i||{},{method:e,url:t,data:(i||{}).data}))}});XNe.forEach(["post","put","patch"],function(e){function t(i){return function(s,a,o){return this.request(RJ(o||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:s,data:a}))}}q5.prototype[e]=t(),q5.prototype[e+"Form"]=t(!0)});var gpt=q5,cse,W6e;function _pt(){if(W6e)return cse;W6e=1;var r=TJ();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 n=this;this.promise.then(function(s){if(n._listeners){var a,o=n._listeners.length;for(a=0;a{i.style.display="none",nX=null},e)}function Ept(r){const e=document.getElementById("login-wrap");e.style.display="flex";const t=document.getElementById("login-btn"),i=async()=>{await r()&&(t.removeEventListener("click",i),e.style.display="none")};t.addEventListener("click",i)}function J5(r,e){const t=e||new Path2D;let i=r.calculative.borderRadius||0,n=i;const{x:s,y:a,width:o,height:l,ex:c,ey:u}=r.calculative.worldRect;i<1&&(i=o*i,n=l*n);let h=ie.x-t&&r.xe.y-t&&r.y0&&i>0?n=180-n:t<0&&i>0?n+=180:t<0&&i<0&&(n=360-n),n}function IJ(r,e){const t=r.x-e.x,i=r.y-e.y;return Math.sqrt(t*t+i*i)}function Npt(r,e){let t=Un.None;if(!e)return t;const i=r.x-e.x,n=r.y-e.y;return Math.abs(i)>Math.abs(n)?i>0?t=Un.Right:t=Un.Left:n>0?t=Un.Bottom:t=Un.Up,t}function G9(r,e,t){r&&(r.x+=e,r.y+=t,r.next&&(r.next.x+=e,r.next.y+=t),r.prev&&(r.prev.x+=e,r.prev.y+=t))}function Z6e(r,e){return r.anchorId===e.anchorId&&r.connectTo===e.connectTo}function sX(r,e,t){let i=Math.sqrt((r.x-e.x)*(r.x-e.x)+(r.y-e.y)*(r.y-e.y))/t.data.scale;e.rotate===0?r.x>>0,1)},emit:function(e,t){(r.get(e)||[]).slice().map(function(i){i(t)}),(r.get("*")||[]).slice().map(function(i){i(e,t)})}}}var gS;(function(r){r[r.None=-1]="None",r[r.Document=0]="Document",r[r.Canvas=1]="Canvas"})(gS||(gS={}));const Jpt={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:gS.Document,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},e0t={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"}}};var Vr;(function(r){r[r.Add=0]="Add",r[r.Update=1]="Update",r[r.Delete=2]="Delete",r[r.Replace=3]="Replace"})(Vr||(Vr={}));const t0t=()=>({data:{x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},theme:"light"},histories:[],pens:{},path2dMap:new WeakMap,animateMap:new WeakMap,active:[],animates:new Set,options:{...Jpt},theme:{...e0t},emitter:qpt(),bindDatas:{},bind:{},pensNetwork:{},cacheDatas:[],messageEvents:{},templatePens:{},globalTriggers:{}}),i0t=(r="default")=>(un[r]||(un[r]=t0t(),un[r].id=r),un[r]),r0t=(r,e)=>{const t=r.data.template===e;if(t)for(const i of r.data.pens)i.canvasLayer===Rs.CanvasTemplate&&(r.templatePens[i.id]=i);r.lastScale=r.data.scale,r.data={x:0,y:0,scale:1,pens:[],origin:{x:0,y:0},center:{x:0,y:0},paths:{},template:t?e:null},r.sameTemplate=t,r.pens={},r.histories=[],r.historyIndex=null,r.path2dMap=new WeakMap,r.animateMap=new WeakMap,r.bindDatas={},r.bind={},r.pensNetwork={},r.active=[],r.hover=void 0,r.lastHover=void 0,r.animates.clear()};function t_(r){const{paddingTop:e,paddingBottom:t,paddingLeft:i,paddingRight:n,worldRect:s,canvas:a}=r.calculative;let{textLeft:o,textTop:l,textWidth:c,textHeight:u}=r.calculative,h=i,d=e;const f=s.width-i-n-((r.textAlign==="right"?-o:o)||0),p=s.height-e-t-((r.textBaseline==="bottom"?-l:l)||0);c&&c<1&&(c*=s.width),u&&u<1&&(u*=s.height),c1?s:1;switch(r.whiteSpace){case"nowrap":if(r.ellipsis!==!1){const u=q6e(e.split(""),r);u[0]&&(t.push(u[0]),u.length>1&&dse(t))}else t.push(e);break;case"pre-line":t=e.split(/[\n]/g),r.ellipsis!==!1&&t.length>a&&(t=t.slice(0,a),dse(t));break;case"break-all":default:const l=e.split(/[\n]/g);let c=0;e:for(const u of l){const h=r.whiteSpace==="break-all"?u.split(""):eFe(u);let d=q6e(h,r);if(d.length===0&&(d=[""]),r.ellipsis!=!1)for(const f of d)if(c++,c>a){dse(t);break e}else t.push(f);else t.push(...d)}break}const o=r.calculative.keepDecimal;return o!=null&&t.forEach((l,c)=>{const u=Number(l);isNaN(u)||(t[c]=u.toFixed(o))}),r.calculative.textLines=t,t}function eFe(r=""){const e=[];let t="";for(let i=0;i126?(t&&(e.push(t),t=""),e.push(r[i])):t+=r[i]}return t&&e.push(t),e}function q6e(r,e){const t=e.calculative.canvas,i=t.offscreen.getContext("2d"),{fontStyle:n,fontWeight:s,fontSize:a,fontFamily:o,lineHeight:l}=e.calculative;i.save();const c=[];let u=r[0]||"";for(let h=1;h{const n=r.measureText(i).width;e.calculative.textLineWidths.push(n),tc&&(c=u)}i.restore();let h=e.length*a*l;r.textAlign==="left"||(r.textAlign==="right"?r.x=r.x-(c-r.width):r.x=r.x-(c-r.width)/2),r.textBaseline==="top"||(r.textBaseline==="bottom"?r.y=r.y-(h-r.height):r.y=r.y-(h-r.height)/2),r.height=h+2,r.width=c+2,r.calculative.canvas.updatePenRect(r),r.calculative.canvas.calcActiveRect()}function Zt(r,e=!1){if(Array.isArray(r)){const t=[];return r.forEach(i=>{t.push(Zt(i,e))}),t}else if(typeof r=="object"){if(r===null)return null;if(r.constructor===RegExp)return r;const t={};for(const i in r)if(!(["canvas","lastFrame"].includes(i)||r[i]instanceof HTMLImageElement||r[i]instanceof HTMLMediaElement)){{if(i==="calculative"&&!e)continue;if(i==="singleton"){e?t[i]={}:t[i]=r[i];continue}}t[i]=Zt(r[i],e)}return t}return r}function _ue(r,e,t){if(Array.isArray(r)){const i=[];return r.forEach(n=>{i.push(_ue(n,e,t))}),i}else if(typeof r=="object"){if(r===null)return null;for(const i in r)if(e.includes(i))if(Array.isArray(r[i]))r[i].forEach((n,s)=>{Number.isNaN(Number(n))||(r[i][s]=Number(n*t))});else{if(Number.isNaN(Number(r[i])))continue;r[i]=Number(r[i])*t}else r[i]=_ue(r[i],e,t);return r}return r}const Pp={};function tFe(r,e,t){if(!Pp[e.fromArrow])return;const i=Wl(e),{x:n,y:s}=i,a={x:n,y:s};if(a.step=(e.fromArrowSize||10)*t.data.scale,i.next)a.rotate=R0(i.next,i)+90;else{const l=e.calculative.worldAnchors[1];if(!l)return;l.prev?a.rotate=R0(l.prev,i)+90:a.rotate=R0(l,i)+90}r.save(),r.beginPath(),r.setLineDash([]);const o=e.fromArrowColor||e.calculative.color;o&&(r.strokeStyle=o),Pp[e.fromArrow](r,e,t,a),r.restore()}function iFe(r,e,t){if(!Pp[e.toArrow]||e.calculative.worldAnchors.length<2)return;r.save();const i=na(e),{x:n,y:s}=i,a={x:n,y:s};if(a.step=(e.toArrowSize||10)*t.data.scale,i.prev)a.rotate=R0(i.prev,i)+90;else{const l=e.calculative.worldAnchors[e.calculative.worldAnchors.length-2];l.next?a.rotate=R0(l.next,i)+90:a.rotate=R0(l,i)+90}r.beginPath(),r.setLineDash([]);const o=e.toArrowColor||e.calculative.color;o&&(r.strokeStyle=o),Pp[e.toArrow](r,e,t,a),r.restore()}Pp.triangleSolid=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step;r.moveTo(n,i.y-i.step/4),r.lineTo(i.x,i.y),r.lineTo(n,i.y+i.step/4),r.closePath(),r.stroke(),r.fillStyle=r.strokeStyle,r.fill(),r.restore()};Pp.triangle=(r,e,t,i)=>{r.save(),r.lineWidth<2&&(r.lineWidth=2),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step;r.moveTo(n,i.y-i.step/4),r.lineTo(i.x,i.y),r.lineTo(n,i.y+i.step/4),r.closePath(),r.stroke(),r.fillStyle=t.data.background||"#ffffff",r.fill(),r.restore()};Pp.circleSolid=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.step/2;r.arc(i.x-n,i.y,n,0,2*Math.PI),r.stroke(),r.fillStyle=r.strokeStyle,r.fill(),r.restore()};Pp.circle=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.step/2;r.arc(i.x-n,i.y,n,0,2*Math.PI),r.stroke(),r.fillStyle=t.data.background||"#ffffff",r.fill(),r.restore()};Pp.diamondSolid=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step,s=i.step/2;r.moveTo(n,i.y),r.lineTo(n+s,i.y-s/2),r.lineTo(i.x,i.y),r.lineTo(n+s,i.y+s/2),r.closePath(),r.stroke(),r.fillStyle=r.strokeStyle,r.fill(),r.restore()};Pp.diamond=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step,s=i.step/2;r.moveTo(n,i.y),r.lineTo(n+s,i.y-s/2),r.lineTo(i.x,i.y),r.lineTo(n+s,i.y+s/2),r.closePath(),r.stroke(),r.fillStyle=t.data.background||"#ffffff",r.fill(),r.restore()};Pp.line=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step;r.moveTo(n,i.y-i.step/3),r.lineTo(i.x,i.y),r.lineTo(n,i.y+i.step/3),r.stroke(),r.restore()};Pp.lineUp=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step;r.moveTo(n,i.y-i.step/3),r.lineTo(i.x,i.y),r.stroke(),r.restore()};Pp.lineDown=(r,e,t,i)=>{r.save(),r.translate(i.x,i.y),r.rotate(i.rotate*Math.PI/180),r.translate(-i.x,-i.y);const n=i.x-i.step;r.moveTo(n,i.y+i.step/3),r.lineTo(i.x,i.y),r.stroke(),r.restore()};function vue(r){const e=parseInt,t=Math.round;let i=r.length,n={};if(i>9){const[s,a,o,l]=r=r.split(",");if(i=r.length,i<3||i>4)return null;n.r=e(s[3]=="a"?s.slice(5):s.slice(4)),n.g=e(a),n.b=e(o),n.a=l?parseFloat(l):-1}else{if(i==8||i==6||i<4)return null;i<6&&(r="#"+r[1]+r[1]+r[2]+r[2]+r[3]+r[3]+(i>4?r[4]+r[4]:"")),r=e(r.slice(1),16),i==9||i==5?(n.r=r>>24&255,n.g=r>>16&255,n.b=r>>8&255,n.a=t((r&255)/.255)/1e3):(n.r=r>>16,n.g=r>>8&255,n.b=r&255,n.a=-1)}return n}function ph(r,e,t,i){let n,s,a,o,l,c,u,h=Math.round,d=typeof t=="string";return typeof r!="number"||r<-1||r>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=vue(e),o=r<0,c=t&&t!="c"?vue(t):o?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},r=o?r*-1:r,o=1-r,!l||!c)?null:(i?(n=h(o*l.r+r*c.r),s=h(o*l.g+r*c.g),a=h(o*l.b+r*c.b)):(n=h((o*l.r**2+r*c.r**2)**.5),s=h((o*l.g**2+r*c.g**2)**.5),a=h((o*l.b**2+r*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*r:0,u?"rgb"+(l?"a(":"(")+n+","+s+","+a+(l?","+h(d*1e3)/1e3:"")+")":"#"+(4294967296+n*16777216+s*65536+a*256+(l?h(d*255):0)).toString(16).slice(1,l?void 0:-2))}globalThis.pSBC=ph;function iZ(r,e){const t=vue(r)||{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 SI(r,e){if(isNaN(r)){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 n=e.substring(1,e.length-1).split(",");if(n.length!==2){console.warn("collection must have 2 numbers");return}const[s,a]=[+n[0],+n[1]];if(s>=a){console.warn("startNum must less than endNum");return}return r>s||t==="["&&r===s?r=c){console.warn("startNum must less than endNum");return}if(r>=l&&r<=c)return!0}else if(r==s)return!0;return!1}function rs(){return((1+Math.random())*4294967296|0).toString(16).substring(1)}const Sv=r=>{let e=0,t=0,i=0,n=0;return typeof r=="number"?e=t=i=n=r:typeof r=="string"?e=t=i=n=parseInt(r,10):Array.isArray(r)&&(e=r[0],i=fse(r[1])?r[0]:r[1],n=fse(r[2])?r[0]:r[2],t=fse(r[3])?i:r[3]),[e,i,n,t]};function fse(r){return r==null}async function a0t(r){return new Promise((e,t)=>{const i=new FileReader;i.onload=n=>{e(n.target.result)},i.onerror=n=>{t(n)},i.readAsDataURL(r)})}async function o0t(r,e,t,i){const n=new FormData;if(n.append("file",r),t)for(const a in t)t.hasOwnProperty(a)&&n.append(a,t[a]);return(await(await fetch(e,{method:"POST",headers:i,body:n})).json()).url}function l0t(r,e,t){var i=document.createElement("link");i.href=r,i.rel="stylesheet",e&&(i.onload=e),document.head.appendChild(i)}function pse(r){let e=r||window.location.search.split("?")[1];const t=new URLSearchParams(e);return Object.fromEntries(t.entries())}function AP(r,e){if(e==null)return r;const t=e.split(".");for(;t.length&&(r=r[t.shift()]););return r}function yue(r,e,t){e!=null&&e.split(".").reduce((i,n,s)=>i[n]=e.split(".").length===++s?t:i[n]||{},r)}function c0t(r){const e=["天","一","二","三","四","五","六"],t=new Date,i=t.getFullYear(),n=t.getMonth()+1,s=t.getDate(),a=t.getDay(),o=t.getHours(),l=t.getMinutes(),c=t.getSeconds();return new Function("year","month","day","week","hours","minutes","seconds",r?`return ${r}`:"return `${year}:${month}:${day} ${hours}:${minutes}:${seconds} 星期${week}`")(i,n,s,e[a],o,l,c)}function u0t(r,e){if(!r||!e)return!1;let t=pp(r);for(;t;){if(t.id===e.id)return!0;t=pp(t)}return!1}function pp(r,e){if(!r||!r.parentId||!r.calculative)return;const i=r.calculative.canvas.store.pens[r.parentId];return e&&pp(i,e)||i}function j1(r,e){if(!r||!r.children)return[];const t=[];return r.children.forEach(i=>{const n=e.pens[i];n&&(t.push(n),t.push(...j1(n,e)))}),t}function Lge(r,e){if(!r||!r.followers)return[];const t=[];return r.followers.forEach(i=>{const n=e.pens[i];n&&!n.parentId&&(t.push(n),t.push(...Lge(n,e)))}),t}function h0t(r,e){const{worldRect:t,gradientFromColor:i,gradientToColor:n,gradientAngle:s}=e.calculative;return nFe(r,t,i,n,s)}function d0t(r,e){const{worldRect:t,gradientFromColor:i,gradientToColor:n,gradientRadius:s}=e.calculative;if(!i||!n)return;const{width:a,height:o,center:l}=t,{x:c,y:u}=l;let h=a;h{d.addColorStop(f.i,f.color)}),d}function m0t(r,e){const{x:t,y:i,ex:n,width:s,height:a,center:o}=e.calculative.worldRect;let l=[{x:n,y:i+a/2},{x:t,y:i+a/2}];const{angle:c,colors:u}=J6(e.calculative.gradientColors);let h=Nge(c,s,a);return l.forEach(d=>{fo(d,c,o)}),PJ(r,l,u,h)}function g0t(r,e){const{worldRect:t,textGradientColors:i}=e.calculative;if(!i)return;const{width:n,height:s,center:a}=t,{x:o,y:l}=a;let c=n;c{h.addColorStop(d.i,d.color)}),h}function _0t(r,e){const{x:t,y:i,ex:n,width:s,height:a,center:o}=e.calculative.worldRect;let l=[{x:n,y:i+a/2},{x:t,y:i+a/2}];const{angle:c,colors:u}=J6(e.calculative.textGradientColors);let h=Nge(c,s,a);return l.forEach(d=>{fo(d,c,o)}),PJ(r,l,u,h)}function Nge(r,e,t){const i=Math.atan(t/e)/Math.PI*180;let n=(r-90)%360,s=0;return n>i&&n<180-i||n>180+i&&n<360-i||n<0?(n>270?n=360-n:n>180?n=n-180:n>90&&(n=180-n),s=Math.abs(t/Math.sin(n/180*Math.PI)/2)):(n>270?n=360-n:n>180?n=n-180:n>90&&(n=180-n),s=Math.abs(e/Math.cos(n/180*Math.PI)/2)),s}function J6(r){if(typeof r=="string"&&r.startsWith("linear-gradient")){let e=r.slice(16,-2).split("deg,");if(e.length>1){let t=e[1].split("%,");const i=[];return t.forEach(n=>{if(/rgba?/.test(n)){let s=n.split(") ");i.push({color:v0t(s[0]+")"),i:parseFloat(s[1])/100})}else{let s=n.split(" ");s.length>2?i.push({color:s[1],i:parseFloat(s[2])/100}):i.push({color:s[0],i:parseFloat(s[1])/100})}}),{angle:parseFloat(e[0]),colors:i}}else return{angle:parseFloat(e[0]),colors:[]}}else return{angle:0,colors:[]}}function v0t(r){if(/rgba?/.test(r)){let e=r.split(",");if(e.length<3)return"";r="#";for(let t=0,i;i=e[t++];)if(t<4)i=parseInt(i.replace(/[^\d]/gi,""),10).toString(16),r+=i.length==1?"0"+i:i;else{i=i.replace(")","");let s=parseInt(i*255+"").toString(16);s=s.length===2?s:"0"+s,r+=s}r=r.toUpperCase()}return r}function y0t(r,e){const{x:t,y:i,ex:n,width:s,height:a,center:o}=e.calculative.worldRect;let l=[{x:n,y:i+a/2},{x:t,y:i+a/2}];const{angle:c,colors:u}=J6(e.calculative.lineGradientColors);let h=Nge(c,s,a);return l.forEach(d=>{fo(d,c,o)}),PJ(r,l,u,h)}function PJ(r,e,t,i){let n=f0t(e[0].x,e[0].y,e[1].x,e[1].y,i),s=r.createLinearGradient(n[0],n[1],n[2],n[3]);return t.forEach(a=>{s.addColorStop(a.i,a.color)}),s}function Ly(r,e,t){let i=[];e.calculative.gradientColorStop?i=e.calculative.gradientColorStop:(i=J6(e.calculative.lineGradientColors).colors,e.calculative.gradientColorStop=i),r.strokeStyle=PJ(r,t,i,e.calculative.lineWidth/2),r.beginPath(),r.moveTo(t[0].x,t[0].y),r.lineTo(t[1].x,t[1].y),r.stroke()}function rFe(r,e){const t=e.calculative.worldAnchors;let i=e.calculative.lineWidth*(e.calculative.gradientSmooth||e.calculative.lineSmooth||0);for(let n=0;n0){let o=t[n-1].curvePoints;o?aX(r,e,i,o[o.length-1],t[n],t[n].curvePoints[0]):aX(r,e,i,t[n-1],t[n],t[n].curvePoints[0]);let l=Mv(i,t[n],t[n].curvePoints[0]);Ly(r,e,[l,t[n].curvePoints[1]])}else Ly(r,e,[t[n],t[n].curvePoints[0]]),Ly(r,e,[t[n].curvePoints[0],t[n].curvePoints[1]]);let s=t[n].curvePoints.length-1;for(let o=1;o0&&n0&&n0&&n0&&n{const P=e.calculative.textLineWidths[E];let w=0;b==="center"?w=(y-P)/2:b==="right"&&(w=y-P),r.fillText(A,m+w,_+(E+x)*C);const{textDecorationColor:M,textDecorationDash:R,textDecoration:I}=e;I&&T0t(r,{x:m+w,y:_+(E+x)*C,width:P},{textDecorationColor:M,textDecorationDash:R,fontSize:n});const{textStrickoutColor:D,textStrickoutDash:k,textStrickout:z}=e;z&&M0t(r,{x:m+w,y:_+(E+x)*C,width:P},{textStrickoutColor:D,textStrickoutDash:k,fontSize:n})}),r.restore()}function T0t(r,e,t){const{textDecorationColor:i,textDecorationDash:n,fontSize:s}=t;let{x:a,y:o,width:l}=e;switch(r.textBaseline){case"top":o+=s;break;case"middle":o+=s/2;break}r.save(),r.beginPath(),r.strokeStyle=i||r.fillStyle,r.lineWidth=1,r.moveTo(a,o),r.setLineDash(n||[]),r.lineTo(a+l,o),r.stroke(),r.restore()}function M0t(r,e,t){const{textStrickoutColor:i,textStrickoutDash:n,fontSize:s}=t;let{x:a,y:o,width:l}=e;switch(r.textBaseline){case"top":o+=s/2;break;case"bottom":o-=s/2;break}r.save(),r.beginPath(),r.strokeStyle=i||r.fillStyle,r.lineWidth=1,r.moveTo(a,o),r.setLineDash(n||[]),r.lineTo(a+l,o),r.stroke(),r.restore()}function aFe(r,e,t){if(t==null)return;const{fontStyle:i,fontWeight:n,fontSize:s,fontFamily:a,lineHeight:o,canvas:l}=e.calculative,c=l.store;r.save();let u;e.calculative.hover?u=e.hoverTextColor||e.hoverColor||c.options.hoverColor:e.calculative.active&&(u=e.activeTextColor||e.activeColor||c.options.activeColor),r.fillStyle=u||kx(e,c),r.font=wp({fontStyle:i,fontWeight:n,fontFamily:a||c.options.fontFamily,fontSize:s,lineHeight:o});const h=r.measureText(t).width;let d,f;for(const p of e.calculative.worldAnchors){if(!f){f=p;continue}const g=IJ(f,p),m=Math.floor(g/h);d="";for(let y=0;y0?o=e.calculative.iconSize:i.width>i.height?o=i.height:o=i.width,r.font=wp({fontSize:o,fontWeight:a,fontFamily:l}),r.fillStyle=e.calculative.iconColor||kx(e,t),e.calculative.iconRotate&&(r.translate(i.center.x,i.center.y),r.rotate(e.calculative.iconRotate*Math.PI/180),r.translate(-i.center.x,-i.center.y)),r.beginPath(),r.fillText(e.calculative.icon,n,s),r.restore()}function wp({fontStyle:r="normal",textDecoration:e="normal",fontWeight:t="normal",fontSize:i=12,fontFamily:n="Arial",lineHeight:s=1}={}){return`${r} ${e} ${t} ${i}px/${s} ${n}`}function PS(r,e){const{x:t,ex:i,y:n,ey:s}=e.calculative.worldRect||{};e.calculative.flipX&&(r.translate(t+i+.5,.5),r.scale(-1,1)),e.calculative.flipY&&(r.translate(.5,n+s+.5),r.scale(1,-1))}function Gv(r,e,t=!1){const{x:i,y:n}=e.calculative.worldRect.pivot||e.calculative.worldRect.center;r.translate(i,n);let s=e.calculative.rotate*Math.PI/180;t||(e.calculative.flipX&&(s*=-1),e.calculative.flipY&&(s*=-1)),r.rotate(s),r.translate(-i,-n)}function aS(r,e,t){r.save(),r.translate(.5,.5),r.beginPath();const i=e.calculative.canvas.store,n=e.textFlip||i.options.textFlip,s=e.textRotate||i.options.textRotate;(!n||!s)&&r.save(),PS(r,e),e.calculative.rotate&&e.name!=="line"&&Gv(r,e),(e.calculative.lineWidth>1||t)&&(r.lineWidth=e.calculative.lineWidth),B0t(r,i,e);let a,o=!1,l;e.calculative.disabled?(l=e.disabledColor||i.options.disabledColor||ph(.4,e.calculative.color||W9(i)),a=e.disabledBackground||i.options.disabledBackground||ph(.4,e.calculative.background||i.data.penBackground)):e.mouseDownValid&&e.calculative.mouseDown?(l=e.mouseDownColor||ph(-.4,e.calculative.color||W9(i)),a=e.mouseDownBackground||ph(-.4,e.calculative.background||i.data.penBackground)):e.calculative.hover?(l=e.hoverColor||i.options.hoverColor,a=e.hoverBackground||i.options.hoverBackground):e.calculative.active?(l=e.activeColor||i.options.activeColor,a=e.activeBackground||i.options.activeBackground):e.calculative.isDock&&(e.type===sa.Line?l=i.options.dockPenColor:a=iZ(i.options.dockPenColor,.2));const c=e.calculative.strokeImg;if(e.calculative.strokeImage&&c)r.strokeStyle=l||r.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=y0t(r,e),e.calculative.lineGradient=h):h=S0t(r,e):h=e.calculative.color||W9(i),r.strokeStyle=l||h}const u=e.calculative.backgroundImg;if(e.calculative.backgroundImage&&u)r.fillStyle=a||r.createPattern(u,"repeat"),a=!0;else{let h;e.calculative.bkType===ew.Linear?e.calculative.gradientColors?e.calculative.gradient?h=e.calculative.gradient:(h=m0t(r,e),e.calculative.gradient=h):h=h0t(r,e):e.calculative.bkType===ew.Radial?e.calculative.gradientColors?e.calculative.radialGradient?h=e.calculative.radialGradient:(h=p0t(r,e),e.calculative.radialGradient=h):h=d0t(r,e):h=e.calculative.background||i.data.penBackground,r.fillStyle=a||h,a=!!h}if(lFe(r,e),cFe(r,e),wS(r,e),e.calculative.lineDash&&r.setLineDash(e.calculative.lineDash.map(h=>h*e.calculative.canvas.store.data.scale)),e.calculative.lineDashOffset&&(r.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(r.shadowColor=e.calculative.shadowColor,r.shadowOffsetX=e.calculative.shadowOffsetX,r.shadowOffsetY=e.calculative.shadowOffsetY,r.shadowBlur=e.calculative.shadowBlur),o?(rFe(r,e),hFe(!0,r,e,i)):(uFe(!0,r,e,i,a),vFe(r,e)),!(e.image&&e.calculative.img)&&e.calculative.icon&&oFe(r,e),(!n||!s)&&r.restore(),n&&!s&&PS(r,e),!n&&s&&e.calculative.rotate&&e.name!=="line"&&Gv(r,e,!0),sFe(r,e),e.type===sa.Line&&e.fillTexts)for(const h of e.fillTexts)aFe(r,e,h);r.restore()}function lFe(r,e){const t=e.lineCap||(e.type?"round":"square");t?r.lineCap=t:e.type&&(r.lineCap="round")}function cFe(r,e){const t=e.lineJoin;t?r.lineJoin=t:e.type&&(r.lineJoin="round")}function rZ(r,e,t,i){var c;r.save(),t&&r.translate(-t.x,-t.y),(c=r.setAttrs)==null||c.call(r,e);let n=!1;const s=e.calculative.canvas.store,a=e.textFlip||s.options.textFlip,o=e.textRotate||s.options.textRotate;r.beginPath(),(!a||!o)&&r.save(),e.calculative.flipX&&(r.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),r.scale(-1,1)),e.calculative.flipY&&(r.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),r.scale(1,-1)),e.calculative.rotate&&e.name!=="line"&&Gv(r,e),(e.calculative.lineWidth>1||i)&&(r.lineWidth=e.calculative.lineWidth);let l;if(e.calculative.hover)r.strokeStyle=e.hoverColor||s.options.hoverColor,r.fillStyle=e.hoverBackground||s.options.hoverBackground,l=e.hoverBackground||s.options.hoverBackground;else if(e.calculative.active)r.strokeStyle=e.activeColor||s.options.activeColor,r.fillStyle=e.activeBackground||s.options.activeBackground,l=e.activeBackground||s.options.activeBackground;else{if(e.strokeImage)e.calculative.strokeImg&&(r.strokeStyle=r.createPattern(e.calculative.strokeImg,"repeat"),l=!0);else{let u;e.calculative.strokeType&&e.calculative.lineGradientColors&&e.name==="line"?n=!0:u=e.calculative.color||W9(s),r.strokeStyle=u}e.backgroundImage?e.calculative.backgroundImg&&(r.fillStyle=r.createPattern(e.calculative.backgroundImg,"repeat"),l=!0):(r.fillStyle=e.background,l=!!e.background)}if(lFe(r,e),cFe(r,e),wS(r,e),e.calculative.lineDash&&r.setLineDash(e.calculative.lineDash),e.calculative.lineDashOffset&&(r.lineDashOffset=e.calculative.lineDashOffset),e.calculative.shadowColor&&(r.shadowColor=e.calculative.shadowColor,r.shadowOffsetX=e.calculative.shadowOffsetX,r.shadowOffsetY=e.calculative.shadowOffsetY,r.shadowBlur=e.calculative.shadowBlur),n?(rFe(r,e),hFe(!0,r,e,s)):(uFe(!1,r,e,s,l),vFe(r,e)),e.calculative.img?(r.save(),r.shadowColor="",r.shadowBlur=0,r.shadowOffsetX=0,r.shadowOffsetY=0,JP(r,e),r.restore()):e.calculative.icon&&oFe(r,e),(!a||!o)&&r.restore(),a&&!o&&(e.calculative.flipX&&(r.translate(e.calculative.worldRect.x+e.calculative.worldRect.ex,0),r.scale(-1,1)),e.calculative.flipY&&(r.translate(0,e.calculative.worldRect.y+e.calculative.worldRect.ey),r.scale(1,-1))),!a&&o&&e.calculative.rotate&&e.name!=="line"&&Gv(r,e,!0),sFe(r,e),e.type===sa.Line&&e.fillTexts)for(const u of e.fillTexts)aFe(r,e,u);r.restore()}function uFe(r=!0,e,t,i,n){const s=r?i.path2dMap.get(t):un.path2dDraws[t.name];let a=null,o=null;if(t.type===sa.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))),s){if(t.type===sa.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()),s instanceof Path2D?(n&&e.fill(s),c&&e.stroke(s)):(s(t,e),n&&e.fill(),c&&e.stroke()),o&&(e.save(),e.lineCap=t.toLineCap,e.stroke(o),e.restore()),e.restore()}s instanceof Path2D?t.type?t.close&&n&&e.fill(s):n&&e.fill(s):(e.save(),s(t,e),n&&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 g=null;if(t.verticalProgress?g=t.reverseProgress?e.createLinearGradient(u,h,u,h+f*l):e.createLinearGradient(u,p,u,h+f*(1-l)):g=t.reverseProgress?e.createLinearGradient(c,h,u+d*(1-l),h):e.createLinearGradient(u,h,u+d*l,h),t.calculative.progressGradientColors){const{colors:m}=J6(t.calculative.progressGradientColors);m.forEach(_=>{g.addColorStop(_.i,_.color)})}else{const m=t.calculative.progressColor||t.calculative.color||i.options.activeColor;g.addColorStop(0,m),g.addColorStop(1,m)}g.addColorStop(1,"transparent"),e.fillStyle=g,s instanceof Path2D?e.fill(s):(s(t,e),e.fill()),e.restore()}if(t.calculative.lineWidth&&(s instanceof Path2D?(i.options.svgPathStroke||t.name!=="svgPath")&&(a&&(e.save(),e.lineCap=t.fromLineCap,e.stroke(a),e.restore()),e.stroke(s),o&&(e.save(),e.lineCap=t.toLineCap,e.stroke(o),e.restore())):(s(t,e),e.stroke())),t.type){if(t.calculative.animatePos){if(e.save(),dFe(e,t,i),t.lineAnimateType===_p.Arrow||t.lineAnimateType===_p.WaterDrop){let c=EFe(t,e);c instanceof Path2D?(e.stroke(c),e.fill(c)):(e.stroke(),e.fill())}else s instanceof Path2D?(a&&!t.lineAnimateType&&(e.save(),e.lineCap=t.fromLineCap,e.stroke(a),e.restore()),e.lineCap=t.lineCap,e.stroke(s)):(s(t,e),e.stroke());e.restore()}t.fromArrow&&tFe(e,t,i),t.toArrow&&iFe(e,t,i),t.calculative.active&&!t.calculative.pencil&&!i.options.disableAnchor&&!i.data.locked&&fFe(e,t)}}}function hFe(r=!0,e,t,i){const n=r?i.path2dMap.get(t):un.path2dDraws[t.name];if(n&&t.type){if(t.calculative.animatePos){if(e.save(),dFe(e,t,i),e.beginPath(),n instanceof Path2D)if(t.lineName==="polyline"||t.lineName==="line")if(t.lineAnimateType===_p.Arrow||t.lineAnimateType===_p.WaterDrop){const s=EFe(t);e.stroke(s),e.fill(s)}else t.calculative.gradientSmooth||t.calculative.lineSmooth?(t.calculative.gradientAnimatePath||(t.calculative.gradientAnimatePath=Fge(t)),t.calculative.gradientAnimatePath instanceof Path2D&&e.stroke(t.calculative.gradientAnimatePath)):e.stroke(n);else e.stroke(n);else n(t,e),e.stroke();e.restore()}t.fromArrow&&tFe(e,t,i),t.toArrow&&iFe(e,t,i),t.calculative.active&&!t.calculative.pencil&&!i.options.disableAnchor&&!i.data.locked&&fFe(e,t)}}function dFe(r,e,t){r.strokeStyle=e.animateColor||t.options.animateColor,e.animateShadow&&(r.shadowBlur=e.animateShadowBlur||e.animateLineWidth||6,r.shadowColor=e.animateShadowColor||e.animateColor||t.options.animateColor),e.calculative.animateLineWidth&&(r.lineWidth=e.calculative.animateLineWidth*t.data.scale);let i=0;switch(e.lineAnimateType){case _p.Beads:e.animateReverse?r.lineDashOffset=e.calculative.animatePos:r.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.lineWidth||5,i<5&&(i=5);const n=e.animateLineDash&&e.animateLineDash.map(s=>s*i/5);r.setLineDash(n||[i,i*2]);break;case _p.Dot:e.animateReverse?r.lineDashOffset=e.calculative.animatePos:r.lineDashOffset=e.length-e.calculative.animatePos,i=e.calculative.animateDotSize||e.calculative.lineWidth*2||6,i<6&&(i=6),i>40&&(i=40),r.lineWidth=(e.calculative.animateLineWidth||i)*t.data.scale,r.setLineDash([.1,e.length]);break;case _p.Arrow:r.fillStyle=e.animateColor||t.options.animateColor,r.lineWidth=1;break;case _p.WaterDrop:r.fillStyle=e.animateColor||t.options.animateColor,r.lineWidth=1;break;default:e.animateReverse?(r.lineDashOffset=Number.EPSILON,r.setLineDash([0,e.length-e.calculative.animatePos+1,e.calculative.animatePos])):r.setLineDash([e.calculative.animatePos,e.length+.01-e.calculative.animatePos]);break}}function W9(r){const{data:e,options:t}=r;return e.color||t.color}function fFe(r,e){const t=e.calculative.canvas.store;r.save(),r.lineWidth=1,r.fillStyle=e.activeColor||t.options.activeColor,e.calculative.worldAnchors.forEach(i=>{!i.hidden&&!i.isTemp&&R0t(r,i,e)}),r.restore()}function R0t(r,e,t){if(!e)return;const i=t.calculative.canvas.store.activeAnchor===t.calculative.activeAnchor&&t.calculative.activeAnchor===e;let n=3;t.calculative.lineWidth>3&&(n=t.calculative.lineWidth),t.anchorRadius&&(n=t.anchorRadius),e.radius&&(n=e.radius),i?(e.prev&&(r.save(),r.strokeStyle="#4dffff",r.beginPath(),r.moveTo(e.prev.x,e.prev.y),r.lineTo(e.x,e.y),r.stroke(),r.restore(),r.save(),r.fillStyle="#ffffff",r.beginPath(),r.arc(e.prev.x,e.prev.y,n,0,Math.PI*2),r.fill(),r.stroke(),r.restore()),e.next&&(r.save(),r.strokeStyle="#4dffff",r.beginPath(),r.moveTo(e.x,e.y),r.lineTo(e.next.x,e.next.y),r.stroke(),r.restore(),r.save(),r.fillStyle="#ffffff",r.beginPath(),r.arc(e.next.x,e.next.y,n,0,Math.PI*2),r.fill(),r.stroke(),r.restore(),r.beginPath(),r.arc(e.x,e.y,n,0,Math.PI*2),r.fill(),r.stroke()),r.beginPath(),r.arc(e.x,e.y,n,0,Math.PI*2),r.fill(),r.stroke()):(r.save(),r.fillStyle="#ffffff",r.beginPath(),r.arc(e.x,e.y,n,0,Math.PI*2),r.fill(),r.stroke(),r.restore())}function pFe(r){const e=r.calculative.canvas.store;let t={x:r.x,y:r.y};if(!r.parentId||r.parentId&&!e.pens[r.parentId])r.parentId=void 0,t.width=r.width,t.height=r.height,t.rotate=r.rotate,Yl(t),Tl(t),r.pivot&&bue(t,r.pivot);else{const i=e.pens[r.parentId];let n=i.calculative.worldRect;n||(n=pFe(i)),t.x=n.x+n.width*r.x,t.y=n.y+n.height*r.y,t.width=n.width*r.width,t.height=n.height*r.height,i.flipX&&(t.x=n.width-(t.x-n.x+t.width)+n.x),i.flipY&&(t.y=n.height-(t.y-n.y+t.height)+n.y),Yl(t),t.rotate=n.rotate+r.rotate,Tl(t),r.pivot&&bue(t,r.pivot)}return r.calculative.worldRect=t,Bge(r,t),t}function Bge(r,e){!r.paddingTop&&(r.calculative.paddingTop=0),!r.paddingBottom&&(r.calculative.paddingBottom=0),!r.paddingLeft&&(r.calculative.paddingLeft=0),!r.paddingRight&&(r.calculative.paddingRight=0),Math.abs(r.calculative.paddingTop)<1&&(r.calculative.paddingTop*=e.height),Math.abs(r.calculative.paddingBottom)<1&&(r.calculative.paddingBottom*=e.height),Math.abs(r.calculative.paddingLeft)<1&&(r.calculative.paddingLeft*=e.width),Math.abs(r.calculative.paddingRight)<1&&(r.calculative.paddingRight*=e.width)}function $Y(r){const e=Zt(r.calculative.worldRect);if(delete e.pivot,!r.parentId){Object.assign(r,e);return}const i=r.calculative.canvas.store.pens[r.parentId].calculative.worldRect;Object.assign(r,XY(e,i))}function K9(r){const e=r.calculative.canvas.store;let t=[];if(r.anchors){let i=Zt(r.anchors);r.flipX&&i.forEach(n=>{n.x=.5-(n.x-.5)}),r.flipY&&i.forEach(n=>{n.y=.5-(n.y-.5)}),i.forEach(n=>{t.push(I0t(r,n))})}if(!t.length&&!r.type&&!r.calculative.canvas.parent.isCombine(r)){const{x:i,y:n,width:s,height:a}=r.calculative.worldRect;t=e.options.defaultAnchors.map((o,l)=>({id:`${l}`,penId:r.id,x:i+s*o.x,y:n+a*o.y}))}r.calculative.rotate&&t.forEach(i=>{fo(i,r.calculative.rotate,r.calculative.worldRect.pivot||r.calculative.worldRect.center)}),(!r.type||r.anchors)&&(r.calculative.worldAnchors=t),r.calculative.activeAnchor&&t.length&&(r.calculative.activeAnchor=t.find(i=>{i.id,r.calculative.activeAnchor.id})),r.calculative.gradientAnimatePath=void 0}function mFe(r){var e;if((e=r.children)!=null&&e.length){let t=r.calculative.worldRect;r.children.forEach(i=>{const n=r.calculative.canvas.store.pens[i];n.calculative.initRect&&n.calculative.initRelativeRect&&(n.calculative.initRect.x=t.x+t.width*n.calculative.initRelativeRect.x,n.calculative.initRect.y=t.y+t.height*n.calculative.initRelativeRect.y,n.calculative.initRect.ex=n.calculative.initRect.x+t.width*n.calculative.initRelativeRect.width,n.calculative.initRect.ey=n.calculative.initRect.y+t.height+n.calculative.initRelativeRect.height,Tl(n.calculative.initRect)),mFe(n)})}}function I0t(r,e){const t={...e},{x:i,y:n,width:s,height:a}=r.calculative.worldRect;return t.x=i+s*e.x,t.y=n+a*e.y,e.prev&&(t.prev={penId:r.id,connectTo:e.prev.connectTo,x:i+s*e.prev.x,y:n+a*e.prev.y}),e.next&&(t.next={penId:r.id,connectTo:e.next.connectTo,x:i+s*e.next.x,y:n+a*e.next.y}),t}function eTe(r,e){const{paddingTop:t,paddingBottom:i,paddingLeft:n,paddingRight:s}=e.calculative;let a=n,o=t,l=e.calculative.worldRect.width-n-s,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=r[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},Yl(e.calculative.worldIconRect),Tl(e.calculative.worldIconRect)}function TI(r,e,t){Wk(r.calculative.worldRect,e,t,r.pivot),r.calculative.initRect&&Wk(r.calculative.initRect,e,t,r.pivot),gFe(r,e,t),r.calculative.x&&tZ(r.calculative,e,t),r.type&&K9(r)}function gFe(r,e,t){var i;r&&(i=r.children)!=null&&i.length&&r.children.forEach(n=>{const s=r.calculative.canvas.store.pens[n];s&&(s.calculative.initRect&&Wk(s.calculative.initRect,e,t),gFe(s,e,t))})}function P0t(r,e){r.anchors||(r.anchors=[]),r.calculative.worldAnchors||(r.calculative.worldAnchors=[]);const t={id:e.id,penId:r.id,x:e.x,y:e.y};if(r.calculative.worldAnchors.push(t),r.calculative.worldRect){r.rotate%360&&fo(e,-r.rotate,r.calculative.worldRect.center);const i={id:e.id,penId:r.id,x:(e.x-r.calculative.worldRect.x)/r.calculative.worldRect.width,y:(e.y-r.calculative.worldRect.y)/r.calculative.worldRect.height};r.anchors.push(i)}return t}function w0t(r,e,t){r.anchors||(r.anchors=[]),r.calculative.worldAnchors||(r.calculative.worldAnchors=[]);const i=Rmt(r,e,t);return r.calculative.worldAnchors.splice(t+1,0,i),r.anchors.splice(t+1,0,H9(i,r.calculative.worldRect)),r.calculative.activeAnchor=i,i}function D0t(r,e){if(!r||!r.calculative.worldAnchors)return;let t=r.calculative.worldAnchors.findIndex(i=>i.id===e.id);t>-1&&r.calculative.worldAnchors.splice(t,1),t=r.anchors.findIndex(i=>i.id===e.id),t>-1&&r.anchors.splice(t,1)}function tw(r,e){if(!e||!e.calculative||!e.calculative.worldRect.center)return Un.None;if(r.anchorId){let t=e.anchors.filter(i=>i.id===r.anchorId);if(t.length&&t[0].direction>-1)return t[0].direction}return Npt(r,e.calculative.worldRect.center)}function SP(r,e){let t=1/0,i;return r.calculative.worldAnchors.forEach(n=>{const s=IJ(e,n);t>s&&(t=s,i=n)}),i}function tTe(r,e,t){r.x+=e,r.y+=t,r.anchors&&r.anchors.forEach(i=>{G9(i,e,t)}),r.calculative.worldAnchors&&r.calculative.worldAnchors.forEach(i=>{G9(i,e,t)})}function kge(r){if(r&&r.calculative&&r.calculative.worldAnchors.length){let e=na(r);if(!r.anchors||!r.anchors.length)for(;r.calculative.worldAnchors.length&&e!==r.calculative.activeAnchor;)r.calculative.worldAnchors.pop(),e=na(r);else e===r.calculative.activeAnchor?r.calculative.worldAnchors=[r.calculative.worldAnchors[0]]:r.calculative.worldAnchors[0]===r.calculative.activeAnchor&&(r.calculative.worldAnchors=[r.calculative.worldAnchors[r.calculative.worldAnchors.length-1]])}}function Du(r,e,t,i){var o,l,c,u,h,d;if(!r||!e||!t||!i||e.twoWay===ch.DisableConnected||e.twoWay===ch.Disable||i.twoWay===ch.DisableConnectTo||i.twoWay===ch.Disable)return;if(e.twoWay===ch.In){if(t.calculative.worldAnchors.length===1)return;const f=na(t);if(i.id!==f.id)return}if(e.twoWay===ch.Out){const f=Wl(t);if(i.id!==f.id)return}if(i.connectTo===r.id&&i.anchorId===e.id)return;if(i.connectTo){const f=r.calculative.canvas.store.pens[i.connectTo];EP(f,oS(f,i.anchorId),t,i)}r.connectedLines||(r.connectedLines=[]),r.connectedLines.findIndex(f=>f.lineId===t.id&&f.lineAnchor===i.id&&f.anchor===e.id)<0&&r.connectedLines.push({lineId:t.id,lineAnchor:i.id,anchor:e.id}),i.connectTo=r.id,i.anchorId=e.id,r.type&&Du(t,i,r,e),r.calculative.canvas.store.emitter.emit("connectLine",{line:t,lineAnchor:i,pen:r,anchor:e});let s=((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=r.onConnectLine)==null||d.call(r,r,{line:t,lineAnchor:i,pen:r,anchor:e,fromPen:s,fromAnchor:a}),!0}function EP(r,e,t,i){if(!(!r||!e||!t||!i)&&!(!r.connectedLines||!r.connectedLines.length))return t.lastConnected||(t.lastConnected={}),t.lastConnected[r.id]||(t.lastConnected[r.id]=Zt(r.connectedLines)),r.connectedLines.forEach((n,s,a)=>{(n.lineId===t.id||n.lineId===t.id)&&n.lineAnchor===i.id&&n.anchor===e.id&&a.splice(s,1)}),i.connectTo=void 0,i.anchorId=void 0,r.type&&e.connectTo===t.id&&e.anchorId===i.id&&EP(t,i,r,e),r.calculative.canvas.store.emitter.emit("disconnectLine",{line:t,lineAnchor:i,pen:r,anchor:e}),!0}function oS(r,e){var t;if(!(!r||!e))return(t=r.calculative.worldAnchors)==null?void 0:t.find(i=>i.id===e)}function Wl(r){if(!(!r||!r.calculative.worldAnchors))return r.calculative.worldAnchors[0]}function na(r){if(!(!r||!r.calculative.worldAnchors))return r.calculative.worldAnchors[r.calculative.worldAnchors.length-1]}function O0t(r,e){var i,n;if(r.calculative.start===0||!r.frames||!r.frames.length)return r.calculative.start=void 0,0;if(!r.calculative.duration){r.calculative.duration=0;for(const s of r.frames){r.calculative.duration+=s.duration;for(const a in s)a!=="duration"&&!r[a]&&a==="scale"&&(r[a]=1)}}if(r.animateCycle||(r.animateCycle=1/0),r.calculative.start){let s=0;const a=Math.ceil((e-r.calculative.start)/r.calculative.duration);if(a>r.animateCycle)return r.currentAnimation=void 0,r.calculative.start=void 0,rTe(r,1),0;const o=(e-r.calculative.start)%r.calculative.duration;let l=0;for(const h of r.frames)if(l+=h.duration,o>l)++s;else break;if(!r.frames[s])return!0;r.calculative.frameDuration=r.frames[s].duration,r.calculative.frameStart=r.calculative.start+r.calculative.duration*(a-1),r.calculative.frameEnd=r.calculative.frameStart+r.calculative.frameDuration;const c=s!==r.calculative.frameIndex,u=a>r.calculative.cycleIndex;if(c&&(r.calculative.frameIndex=s),u&&(r.calculative.cycleIndex=a),c||u)if(r.calculative.x=r.calculative.initRect.x,r.calculative.y=r.calculative.initRect.y,(n=r.children)!=null&&n.length&&!r.parentId?r.calculative.canvas.rotatePen(r,(r.calculative.initRect.rotate||0)-(r.calculative.rotate||0),r.calculative.initRect):r.calculative.rotate=r.calculative.initRect.rotate||0,s>0){r.prevFrame={};const h=r.frames[s-1];for(const d in h)r.prevFrame[d]=h[d];Object.assign(r.prevFrame,{rotate:h.rotate||0,x:h.x||0,y:h.y||0,scale:h.scale||1})}else iTe(r)}else{if(r.calculative.start=e,r.calculative.frameIndex=0,r.calculative.frameStart=r.calculative.start,r.calculative.frameDuration=r.frames[0].duration,r.calculative.frameEnd=r.calculative.frameStart+r.calculative.frameDuration,r.calculative.cycleIndex=1,r.calculative.x=r.calculative.worldRect.x,r.calculative.y=r.calculative.worldRect.y,r.calculative.initRect=Zt(r.calculative.worldRect),r.parentId&&(r.calculative.initRelativeRect={x:r.x,y:r.y,width:r.width,height:r.height}),(i=r.children)!=null&&i.length){const s=r.calculative.canvas.store;r.calculative.childrenVisible={},r.children.forEach(a=>{r.calculative.childrenVisible[a]=s.pens[a].visible})}r.calculative.initRect.rotate=r.calculative.rotate||0,iTe(r)}const t=(e-r.calculative.frameStart)/r.calculative.frameDuration%1;return rTe(r,t),!0}function iTe(r){r.prevFrame={};for(const e in r)(typeof r[e]!="object"||e==="lineDash")&&(r.prevFrame[e]=r[e]);r.prevFrame.rotate=0,r.prevFrame.x=0,r.prevFrame.y=0,r.prevFrame.scale=1}function rTe(r,e){var i,n;if(e<0)return;e>1&&(e=1);const t=r.frames[r.calculative.frameIndex];for(const s in t)if(s!=="duration"){if(s==="scale"){r.calculative.worldRect=Zt(r.calculative.initRect),Wk(r.calculative.worldRect,r.prevFrame.scale,r.calculative.worldRect.center);const a=r.prevFrame.scale+(t[s]-r.prevFrame.scale)*e;Wk(r.calculative.worldRect,a/r.prevFrame.scale,r.calculative.worldRect.center),r.calculative.patchFlags=!0}else if(s==="x"){const a=gse(r,s,r.calculative.frameIndex);r.calculative.worldRect.x=r.calculative.initRect.x+a,r.calculative.worldRect.ex=r.calculative.initRect.ex+a,_S(r.calculative.worldRect,t[s]*e*r.calculative.canvas.store.data.scale,0),r.calculative.patchFlags=!0}else if(s==="y"){const a=gse(r,s,r.calculative.frameIndex);r.calculative.worldRect.y=r.calculative.initRect.y+a,r.calculative.worldRect.ey=r.calculative.initRect.ey+a,_S(r.calculative.worldRect,0,t[s]*e*r.calculative.canvas.store.data.scale),r.calculative.patchFlags=!0}else if(s==="rotate"){r.prevFrame[s]>=360&&(r.prevFrame[s]%=360);const a=gse(r,s,r.calculative.frameIndex),o=(r.calculative.initRect.rotate+a+t[s]*e)%360-(r.calculative.rotate||0);(i=r.children)!=null&&i.length?r.calculative.canvas.rotatePen(r,o,r.calculative.initRect):r.calculative.rotate=(r.calculative.initRect.rotate+a+t[s]*e)%360,r.calculative.patchFlags=!0}else if(s==="image")r.image=t.image,r.calculative.image=void 0,r.calculative.canvas.loadImage(r),r.canvasLayer===Rs.CanvasImageBottom?r.calculative.canvas.canvasImageBottom.init():r.canvasLayer===Rs.CanvasImage&&r.calculative.canvas.canvasImage.init();else if(L0t(t[s],s,r)){r.prevFrame[s]==null&&(s==="globalAlpha"?r.prevFrame[s]=1:r.prevFrame[s]=0);const a=r.prevFrame[s]+(t[s]-r.prevFrame[s])*e;r.calculative[s]=Math.round(a*100)/100}else{if(s==="visible"){if(r.calculative.image)r.canvasLayer===Rs.CanvasImageBottom?r.calculative.canvas.canvasImageBottom.init():r.canvasLayer===Rs.CanvasImage&&r.calculative.canvas.canvasImage.init();else if((n=r.children)!=null&&n.length){const o=j1(r,r.calculative.canvas.store);r.calculative.canvas.initImageCanvas(o)}}r.calculative[s]=t[s];const a={};a[s]=t[s],Uge(r,a)}s==="text"&&xz(r)}}function L0t(r,e,t){const i=["strokeType","bkType","showChild"];return typeof r=="number"&&t.linear!==!1&&!i.includes(e)}function N0t(r,e){if(r.calculative.start===0)return r.calculative.start=void 0,0;if(r.animateCycle||(r.animateCycle=1/0),r.animateSpan||(r.animateSpan=1),r.calculative.animatePos+=r.animateSpan*(r.calculative.canvas.store.data.scale||1),!r.calculative.start)r.calculative.start=Date.now(),r.calculative.animatePos=r.animateSpan*(r.calculative.canvas.store.data.scale||1),r.calculative.cycleIndex=1;else if(r.calculative.animatePos>r.length){if(++r.calculative.cycleIndex,r.calculative.cycleIndex>r.animateCycle)return r.currentAnimation=void 0,r.calculative.start=void 0,0;r.calculative.animatePos=r.animateSpan}return!0}function gP(r,e=!0){if(!r.children||r.childActive===!1)return;const t=r.calculative.canvas.store;r.children.forEach(i=>{const n=t.pens[i];n&&(n.calculative.active=e,gP(n,e))})}function x9(r,e=!0){if(!r)return;const t=r.calculative.canvas.store;r.calculative.hover=e,r.childHover!==!1&&r.children&&r.children.forEach(i=>{var n,s;((n=t.pens[i])==null?void 0:n.hoverColor)==null&&((s=t.pens[i])==null?void 0:s.hoverBackground)==null&&x9(t.pens[i],e)})}function Po(r,e){if(!e)return;const t=r.calculative.canvas.store,i=r.calculative.worldRect;e.style.opacity=r.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=r.calculative.inView!=!1?r.calculative.cssDisplay||"inline":"none",!r.calculative.rotate&&(r.calculative.rotate=0),e.style.transform=`rotate(${r.calculative.rotate}deg)`,r.calculative.rotate||(r.calculative.flipX&&(e.style.transform="rotateY(180deg)"),r.calculative.flipY&&(e.style.transform="rotateX(180deg)"),r.calculative.flipX&&r.calculative.flipY&&(e.style.transform="rotateZ(180deg)")),e.style.zIndex=r.calculative.zIndex!==void 0?r.calculative.zIndex+"":"5",r.calculative.zIndex>r.calculative.canvas.maxZindex&&(r.calculative.canvas.maxZindex=r.calculative.zIndex),r.locked===Ss.DisableEdit||r.locked===Ss.DisableMove||t.data.locked?(e.style.userSelect="initial",e.style.pointerEvents="initial",r.name==="gif"&&(e.style.userSelect="none",e.style.pointerEvents="none")):(e.style.userSelect="none",e.style.pointerEvents="none")}function mse(r){return r.every(e=>e.locked)}function nTe(r){return r.every(e=>e.disableRotate)}function _Fe(r,e,t){var i;r.type?(r.calculative.worldAnchors.forEach(n=>{fo(n,e,t.center)}),F0t(r),$Y(r)):(r.calculative.rotate?r.calculative.rotate+=e:r.calculative.rotate=e,fo(r.calculative.worldRect.center,e,t.center),r.parentId&&(r.calculative.worldRect.x=r.calculative.worldRect.center.x-r.calculative.worldRect.width/2,r.calculative.worldRect.y=r.calculative.worldRect.center.y-r.calculative.worldRect.height/2,r.x=(r.calculative.worldRect.x-t.x)/t.width,r.y=(r.calculative.worldRect.y-t.y)/t.height)),(i=r.children)==null||i.forEach(n=>{const s=r.calculative.canvas.store.pens[n];_Fe(s,e,t)})}function F0t(r){var n;if(!((n=r.calculative.worldAnchors)!=null&&n.length)||!isFinite(r.x)||!isFinite(r.x)||r.x==null||r.y==null)return;const e=Sue(r);r.parentId||Object.assign(r,e);const{fontSize:t,lineHeight:i}=r.calculative.canvas.store.options;r.fontSize?r.fontSize<0&&(r.fontSize=0,r.calculative.fontSize=0):(r.fontSize=t>=0?t:12,r.calculative.fontSize=r.fontSize*r.calculative.canvas.store.data.scale),r.lineHeight||(r.lineHeight=i,r.calculative.lineHeight=r.lineHeight),Tl(e),r.calculative.worldRect=e,Bge(r,e),t_(r),r.calculative.worldAnchors&&(r.anchors=r.calculative.worldAnchors.map(s=>H9(s,r.calculative.worldRect)))}function sTe(r){return r.every(e=>e.disableSize||e.pivot)}function gse(r,e,t){if(!r.frames||!e)return 0;let i=0;for(let n=0;n{const o=t.pens[a];o&&Ev(o,!0)})),r.calculative.inView=!0,!nZ(r,t)||r.visible==!1||r.calculative.visible==!1)r.calculative.inView=!1;else{const{x:a,y:o,width:l,height:c,rotate:u}=r.calculative.worldRect,h={x:a+t.data.x,y:o+t.data.y,width:l,height:c,rotate:u};Yl(h),Jy(h,i)||(r.calculative.inView=!1)}(s=r.calculative.singleton)!=null&&s.div&&Po(r,r.calculative.singleton.div)}function B0t(r,e,t){if(e.fillWorldTextRect){r.save(),r.fillStyle="#c3deb7";const{x:i,y:n,width:s,height:a}=t.calculative.worldTextRect;r.fillRect(i,n,s,a),r.restore()}}function wS(r,e){const t=e.calculative.globalAlpha;typeof t=="number"&&t<1&&!isNaN(t)&&(r.globalAlpha=t)}function vFe(r,e){const t=k0t(r,e)||un.canvasDraws[e.name];t&&(r.save(),t(r,e),r.restore())}function k0t(r,e){const t=e.drawCommand;if(!(!t||e.name==="line"))return(i,n)=>{t.forEach(s=>{try{s.steps=s.steps.flat(1/0),s.steps.reduce((a,o)=>{const l=U0t(o,n,a.x,a.y);try{if(l.c){if(l.c.startsWith("_")){const u=l.c.split("_")[1];return(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),i.moveTo(l.startX||l.v.x,l.startY||l.v.y),{x:l.startX||l.v.x,y:l.startY||l.v.y}}return{x:a.x,y:a.y}}catch(c){console.log(c,"error",l)}},{})}catch{}}),i.stroke()}}function U0t(r,e,t,i){return{visio:V0t,dxf:z0t}[e.parseType](r,e,t,i)}function z0t(r,e,t,i){const{x:n,y:s,width:a,height:o}=e.calculative.worldRect,{originWidth:l,originHeight:c}=e.dxfOrigin;switch(r.c){case"beginPath":return{c:"beginPath",v:{}};case"closePath":return{c:"closePath",v:{}};case"moveTo":return{c:"moveTo",v:{x:r.v.x*(a/l)+n,y:r.v.y*(o/c)+s}};case"lineTo":return{c:"lineTo",v:{x:r.v.x*(a/l)+n,y:r.v.y*(o/c)+s}};case"arc":return{c:"ellipse",v:{x:r.v.x*(a/l)+n,y:r.v.y*(o/c)+s,rx:r.v.xr*(a/l),ry:r.v.yr*(o/c),rotation:r.v.rotation||0,startAngle:r.v.startAngle,endAngle:r.v.endAngle,a:r.v.aclockwise??!0}};case"ellipse":return{c:"ellipse",v:{x:r.v.x*(a/l)+n,y:r.v.y*(o/c)+s,rx:r.v.xr*(a/l),ry:r.v.yr*(o/c),rotation:r.v.rotation||0,startAngle:r.v.startAngle,endAngle:r.v.endAngle,a:r.v.aclockwise??!0}};case"_font":const u=e.calculative.canvas.store;return{c:"_font",v:{value:r.v.fontSize*u.data.scale+"px "+(r.v.fontFamily||u.options.fontFamily)}};case"_fillStyle":return{c:"_fillStyle",v:{value:e.color||r.v.value}};default:const h={c:r.c,v:{...r.v,x:r.v.x*(a/l)+n,y:r.v.y*(o/c)+s}};return!r.v.x&&delete h.v.x,!r.v.y&&delete h.v.y,h}}function V0t(r,e,t,i){const{x:n,y:s,width:a,height:o}=e.calculative.worldRect,{width:l,height:c}=e.origin;switch(r.c){case"MoveTo":return{c:"moveTo",v:{x:+r.v.X*100*(a/l)+n,y:+r.v.Y*100*(o/c)+s}};case"RelMoveTo":return{c:"moveTo",v:{x:+r.v.X*l*(a/l)+n,y:+r.v.Y*c*(o/c)+s}};case"LineTo":return{c:"lineTo",v:{x:+r.v.X*100*(a/l)+n,y:+r.v.Y*100*(o/c)+s}};case"RelLineTo":return{c:"lineTo",v:{x:+r.v.X*l*(a/l)+n,y:+r.v.Y*c*(o/c)+s}};case"Ellipse":let u=r.v.X,h=r.v.Y,d=Math.abs(r.v.A-r.v.C),f=Math.abs(r.v.B-r.v.D);return{c:"ellipse",v:{x:u*100*(a/l)+n,y:h*100*(o/c)+s,radiuX:d*100*(a/l),radiuY:f*100*(o/c),rotation:0,startAngle:0,endAngle:Math.PI*2,anticlockwise:!0}};case"EllipticalArcTo":const p=r.v.X*100*(a/l)+n,g=r.v.Y*100*(o/c)+s,m=r.v.A*100*(a/l)+n,_=r.v.B*100*(o/c)+s,y=r.v.C,v=r.v.D*(a/o)*(c/l),x=G0t(t,i,p,g,m,_,v);return!r.orign&&(r.orign={}),!r.orign.startA&&(r.orign.startA=aTe(x.x0,x.y0,t,i)),!r.orign.endA&&(r.orign.endA=aTe(x.x0,x.y0,p,g)),{c:"ellipse",v:{centerX:x.x0,centerY:x.y0,radiuX:x.a,radiuY:x.b,rotation:0,startAngle:r.orign.startA,endAngle:r.orign.endA,anticlockwise:+y<0},startX:p,startY:g};case"ArcTo":let b=r.v.X*100*a/l+n,C=r.v.Y*100*o/c+s,A=r.v.A*100*(a/o)*(c/l),E=(t+b)/2,P=(i+C)/2,w=Math.sqrt((b-t)**2+(C-i)**2),M=w**2/(8*A)+A/2,R=-(C-i)/w,I=(b-t)/w,D=E+R*M,k=P+I*M,z=D,W=k,K=Math.atan2(i-W,t-z),U=Math.atan2(C-W,b-z);return{c:"arc",v:{x:z,y:W,radius:M,startAngle:K,endAngle:U,aclockwise:!0}};default:return{}}}function Uge(r,e){for(const t in e)ZNe.includes(t)&&(t=="fontSize"&&e[t]<0&&(e[t]=0),r[t]=e[t],["fontSize","lineWidth"].includes(t)?(r.calculative[t]=e[t]*r.calculative.canvas.store.data.scale,t_(r)):r.calculative[t]=e[t]);if(r.calculative.canvas.parent.isCombine(r)){const t=r.children;t==null||t.forEach(i=>{let n=Zt(e);r.calculative.childrenVisible&&r.calculative.childrenVisible[i]===!1&&delete n.visible;const s=r.calculative.canvas.store.pens[i];s&&Uge(s,n)})}}function G0t(r,e,t,i,n,s,a){let o=(r-t)*(r+t)*(i-s)-(t-n)*(t+n)*(e-i)+a*a*(e-i)*(i-s)*(e-s),l=2*((r-t)*(i-s)-(t-n)*(e-i)),c=o/l,u=(r-t)*(t-n)*(r-n)+a*a*((t-n)*(e-i)*(e+i)-(r-t)*(i-s)*(i+s)),h=2*a*a*((t-n)*(e-i)-(r-t)*(i-s)),d=u/h,f=Math.sqrt(Math.pow(r-c,2)+Math.pow(a*(e-d),2)),p=f/a;return{x0:c,y0:d,a:f,b:p}}function aTe(r,e,t,i){let n=t-r,s=i-e,a=Math.atan2(s,n);return a<0&&(a+=2*Math.PI),a}function oTe(r,e,t){let i,n,s=1/0,a=1/0;const o=8;for(const l of r.data.pens){if(l.calculative.inView===!1)continue;zge(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{s.x+=i.x,s.y+=i.y})):(Tl(e),n=[e.center,...Wv(e)]),yFe(r,n,e,!0)}function zge(r){if(r.type){if(r.type===sa.Line)return r.calculative.worldAnchors}else{const e=Wv(r.calculative.worldRect);return Tl(r.calculative.worldRect),[...r.calculative.worldAnchors,...e,r.calculative.worldRect.center]}}function K0t(r,e,t,i){const n=Wv(e);return yFe(r,n,e)}function yFe(r,e,t,i=!1){let n,s,a=1/0,o=1/0;const l=10,c=Q0t(t,l);return r.data.pens.forEach(u=>{const{inView:h,worldRect:d,active:f}=u.calculative;if(h===!1||!i&&f||Y0t(c,d)||u.type&&r.active.some(g=>xFe(r,g,u)))return;const p=zge(u);if(p)for(const g of p)for(const m of e){const _=g.x-m.x,y=g.y-m.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)?r=e.get(t):e.set(t,r=new Map),typeof n!="function")return()=>{console.warn("[rewritePenLifeCycle] warn: not a function ")};let a=new Set,o=new Map;r.has(i)&&r.get(i)?a=r.get(i):(o.set(i,t[i]),r.set(i,a)),s?a.delete(n):a.add(n);let l=o.get(i),c=(...u)=>{l==null||l(...u),a.forEach(h=>{h(...u)})};t[i]=c}}let j0t=H0t();function $0t(r){return!r.name&&!r.install?(console.error("installPenPlugin Error: Validation Failed"),!1):!0}function Ny(r,e){if(!e)return;if(e.ex==null&&Yl(e),!e.rotate||e.rotate%360===0)return r.x>e.x&&r.xe.y&&r.y{fo(i,e.rotate,e.pivot||e.center)}),X0t(r,t)}function DS(r,e,t=0){const{x:i,y:n,ex:s,ey:a}=e;return r.x>=i-t&&r.x<=s+t&&r.y>=n-t&&r.y<=a+t}function Tl(r){r.center||(r.center={}),r.center.x=r.x+r.width/2,r.center.y=r.y+r.height/2}function Yl(r){r.ex=r.x+r.width,r.ey=r.y+r.height}function bue(r,e){r.pivot||(r.pivot={}),r.pivot.x=r.x+r.width*e.x,r.pivot.y=r.y+r.height*e.y}function X0t(r,e){if(e.length<3)return!1;let t=!1,i=e[e.length-1];for(const n of e)i.y>r.y!=n.y>r.y&&n.x+(r.y-n.y)*(i.x-n.x)/(i.y-n.y)>r.x&&(t=!t),i=n;return t}function u_(r){const e=[];r.forEach(i=>{if(i.isRuleLine)return;const n=i.calculative.worldRect;if(n){const s=Wv(n);e.push(...s)}});const t=bz(e);return Tl(t),t}function Wv(r){const e=[{x:r.x,y:r.y},{x:r.ex,y:r.y},{x:r.ex,y:r.ey},{x:r.x,y:r.ey}];return r.rotate&&(r.center||Tl(r),e.forEach(t=>{fo(t,r.rotate,r.pivot||r.center)})),e}function bz(r){let e=1/0,t=1/0,i=-1/0,n=-1/0;return r==null||r.forEach(s=>{!isFinite(s.x)||!isFinite(s.y)||(e=Math.min(e,s.x),t=Math.min(t,s.y),i=Math.max(i,s.x),n=Math.max(n,s.y))}),{x:e,y:t,ex:i,ey:n,width:i-e,height:n-t}}function Jy(r,e,t){return r.rotate&&(r=bz(Wv(r))),t?r.x>e.x&&r.exe.y&&r.eye.ex||r.exe.ey)}function Y0t(r,e){return(e.x>r.ex||e.exr.ey||e.eyr.y!=l>r.y&&r.x<(o-s)*(r.y-a)/(l-a)+s&&(t=!t)}return t}const emt=/^[\t\n\f\r ]*([MLHVZCSQTAmlhvzcsqta])[\t\n\f\r ]*/,uTe=/^[01]/,Eo=/^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/,tmt=/^(([\t\n\f\r ]+,?[\t\n\f\r ]*)|(,[\t\n\f\r ]*))/,imt={M:[Eo,Eo],L:[Eo,Eo],H:[Eo],V:[Eo],Z:[],C:[Eo,Eo,Eo,Eo,Eo,Eo],S:[Eo,Eo,Eo,Eo],Q:[Eo,Eo,Eo,Eo],T:[Eo,Eo],A:[Eo,Eo,Eo,uTe,uTe,Eo,Eo]};function rmt(r){let e=0;const t=[];for(;e{s.worldPoints.forEach((a,o)=>{o%2===0?(ai&&(i=a)):(an&&(n=a))})}),--e,--t,{x:e,y:t,ex:i,ey:n,width:i-e+1,height:n-t+1}}function nmt(r,e,t){t==null&&(t=e),r.commands.forEach((i,n)=>{if(!(i.relative&&n))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((s,a)=>{i.values[a]=s+(a%2===0?e:t)});break}})}function smt(r,e,t){t==null&&(t=e),r.commands.forEach(i=>{switch(i.key){case"A":case"a":const n=i.values[0],s=i.values[1],a=Math.PI*i.values[2]/180,o=Math.cos(a),l=Math.sin(a),c=s*s*t*t*o*o+n*n*t*t*l*l,u=2*e*t*o*l*(s*s-n*n),h=n*n*e*e*o*o+s*s*e*e*l*l,d=-(n*n*s*s*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((g,m)=>{i.values[m]=g*(m%2===0?e:t)});break}})}function amt(r){let e="";return r.commands.forEach(t=>{e+=t.key+" ",t.values.forEach(i=>{e+=i+" "})}),e}function omt(r,e,t){const i=imt[r.toUpperCase()],n=[];for(;t<=e.length;){const s={key:r,values:[]};for(const a of i){const o=e.slice(t).match(a);if(o!==null){s.values.push(+o[0]),t+=o[0].length;const l=e.slice(t).match(tmt);l!==null&&(t+=l[0].length)}else{if(s.values.length===0)return{cursor:t,commands:n};throw new Error("malformed path (first error at "+t+")")}}if(s.relative=s.key.toUpperCase()!==s.key,n.push(s),i.length===0)return{cursor:t,commands:n};r==="m"&&(r="l"),r==="M"&&(r="L")}throw new Error("malformed path (first error at "+t+")")}function lmt(r,e){const t=[];let i=r.relative&&e?{x:e.worldPoints[e.worldPoints.length-2],y:e.worldPoints[e.worldPoints.length-1]}:{x:0,y:0};for(let n=0;n{switch(n.key){case"Z":case"z":n.worldPoints=[t,i];break;case"H":n.worldPoints=[n.values[0],e.worldPoints[e.worldPoints.length-1]];break;case"h":n.worldPoints=[n.values[0]+e.worldPoints[e.worldPoints.length-2],e.worldPoints[e.worldPoints.length-1]];break;case"V":n.worldPoints=[e.worldPoints[e.worldPoints.length-2],n.values[0]];break;case"v":n.worldPoints=[e.worldPoints[e.worldPoints.length-2],n.values[0]+e.worldPoints[e.worldPoints.length-1]];break;case"A":n.worldPoints=[e.worldPoints[e.worldPoints.length-2],n.values[0]+e.worldPoints[e.worldPoints.length-1]];break;default:lmt(n,e);break}(n.key==="M"||n.key==="m"||n.key==="Z"||n.key==="z")&&(t=n.worldPoints[n.worldPoints.length-2],i=n.worldPoints[n.worldPoints.length-1]),e=n})}function umt(r,e){var l;const i=r.calculative.canvas.store.data.paths[r.pathId];if(!i)return new Path2D;const n=rmt(i);r.calculative.svgRect=hTe(n),Tl(r.calculative.svgRect),(r.calculative.svgRect.width!==r.calculative.worldRect.width||r.calculative.svgRect.height!==r.calculative.worldRect.height)&&smt(n,r.calculative.worldRect.width/r.calculative.svgRect.width,r.calculative.worldRect.height/r.calculative.svgRect.height);const s=hTe(n);Tl(s),nmt(n,r.calculative.worldRect.x-s.x,r.calculative.worldRect.y-s.y);const a=amt(n);if(e){(l=e.svgPath)==null||l.call(e,a);return}return new Path2D(a)}function hmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i+s/2,n),t.lineTo(i+s,n+a/2),t.lineTo(i+s/2,n+a),t.lineTo(i,n+a/2),t.lineTo(i+s/2,n),t.closePath(),t instanceof Path2D)return t}function dmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i+s/2,n),t.lineTo(i+s,n+a),t.lineTo(i,n+a),t.lineTo(i+s/2,n),t.closePath(),t instanceof Path2D)return t}function fmt(r){const e=[{x:.5,y:0},{x:.75,y:.5},{x:.5,y:1},{x:.25,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function pmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i+s/2,n),t.lineTo(i+s,n+a*2/5),t.lineTo(i+s*4/5,n+a),t.lineTo(i+s/5,n+a),t.lineTo(i,n+a*2/5),t.closePath(),t instanceof Path2D)return t}function mmt(r){const e=[{x:.5,y:0},{x:1,y:.4},{x:.8,y:1},{x:.2,y:1},{x:0,y:.4}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function gmt(r,e){r.onResize||(r.onResize=_mt);const t=e||new Path2D,{width:i,height:n,center:s}=r.calculative.worldRect,a=i>n?n:i,o=s.x,l=s.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 bFe(r){const{width:e,height:t}=r,i=e>t?t:e,n=[];for(let s=0;s<5;++s)n.push({flag:1,id:String(s),penId:r.id,x:.5+i/2*Math.sin(Math.PI/180*72*s)/e,y:-i/2*Math.cos(Math.PI/180*72*s)/t+.5});r.anchors=n}function _mt(r){const e=r.anchors.filter(t=>t.flag!==1);bFe(r),r.anchors=r.anchors.concat(...e)}function vmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i+s/4,n),t.lineTo(i+s*3/4,n),t.lineTo(i+s,n+a/2),t.lineTo(i+s*3/4,n+a),t.lineTo(i+s*1/4,n+a),t.lineTo(i,n+a/2),t.lineTo(i+s/4,n),t.closePath(),t instanceof Path2D)return t}function ymt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i,n+a/2),t.lineTo(i+a/2,n),t.lineTo(i+a/2,n+a/3),t.lineTo(i+s,n+a/3),t.lineTo(i+s,n+a*2/3),t.lineTo(i+a/2,n+a*2/3),t.lineTo(i+a/2,n+a*2/3),t.lineTo(i+a/2,n+a),t.closePath(),t instanceof Path2D)return t}function xmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i,n+a/3),t.lineTo(i+(s-a/2),n+a/3),t.lineTo(i+(s-a/2),n),t.lineTo(i+s,n+a/2),t.lineTo(i+(s-a/2),n+a),t.lineTo(i+(s-a/2),n+a*2/3),t.lineTo(i,n+a*2/3),t.closePath(),t instanceof Path2D)return t}function bmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i,n+a/2),t.lineTo(i+a/2,n),t.lineTo(i+a/2,n+a/3),t.lineTo(i+(s-a/2),n+a/3),t.lineTo(i+(s-a/2),n),t.lineTo(i+s,n+a/2),t.lineTo(i+(s-a/2),n+a),t.lineTo(i+(s-a/2),n+a*2/3),t.lineTo(i+a/2,n+a*2/3),t.lineTo(i+a/2,n+a),t.closePath(),t instanceof Path2D)return t}function Cmt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a,ey:o}=r.calculative.worldRect;if(t.moveTo(i,n),t.lineTo(i+s,n),t.lineTo(i+s,n+a*3/4),t.lineTo(i+s*8/16,n+a*3/4),t.lineTo(i+s/4,o),t.lineTo(i+s*5/16,n+a*3/4),t.lineTo(i,n+a*3/4),t.closePath(),t instanceof Path2D)return t}function Amt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.moveTo(i+s/5,n+a*13/16),t.bezierCurveTo(i-s/15,n+a*13/16,i-s/15,n+a*7/16,i+s/5,n+a*7/16),t.bezierCurveTo(i+s/5,n,i+s*4/5,n,i+s*4/5,n+a*7/16),t.bezierCurveTo(i+s*16/15,n+a*7/16,i+s*16/15,n+a*13/16,i+s*4/5,n+a*13/16),t.closePath(),t instanceof Path2D)return t}function Smt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ex:a,ey:o}=r.calculative.worldRect,l=s/6;if(t.moveTo(i,n),t.lineTo(a-l,n),t.lineTo(a,n+l),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t.moveTo(a-l,n),t.lineTo(a-l,n+l),t.lineTo(a,n+l),t.closePath(),t instanceof Path2D)return t}function Emt(r,e){const{x:t,y:i,width:n,ex:s,ey:a}=e.calculative.worldRect;let o=n*.25;const l=e.z;l>1?o=l:l>0&&(o=n*l);const c={x:t,y:i+o},u={x:s-o,y:i+o},h={x:s-o,y:a};_se(r,[c,u,h,{x:t,y:a}],e.backgroundFront||e.background,e.color),_se(r,[c,{x:t+o,y:i},{x:s,y:i},u],e.backgroundUp||e.background,e.color),_se(r,[u,{x:s,y:i},{x:s,y:a-o},h],e.backgroundRight||e.background,e.color)}function _se(r,e,t="",i=""){r.save(),t&&(r.fillStyle=t),i&&(r.strokeStyle=i),r.beginPath();for(let n=0;ni.x?o=Un.Right:o=Un.Left),i.next={id:rs(),penId:e.id,x:i.x,y:i.y,prevNextType:2},n.prev={id:rs(),penId:e.id,x:n.x,y:n.y,prevNextType:2},o){case Un.Up:i.next.y-=s,n.prev.y=i.y;break;case Un.Bottom:i.next.y+=s,n.prev.y=i.y;break;case Un.Left:i.next.x-=s,n.prev.x=i.x;break;default:i.next.x+=s,n.prev.x=i.x;break}}function Pmt(r,e){const t=e||new Path2D;if((r.lineName==="line"||r.lineName==="polyline")&&r.calculative.lineSmooth){let n=Fge(r);if(t.addPath(n),t instanceof Path2D)return t}const i=r.calculative.worldAnchors;if(i.length>1){let n;i.forEach(s=>{n?fTe(t,n,s):s.start=!0,n=s}),r.close&&fTe(t,n,i[0])}if(t instanceof Path2D)return t}function wmt(r,e,t){var s;if(e.calculative.worldAnchors||(e.calculative.worldAnchors=[]),e.calculative.worldAnchors.length<2||((s=e.anchors)==null?void 0:s.length)>1)return;const i=Wl(e),n=na(e);!i||!n||!n.id||i===n||(i.next=void 0,kge(e),n.prev=void 0,e.calculative.worldAnchors.push(n))}function fTe(r,e,t){!t||t.isTemp||(e.start&&r.moveTo(e.x,e.y),e.next?t.prev?r.bezierCurveTo(e.next.x,e.next.y,t.prev.x,t.prev.y,t.x,t.y):r.quadraticCurveTo(e.next.x,e.next.y,t.x,t.y):t.prev?r.quadraticCurveTo(t.prev.x,t.prev.y,t.x,t.y):r.lineTo(t.x,t.y))}function Sue(r){return Eue(r),bz(AFe(r))}function AFe(r){const e=[];let t;return r.calculative.worldAnchors.forEach(i=>{e.push(i),t&&e.push(...pTe(t,i,r)),t=i}),r.close&&r.calculative.worldAnchors.length>1&&e.push(...pTe(t,r.calculative.worldAnchors[0],r)),e}function sZ(r){return r!=null&&r.lineWidth?r.lineWidth/2+4:4}function pTe(r,e,t){const i=[];if(!e)return i;let n=.02;if(r.lineLength&&(n=sZ(t)/r.lineLength),r.next)if(e.prev)for(let s=n;s<1;s+=n)i.push(CFe(s,r,r.next,e.prev,e));else for(let s=n;s<1;s+=n)i.push(Aue(s,r,r.next,e));else if(e.prev)for(let s=n;s<1;s+=n)i.push(Aue(s,r,e.prev,e));else i.push({x:e.x,y:e.y});return i.length>1&&(r.curvePoints=i),i}function Dmt(r,e){const t=sZ(e);let i=0,n,s;for(const a of e.calculative.worldAnchors){if(n){if(s=mTe(r,n,a,t),s)return{i,point:s};++i}n=a}if(e.close&&e.calculative.worldAnchors.length>1&&(s=mTe(r,n,e.calculative.worldAnchors[0],t)))return{i,point:s}}function mTe(r,e,t,i=4){if(!e.next&&!t.prev){const{x:n,y:s}=e,{x:a,y:o}=t,l=Math.min(n,a),c=Math.max(n,a),u=Math.min(s,o),h=Math.max(s,o);return r.x>=l-i&&r.x<=c+i&&r.y>=u-i&&r.y<=h+i?Omt(r,e,t,i):void 0}else if(e.curvePoints){for(const n of e.curvePoints)if(pP(r,n,i))return n}}function Omt(r,e,t,i=4){if(e.x===t.x){if(Math.abs(r.x-e.x)<=i)return{x:e.x,y:r.y}}else{const n=(e.y-t.y)/(e.x-t.x),s=e.y-n*e.x;if(Math.abs((n*r.x+s-r.y)/Math.sqrt(n*n+1))<=i){const l=(r.x+n*r.y-n*s)/(n*n+1);return{x:l,y:n*l+s}}}}function gTe(r,e,t,i){if(!e&&!t)return Math.sqrt(Math.pow(Math.abs(r.x-i.x),2)+Math.pow(Math.abs(r.y-i.y),2))||0;const n=document.createElementNS("http://www.w3.org/2000/svg","path");return e&&t?n.setAttribute("d",`M${r.x} ${r.y} C${e.x} ${e.y} ${t.x} ${t.y} ${i.x} ${i.y}`):e?n.setAttribute("d",`M${r.x} ${r.y} Q${e.x} ${e.y} ${i.x} ${i.y}`):n.setAttribute("d",`M${r.x} ${r.y} Q${t.x} ${t.y} ${i.x} ${i.y}`),n.getTotalLength()||0}function Eue(r){if(r.calculative.worldAnchors.length<2)return 0;let e=0,t;if(r.calculative.worldAnchors.forEach(i=>{t&&(t.lineLength=gTe(t,t.next,i.prev,i),e+=t.lineLength),t=i}),r.close){const i=Wl(r);t.lineLength=gTe(t,t.next,i.prev,i),e+=t.lineLength}return r.calculative.animatePos&&(r.calculative.animatePos=e/r.length*r.calculative.animatePos),r.length=e,e}function vse(r,e){const t=r.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&&s>c||n>l&&a>l||nf.y&&i.yf.y))){p=d;let m=mf;i.x{m.id=rs(),m.penId=e.id,e.calculative.worldAnchors.push(m)}),e.calculative.worldAnchors.push(n),p&&e.calculative.worldAnchors.push(p),d&&e.calculative.worldAnchors.push(f),s&&e.calculative.worldAnchors.reverse(),a){const m=e.calculative.worldAnchors.length-2;e.calculative.worldAnchors[m].isTemp=!1,e.calculative.worldAnchors[1].isTemp=!1}}function _Te(r,e,t){const i={x:r.x,y:r.y,id:rs()};switch(e){case Un.Up:i.y-=t;break;case Un.Right:i.x+=t;break;case Un.Bottom:i.y+=t;break;case Un.Left:i.x-=t;break;default:return}return i}function Fmt(r,e,t){if(r.x===e.x||r.y===e.y)return[];const i=[];let n,s;switch(t){case Un.Up:r.yr.y)n=r.x+(e.x-r.x)/2,i.push({x:n,y:r.y},{x:n,y:e.y});else{const a=(r.y+e.y)/2;i.push({x:r.x,y:a},{x:e.x,y:a})}break;case Un.Right:n=e.x,s=r.y,e.xr.x&&e.yr.y-mf)n=r.x+(e.x-r.x)/2,i.push({x:n,y:r.y},{x:n,y:e.y});else{const a=(r.y+e.y+mf)/2;i.push({x:r.x,y:a},{x:e.x,y:a})}break}return i}function Bmt(r,e,t){if(r.x===e.x||r.y===e.y)return[];const i=[];let n,s;switch(t){case Un.Up:n=r.x,s=e.y,e.x>r.x&&e.y>r.y&&(n=e.x,s=r.y),i.push({x:n,y:s});break;case Un.Bottom:n=r.x,s=e.y,e.x>r.x&&e.yr.y&&(n=r.x,s=e.y),i.push({x:n,y:s});break;case Un.Bottom:r.y>e.y?(n=e.x,s=r.y):(n=r.x,s=e.y),i.push({x:n,y:s});break;case Un.Left:n=e.x,s=r.y,e.x>r.x&&e.y>r.y&&(n=r.x,s=e.y),i.push({x:n,y:s});break;default:if(n=r.x,e.yr.y&&(n=e.x,s=r.y),i.push({x:n,y:s});break;case Un.Bottom:n=r.x,s=e.y,e.xr.x)n=e.x,s=r.y+(e.y-r.y)/2,i.push({x:r.x,y:s},{x:e.x,y:s});else{const a=(r.x+e.x)/2;i.push({x:a,y:r.y},{x:a,y:e.y})}break;case Un.Left:e.x>r.x?i.push({x:r.x,y:e.y}):i.push({x:e.x,y:r.y});break;default:if(n=r.x,s=e.y,e.xMath.abs(t.y-e.y));let n=r.calculative.worldAnchors.findIndex(s=>s.id==e.id);if(n>1){let s=r.calculative.worldAnchors[n-1];if(s.x===e.x&&s.y!==e.y)return i.push({x:t.x,y:e.y}),i;if(s.y===e.y&&s.x!==e.x)return i.push({x:e.x,y:t.y}),i}return r.calculative.worldAnchors.length&&(t.isTemp=void 0,r.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),n=Wl(r),s=na(r);let a=r.calculative.worldAnchors[i-1],o=r.calculative.worldAnchors[i+1];if(r.calculative.h==null&&(n.connectTo&&(oX(r,e,!0)?r.calculative.h=!0:lX(r,e,!0)&&(r.calculative.h=!1)),r.calculative.h==null&&s.connectTo&&(oX(r,e,!1)?r.calculative.h=!0:lX(r,e,!1)&&(r.calculative.h=!1)),r.calculative.h==null&&(a?r.calculative.h=a.y===e.y:o&&(r.calculative.h=o.y===e.y))),r.calculative.h){if(e.x=t.x,n.connectTo&&oX(r,e,!0)){o&&o.y!==e.y&&(o.x=e.x);return}if(s.connectTo&&oX(r,e,!1)){a&&a.y!==e.y&&(a.x=e.x);return}const l=r.anchors[i];let c;for(let u=i-1;u>-1;u--)if(a=r.anchors[u],c==null&&(c=a.y===l.y),c===!0)if(a.y===l.y)r.calculative.worldAnchors[u].y=t.y;else break;else if(a.x===l.x)r.calculative.worldAnchors[u].x=t.x;else break;c=void 0;for(let u=i+1;u-1;u--)if(a=r.anchors[u],c==null&&(c=a.x===l.x),c===!0)if(a.x===l.x)r.calculative.worldAnchors[u].x=t.x;else break;else if(a.y===l.y)r.calculative.worldAnchors[u].y=t.y;else break;c=void 0;for(let u=i+1;u1?(c=g.x-p.x,u=g.y-p.y):m>0?(c=g.x-(o+h*m),u=g.y-(l+d*m)):(c=g.x-o,u=g.y-l)):(c=g.x-o,u=g.y-l),_=c*c+u*u,_>s&&(a=v,s=_);return s>e&&(a-t>1&&n.push(...Tue(r,e,t,a)),n.push({id:r[a].id,penId:r[a].penId,x:r[a].x,y:r[a].y}),i-a>1&&n.push(...Tue(r,e,a,i))),n}function Gmt(r,e=.8,t=!1){if(r.length<3)return r;let i,n,s,a,o,l,c,u,h,d,f,p,g,m,_;const y=(v,x,b,C)=>(a=Math.sqrt(v*v+x*x),a>0?(p=v/a,m=x/a):(p=1,m=0),o=Math.sqrt(b*b+C*C),o>0?(g=b/o,_=C/o):(g=1,_=0),Math.acos(p*g+m*_));d=[],f=r.length,i=r[0],r[f-1],d.push({...r[0]});for(let v=0;v1){let u,h=0;for(let d=0;da)&&m>l+a&&_-m>l&&(r.lineAnimateType===_p.Arrow?Kmt(t,g,s,p,c,a):r.lineAnimateType===_p.WaterDrop&&Hmt(t,g,r.animateReverse,p,c,a)),g.x+=o*Math.cos(p*Math.PI/180),g.y-=o*Math.sin(p*Math.PI/180),m=Math.sqrt((g.x-u.x)**2+(g.y-u.y)**2)}u=f}}if(t instanceof Path2D)return t}function Wmt(r,e){let t=e.x-r.x,i=e.y-r.y,n=Math.atan(i/t)*180/Math.PI;return e.x>=r.x?n=-n:n=180-n,n}function Gy(r,e,t){let i=(180-t)*Math.PI/180;return{x:(r.x-e.x)*Math.cos(i)-(r.y-e.y)*Math.sin(i)+e.x,y:(r.x-e.x)*Math.sin(i)+(r.y-e.y)*Math.cos(i)+e.y}}function Kmt(r,e,t,i,n,s){let a=Gy({x:e.x+t,y:e.y+.57*t},{x:e.x,y:e.y},i),o=Gy({x:e.x+t,y:e.y-.57*t},{x:e.x,y:e.y},i),l=Gy({x:e.x+t,y:e.y+n/2},{x:e.x,y:e.y},i),c=Gy({x:e.x+s,y:e.y+n/2},{x:e.x,y:e.y},i),u=Gy({x:e.x+t,y:e.y-n/2},{x:e.x,y:e.y},i),h=Gy({x:e.x+s,y:e.y-n/2},{x:e.x,y:e.y},i);r.moveTo(a.x,a.y),r.lineTo(e.x,e.y),r.lineTo(o.x,o.y),r.lineTo(u.x,u.y),r.lineTo(h.x,h.y),r.lineTo(c.x,c.y),r.lineTo(l.x,l.y),r.lineTo(a.x,a.y)}function Hmt(r,e,t,i,n,s){let a=n/2;t&&(a=-n/2);let o=Gy({x:e.x,y:e.y+a},{x:e.x,y:e.y},i),l=Gy({x:e.x+s,y:e.y},{x:e.x,y:e.y},i),c=Math.PI/2;t&&(c=-Math.PI/2),r.moveTo(e.x,e.y),r.arc(e.x,e.y,n/2,-c-i/180*Math.PI,c-i/180*Math.PI,!1),r.lineTo(l.x,l.y),r.lineTo(o.x,o.y)}function jmt(r){var t;r.onDestroy||(r.onDestroy=$mt,r.onMove=cX,r.onResize=cX,r.onRotate=cX,r.onValue=cX,r.onMouseMove=Ymt,r.onBeforeValue=Xmt,r.onRenderPenRaw=Qmt),r.calculative.singleton||(r.calculative.singleton={});const e=r.calculative.worldRect;if(!r.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=r.calculative.canvas.externalElements)==null||t.parentElement.appendChild(i),Po(r,i),r.calculative.singleton.div=i;const n=document.createElement("iframe");n.style.width="100%",n.style.height="100%",n.scrolling=r.scrolling||"no",n.frameBorder="0",n.style.border="none",n.src=r.iframe,r.calculative.iframe=r.iframe,i.appendChild(n),MFe(r),n.onload=()=>{n.setAttribute("document.domain","")}}return r.calculative.patchFlags&&Po(r,r.calculative.singleton.div),r.onRenderPenRaw(r),new Path2D}function $mt(r){RFe(r),r.calculative.singleton&&r.calculative.singleton.div&&(r.calculative.singleton.div.remove(),delete r.calculative.singleton.div)}function cX(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function Xmt(r,e){if(e.iframe&&r.calculative.singleton.div&&(r.calculative.singleton.div.children[0].src=e.iframe,r.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){r.operationalRect||(r.operationalRect={});let t=Zt(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(r.operationalRect,t.operationalRect),r.calculative.singleton.div&&(r.calculative.singleton.div.children.length===1?MFe(r):(r.calculative.singleton.div.children[1].style.height=r.operationalRect.y*100+"%",r.calculative.singleton.div.children[1].style.left=r.operationalRect.x*100+"%",r.calculative.singleton.div.children[1].style.width=r.operationalRect.width*100+"%",r.calculative.singleton.div.children[2].style.width=(1-r.operationalRect.x-r.operationalRect.width)*100+"%",r.calculative.singleton.div.children[3].style.height=(1-r.operationalRect.y-r.operationalRect.height)*100+"%",r.calculative.singleton.div.children[3].style.left=r.operationalRect.x*100+"%",r.calculative.singleton.div.children[3].style.width=r.operationalRect.width*100+"%",r.calculative.singleton.div.children[4].style.width=r.operationalRect.x*100+"%"))}if(e.blur!==void 0)for(let t=1;t<5;t++)r.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++)r.calculative.singleton.div.children[t].style.backgroundColor=e.blurBackground;return e}function Ymt(r,e){if(!(!r.calculative.canvas.store.data.locked&&!r.locked)&&TFe(r.operationalRect)&&r.calculative.zIndex<5&&e.x>r.x+r.width*r.operationalRect.x&&e.xr.y+r.height*r.operationalRect.y&&e.y{RFe(r)};t.onmouseenter=a,n.onmouseenter=a,i.onmouseenter=a,s.onmouseenter=a,e.onmouseleave=a}function RFe(r){if(!(!r.calculative.canvas.store.data.locked&&!r.locked)&&r.calculative.zIndex<5){let e=r.calculative.singleton.div.parentNode.children;for(let t=1;t<6;t++)e[t].style.pointerEvents="initial"}}function Qmt(r){if(r.thumbImg&&!r.calculative.img){const e=new Image;e.crossOrigin=r.crossOrigin==="undefined"?void 0:r.crossOrigin||"anonymous",r.calculative.canvas.store.options.cdn&&!(r.thumbImg.startsWith("http")||r.thumbImg.startsWith("//")||r.thumbImg.startsWith("data:image"))?e.src=r.calculative.canvas.store.options.cdn+r.thumbImg:e.src=r.thumbImg,e.onerror=t=>{e.remove(),r.calculative.img=void 0},r.calculative.img=e}}const gf={},YY=['',''];function Zmt(r){var e;if(r.onDestroy||(r.onDestroy=qmt,r.onMove=yse,r.onResize=yse,r.onRotate=yse,r.onClick=vTe,r.onValue=egt,r.onChangeId=Jmt),gf[r.id])r.video&&r.calculative.media&&r.video!==r.calculative.video?(console.warn("video 更改, 此处是否执行?"),r.calculative.media.src=r.video,r.autoPlay&&(r.calculative.media.muted=!0,r.calculative.media.autoplay=!0),r.calculative.media.loop=r.playLoop,r.calculative.video=r.video):r.audio&&r.calculative.media&&r.audio!==r.calculative.audio&&(r.calculative.media.src=r.audio,r.autoPlay&&(r.calculative.media.muted=!0,r.calculative.media.autoplay=!0),r.calculative.media.loop=r.playLoop,r.calculative.audio=r.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",r.hideProgress&&(i.style.display="none");const n=document.createElement("div");n.innerHTML=YY[1],n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.width="20px",n.style.height="20px",n.style.fill="hsla(0, 0%, 100%, .8)",n.style.zIndex="1",n.style.display="none",t.appendChild(i),t.appendChild(n),n.onclick=a=>{a.stopPropagation(),r.calculative.media.muted?(n.innerHTML=YY[0],r.calculative.media.muted=!1):(n.innerHTML=YY[1],r.calculative.media.muted=!0)},r.calculative.singleton||(r.calculative.singleton={}),r.calculative.singleton.muted=n,t.onmouseenter=a=>{n.style.display="block"},t.onmouseleave=a=>{n.style.display="none"},t.onclick=a=>{a.stopPropagation(),vTe(r)};let s;r.video?(s=document.createElement("video"),s.src=r.video):r.audio&&(s=document.createElement("audio"),s.src=r.audio),s.loop=r.playLoop,s.ontimeupdate=()=>{IFe(i,s,r.calculative.worldRect.width)},s.onended=()=>{r.calculative.onended&&r.calculative.onended(r)},r.calculative.media=s,s.style.position="absolute",s.style.outline="none",s.style.left="0",s.style.top="0",s.style.width="100%",s.style.height="100%",t.appendChild(s),gf[r.id]=t,(e=r.calculative.canvas.externalElements)==null||e.parentElement.appendChild(t),Po(r,t),r.autoPlay&&(s.autoplay=!0,s.muted=!0)}return r.calculative.patchFlags&&Po(r,gf[r.id]),new Path2D}function qmt(r){gf[r.id].onclick=null,gf[r.id].remove(),gf[r.id]=void 0}function yse(r){Po(r,gf[r.id]);const e=gf[r.id].children[0],t=gf[r.id].children[1];IFe(e,t,r.calculative.worldRect.width)}function vTe(r){r.calculative.media&&(r.calculative.media.muted=!1,r.calculative.singleton.muted.innerHTML=YY[0],r.calculative.media.paused?r.calculative.media.play():r.calculative.media.pause())}function IFe(r,e,t){r.style.width=e.currentTime/e.duration*t+"px"}function Jmt(r,e,t){gf[e]&&(gf[t]=gf[e],delete gf[e])}function egt(r){const e=gf[r.id];if(!e)return;Po(r,e);const t=r.calculative.media.getAttribute("src");r.video?t!==r.video&&(r.calculative.media.src=r.video):r.audio&&t!==r.audio&&(r.calculative.media.src=r.audio),r.autoPlay&&(r.calculative.media.muted=!0,r.calculative.media.autoplay=!0),r.calculative.media.loop=r.playLoop}function Rv(){try{const r=new OffscreenCanvas(0,0),e=r.getContext("2d");return e&&e.arc?r:document.createElement("canvas")}catch{return document.createElement("canvas")}}let tgt=class QY{constructor(e,t){Xe(this,"parentElement");Xe(this,"store");Xe(this,"box");Xe(this,"text");Xe(this,"arrowUp");Xe(this,"arrowDown");Xe(this,"x");Xe(this,"y");Xe(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 n=0;n0?(this.arrowUp.style.borderBottomColor="transparent",this.arrowDown.style.borderTopColor="#777777"):(a+=i.height+n.height+5,this.arrowUp.style.borderBottomColor="#777777",this.arrowDown.style.borderTopColor="transparent"),this.x=s,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 PFe{constructor(e){Xe(this,"parent");Xe(this,"h");Xe(this,"v");Xe(this,"isDownH");Xe(this,"isDownV");Xe(this,"x");Xe(this,"y");Xe(this,"hSize");Xe(this,"vSize");Xe(this,"scrollX");Xe(this,"scrollY");Xe(this,"lastScrollX");Xe(this,"lastScrollY");Xe(this,"rect");Xe(this,"isShow");Xe(this,"pageMode");Xe(this,"onMouseDownH",e=>{e.preventDefault(),e.stopPropagation(),this.isDownH=e.x,this.x=this.parent.store.data.x||0,this.lastScrollX=this.scrollX});Xe(this,"onMouseDownV",e=>{e.preventDefault(),e.stopPropagation(),this.isDownV=e.y,this.y=this.parent.store.data.y||0,this.lastScrollY=this.scrollY});Xe(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())});Xe(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 yTe{constructor(e,t,i){Xe(this,"parentElement");Xe(this,"store");Xe(this,"isBottom");Xe(this,"canvas",document.createElement("canvas"));Xe(this,"otherOffsreen",Rv());Xe(this,"offscreen",Rv());Xe(this,"animateOffsScreen",Rv());Xe(this,"fitOffscreen",Rv());Xe(this,"fitFlag",!1);Xe(this,"currentFit");Xe(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===Rs.CanvasImageBottom||!this.isBottom&&e.canvasLayer===Rs.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(pp(o,!0))&&(t=!0));const i=this.store.patchFlagsBackground,n=this.store.patchFlagsTop;if(n&&!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(pp(l,!0))||l.canvasLayer!==Rs.CanvasTemplate&&(l.calculative.imageDrawed=!0,o.save(),PS(o,l),l.calculative.rotate&&Gv(o,l),wS(o,l),JP(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!==Rs.CanvasTemplate&&(l.calculative.imageDrawed=!0,o.save(),PS(o,l),l.calculative.rotate&&Gv(o,l),wS(o,l),JP(o,l),o.restore());for(const l of this.store.data.pens)!l.calculative.hasImage||!l.parentId||l.canvasLayer!==Rs.CanvasTemplate&&this.store.animates.has(pp(l,!0))&&(l.calculative.imageDrawed=!0,o.save(),PS(o,l),l.calculative.rotate&&Gv(o,l),wS(o,l),JP(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.options.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||n&&!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,b,C,A,E,P,w;const{data:t,options:i}=this.store,{rule:n,ruleColor:s,scale:a,origin:o}=t;if(!(n??i.rule))return;const l=a*10;e.save();const c=s||i.ruleColor;e.strokeStyle=iZ(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=(b=i.ruleOptions)==null?void 0:b.background,e.rect(0,0,d,p),e.fill(),e.rect(0,0,p,f),e.fill()),(C=i.ruleOptions)!=null&&C.underline&&(e.beginPath(),e.fillStyle=iZ(c,.7),e.moveTo(0,p),e.lineTo(d,p),e.stroke(),e.moveTo(p,0),e.lineTo(p,f),e.stroke());let g=p/4;((A=i.ruleOptions)==null?void 0:A.baseline)==="bottom"&&(g=p*3/4),e.beginPath(),e.lineWidth=p/2,e.lineDashOffset=-u%l,e.setLineDash([1,l-1]),e.moveTo(0,g),e.lineTo(d,g),e.stroke(),e.beginPath(),e.lineDashOffset=-h%l,e.moveTo(g,0),e.lineTo(g,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=((E=i.ruleOptions)==null?void 0:E.textColor)||e.strokeStyle;let m=0-Math.floor(u/l/10)*100,_=((P=i.ruleOptions)==null?void 0:P.textTop)||16,y=((w=i.ruleOptions)==null?void 0:w.textLeft)||4;u<0&&(m-=100);for(let M=u%(l*10);M{i.drawImage(l,n.x-e,n.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,(n.x-e-2.5)/this.store.dpiRatio,(n.y-e-2.5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio,(this.magnifierSize+5)/this.store.dpiRatio)}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 wFe(r){if(r.data.locked)throw new Error("canvas is locked")}class rgt{constructor(e){Xe(this,"parentElement");Xe(this,"box");Xe(this,"iframe");Xe(this,"dialog");Xe(this,"close");Xe(this,"title");Xe(this,"body");Xe(this,"x");Xe(this,"y");Xe(this,"url");this.parentElement=e,this.box=document.createElement("div"),this.dialog=document.createElement("div");let t=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.box.className="meta2d-dialog_mask",this.dialog.className="meta2d-dialog",this.body.className="meta2d-dialog_body",t.className="meta2d-dialog_header",this.title.className="meta2d-dialog-content",this.close.className="meta2d-dialog-close",t.appendChild(this.title),t.appendChild(this.close),this.body.appendChild(this.iframe),this.dialog.appendChild(t),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 i;for(let n=0;n{e.stopPropagation()});Xe(this,"curve",Mmt);Xe(this,"polyline",Nmt);Xe(this,"mind",Imt);Xe(this,"line",wmt);Xe(this,"onCopy",e=>{this.store.options.disableClipboard||e.target!==this.externalElements&&e.target!==document.body&&e.target.offsetParent!==this.externalElements||this.copy()});Xe(this,"onCut",e=>{this.store.options.disableClipboard||e.target!==this.externalElements&&e.target!==document.body&&e.target.offsetParent!==this.externalElements||this.cut()});Xe(this,"onPaste",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 n=0;n{c=h.target.result;const d=new Image;d.src=c,d.onload=()=>{const{width:f,height:p}=d,g={name:l,x:s-50/2,y:a-p/f*50,externElement:l==="gif",width:100,height:p/f*100,image:c};this.addPens([g]),this.active([g]),this.copy([g])}},u.readAsDataURL(o)}}}}else this.paste()});Xe(this,"onMessage",e=>{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):this.parent.doMessageEvent(t)});Xe(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===Kr.Node||this.hoverType===Kr.Line))||this.store.data.locked===Ss.Disable||this.store.data.locked===Ss.DisableScale||this.store.data.locked===Ss.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 s=this.store.data.scale||1;this.translate(-e.deltaX/s,-e.deltaY/s);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:n}=e;this.scale(this.store.data.scale+t,{x:i,y:n}),this.externalElements.focus()});Xe(this,"onkeydown",e=>{var s,a,o;if(this.store.data.locked>=Ss.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>=Ss.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;let t=10,i=10,n=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&&(n={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=ya.Translate;break;case"Control":this.drawingLine?this.drawingLine.calculative.drawlineH=!this.drawingLine.calculative.drawlineH:this.hotkeyType||(this.patchFlags=!0,this.hotkeyType=ya.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=ya.Resize));break;case"Alt":if(!e.ctrlKey&&!e.shiftKey&&this.drawingLine){const l=na(this.drawingLine);l!==this.drawingLine.calculative.activeAnchor?(kge(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!==Ss.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}n&&this.activeRect.x+tn.x+n.width&&(t=n.x+n.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,n&&this.activeRect.y+this.activeRect.height+i>n.y+n.height&&(i=n.y+n.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":(s=this.store.active[0])!=null&&s.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===Kr.NodeAnchor&&(this.movingAnchor=this.store.hoverAnchor,this.externalElements.style.cursor="move");break;case"s":case"S":!this.store.data.locked&&this.hoverType===Kr.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&&AFe(l),this.store.path2dMap.set(l,un.path2dDraws.line(l)),Eue(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=ya.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.setFollowers();break}this.render(!1)});Xe(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:n}=e.dataTransfer;if(n.length&&n[0].type.match("image.*")&&!(this.addCaches&&this.addCaches.length)){const s=n[0].type==="image/gif";i=await this.fileToPen(n[0],s)}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 n={x:e.offsetX,y:e.offsetY};this.calibrateMouse(n),this.dropPens(i,n),this.addCaches=[],this.getContainerHover(n),this.mousePos.x=n.x,this.mousePos.y=n.y,this.store.emitter.emit("mouseup",{x:n.x,y:n.y,pen:this.store.hoverContainer})}this.store.emitter.emit("drop",i||t)});Xe(this,"ontouchstart",e=>{this.store.data.locked!==Ss.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,n={x:t,y:i};if(this.calibrateMouse(n),this.getHover(n),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))});Xe(this,"ontouchmove",e=>{var o;if(this.store.data.locked===Ss.Disable)return;e.stopPropagation(),e.preventDefault();const t=performance.now();if(t-this.touchStart<50)return;this.touchStart=t;const i=e.touches,n=i.length,s=e.touches[0].pageX-this.clientRect.x,a=e.touches[0].pageY-this.clientRect.y;if(n===1)this.onMouseMove({x:s,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(n===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,Zt(this.touchCenter))}if(this.touchMoving){if(this.store.data.locked>=Ss.DisableMove&&this.store.data.locked!==Ss.DisableScale||this.store.data.disableScale||this.store.options.disableScale)return;if(this.lastOffsetX){const{scale:l}=this.store.data;this.translate((s-this.lastOffsetX)/l,(a-this.lastOffsetY)/l)}this.lastOffsetX=s,this.lastOffsetY=a}}});Xe(this,"ontouchend",e=>{if(this.store.data.locked===Ss.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)});Xe(this,"onGesturestart",e=>{e.preventDefault()});Xe(this,"onMouseDown",e=>{var t,i,n,s;if(e.buttons===2&&!this.drawingLine&&(this.mouseRight=pv.Down),this.hideInput(),this.store.data.locked===Ss.Disable||e.buttons!==1&&e.buttons!==2){this.hoverType=Kr.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===ya.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 a=this.store.activeAnchor;if(!a)return;const o={id:rs(),x:a.x,y:a.y};this.drawingLine=this.createDrawingLine(o);let l=Wl(this.drawingLine);this.drawingLine.calculative.activeAnchor=l,Du(this.store.hover,a,this.drawingLine,o),this.drawline();return}if(!(this.hotkeyType===ya.Translate||this.mouseRight===pv.Down&&!this.store.options.mouseRightActive)){if(this.drawingLine){if(this.store.hoverAnchor){const o=na(this.drawingLine);this.store.hoverAnchor.type===vv.Line?sX(o,this.store.hoverAnchor,this.store):(o.x=this.store.hoverAnchor.x,o.y=this.store.hoverAnchor.y),Du(this.store.hover,this.store.hoverAnchor,this.drawingLine,o),this.drawline(),this.finishDrawline(!0);return}if(!this.store.options.autoAnchor&&e.shiftKey&&e.altKey&&e.ctrlKey){this.setAnchor(this.store.pointAt);const o=na(this.drawingLine),l=this.store.activeAnchor;if(!l)return;o.x=l.x,o.y=l.y,Du(this.store.hover,l,this.drawingLine,o),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),(n=this.store.active[0])!=null&&n.anchors[0].connectTo||this.store.active.length==0?this.drawingLineName="":this.drawingLineName=this.store.options.drawingLineName;return}if(this.store.options.autoAnchor&&this.hoverType===Kr.Node){const o=na(this.drawingLine),l=SP(this.store.hover,e);o.x=l.x,o.y=l.y,this.drawingLine.autoTo=!0,Du(this.store.hover,l,this.drawingLine,o),this.drawline(),this.finishDrawline(!0);return}const a=na(this.drawingLine);a.isTemp?(this.drawingLine.calculative.activeAnchor=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2],a.isTemp=void 0):(this.drawingLine.calculative.activeAnchor=a,this.drawingLine.calculative.worldAnchors.push({x:a.x,y:a.y,penId:a.penId})),this.drawingLine.calculative.drawlineH=void 0,this.drawingLineName!=="polyline"&&this.drawline()}if(this.drawingLineName){if(this.hoverType===Kr.Node)if(this.store.options.autoAnchor){this.inactive(!0);const a=SP(this.store.hover,e);this.store.hoverAnchor=a;const o={id:rs(),x:a.x,y:a.y};this.drawingLine=this.createDrawingLine(o),this.drawingLine.autoFrom=!0,Du(this.store.hover,a,this.drawingLine,o)}else this.inactive(),this.hoverType=Kr.None;else if(this.hoverType===Kr.NodeAnchor){this.drawingLineName=this.store.options.drawingLineName;const a={id:rs(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};this.drawingLine=this.createDrawingLine(a),this.drawingLine.calculative.activeAnchor=a,Du(this.store.hover,this.store.hoverAnchor,this.drawingLine,a)}else if(!this.drawingLine&&this.drawingLineName!=="curve"){this.inactive(!0);const a={id:rs(),x:e.x,y:e.y};this.drawingLine=this.createDrawingLine(a),this.drawingLine.calculative.activeAnchor=a}}else if(this.pencil){this.inactive(!0);const a=rs(),o={x:e.x,y:e.y,id:rs(),penId:a};this.pencilLine=this.getInitPencilLine(o)}else{switch(this.hoverType){case Kr.None:(this.store.data.rule||this.store.options.rule)&&!this.store.options.disableRuleLine&&this.addRuleLine(e),this.store.options.resizeMode&&(this.hotkeyType=ya.None),this.inactive();break;case Kr.Node:case Kr.Line:if(this.store.hover){const a=pp(this.store.hover,!0);let o=a||this.store.hover;a&&(a.container||(s=this.store.options.containerShapes)!=null&&s.includes(a.name))&&(o=this.store.hover),e.ctrlKey&&!e.shiftKey?(o.calculative.active?this.willInactivePen=o:this.store.active.length>0&&(o.calculative.active=!0,gP(o),this.store.active.push(o),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&&Ny({x:e.x,y:e.y},this.activeRect))||this.store.active.length==1)&&(o.calculative.active||(this.active([o]),this.store.options.resizeMode&&(this.hotkeyType=ya.Resize))),this.calcActiveRect()}break;case Kr.LineAnchor:this.store.activeAnchor=this.store.hoverAnchor,this.store.hover.calculative.activeAnchor=this.store.hoverAnchor,this.active([this.store.hover]);break;case Kr.LineAnchorPrev:case Kr.LineAnchorNext:this.store.activeAnchor&&(this.prevAnchor={...this.store.activeAnchor.prev},this.nextAnchor={...this.store.activeAnchor.next});break;case Kr.Resize:this.activeInitPos=[],this.store.active.forEach(a=>{this.activeInitPos.push({x:(a.calculative.worldRect.x-this.activeRect.x)/this.activeRect.width,y:(a.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()}}});Xe(this,"onMouseMove",e=>{var i,n,s,a,o,l,c,u;if(this.store.data.locked===Ss.Disable){this.hoverType=Kr.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===pv.Down&&(this.mouseRight=pv.Translate),this.store.data.locked===Ss.DisableEdit||this.store.data.locked===Ss.DisableScale||this.hotkeyType===ya.Translate||this.mouseRight===pv.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===Kr.NodeAnchor){if(!this.store.hoverAnchor)return;this.drawingLineName=this.store.options.drawingLineName;const h={id:rs(),x:this.store.hoverAnchor.x,y:this.store.hoverAnchor.y};this.drawingLine=this.createDrawingLine(h),this.drawingLine.calculative.activeAnchor=h,Du(this.store.hover,this.store.hoverAnchor,this.drawingLine,h),this.drawline();return}}else if(this.drawingLineName&&this.hoverType===Kr.None){const h={id:rs(),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(!((n=this.store.active[0])!=null&&n.locked)){const h={x:e.x,y:e.y};if(this.hoverType===Kr.LineAnchor){(this.dockInAnchor(e)||((s=this.store.active[0])==null?void 0:s.lineName)==="line")&&!this.store.options.disableDock&&!this.store.options.disableLineDock&&(this.clearDock(),this.dock=oTe(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===Kr.LineAnchorPrev){this.moveLineAnchorPrev(e);return}if(this.hoverType===Kr.LineAnchorNext){this.moveLineAnchorNext(e);return}}if(this.hoverType===Kr.Rotate){this.rotatePens({x:e.x,y:e.y});return}if(this.hoverType===Kr.Resize){this.resizePens(e);return}if(this.hoverType===Kr.Node||this.hoverType===Kr.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=na(this.drawingLine)),p?(p.prev=void 0,p.next=void 0,p.id||(p.id=rs()),p.x=f.x,p.y=f.y,p.connectTo=void 0):(p={...f},this.drawingLine.calculative.worldAnchors.push(p)),(this.hoverType===Kr.NodeAnchor||this.hoverType===Kr.LineAnchor)&&(this.store.hoverAnchor.type!==vv.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 g=this.drawingLine.calculative.worldAnchors[this.drawingLine.calculative.worldAnchors.length-2];this.getSpecialAngle(p,g)}}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===ya.AddAnchor&&(this.patchFlags=!0),this.render(!1)});Xe(this,"onMouseUp",e=>{if(this.store.data.locked===Ss.Disable){this.hoverType=Kr.None;return}if(this.mouseDown){if(this.mouseRight===pv.Down&&(this.store.hover&&this.store.hover.calculative.focus?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=pv.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=na(this.drawingLine);this.store.hoverAnchor.type===vv.Line?sX(t,this.store.hoverAnchor,this.store):(t.x=this.store.hoverAnchor.x,t.y=this.store.hoverAnchor.y),Du(this.store.hover,this.store.hoverAnchor,this.drawingLine,t),this.drawline(),this.finishDrawline(!0);return}if(this.store.options.autoAnchor&&this.hoverType===Kr.Node){const t=na(this.drawingLine),i=SP(this.store.hover,e);t.x=i.x,t.y=i.y,this.drawingLine.autoTo=!0,Du(this.store.hover,i,this.drawingLine,t),this.drawline(),this.finishDrawline(!0);return}}if(this.hoverType===Kr.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=Wl(t),n=na(t);if(this.store.hoverAnchor){const s=this.store.hover,a=Wl(s)===this.store.hoverAnchor,o=na(s)===this.store.hoverAnchor,l=i===this.store.activeAnchor,c=n===this.store.activeAnchor;if((e.ctrlKey||e.altKey)&&s.type===sa.Line&&(a||o)&&(l||c)){const u=s.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([s]),this.render()}else this.store.activeAnchor&&(this.store.hoverAnchor.type===vv.Line?sX(this.store.activeAnchor,this.store.hoverAnchor,this.store):(this.store.activeAnchor.x=this.store.hoverAnchor.x,this.store.activeAnchor.y=this.store.hoverAnchor.y),Du(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,un.path2dDraws.line(t)),this.initLineRect(t)}else i===this.store.activeAnchor&&t.autoFrom?this.calcAutoAnchor(t,i,this.store.hover):n===this.store.activeAnchor&&t.autoTo&&this.calcAutoAnchor(t,n,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===Kr.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>=Ss.DisableMove||i.parentId||i.isRuleLine)return!1;if(Jy(i.calculative.worldRect,this.dragRect,e.ctrlKey||this.store.options.dragAllIn))return i.type===sa.Line&&!this.store.options.dragAllIn?vse(i,this.dragRect):!0});this.active(t)}if(e.button!==2&&(IJ(this.mouseDown,e)<2&&(this.store.hover&&this.store.hover.input&&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,gP(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()}});Xe(this,"clearDock",()=>{var s,a,o,l;const e=(a=(s=this.dock)==null?void 0:s.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 n=this.store.pens[t];n&&(n.calculative.isDock=!1),this.dock=void 0});Xe(this,"onResize",()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.resize(),this.timer=void 0},100)});Xe(this,"onScroll",()=>{this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.clientRect=this.canvas.getBoundingClientRect(),this.timer=void 0},100)});Xe(this,"calibrateMouse",e=>(e.x-=this.store.data.x,e.y-=this.store.data.y,e));Xe(this,"getContainerHover",e=>{var i;if(this.dragRect)return;this.store.hoverContainer=void 0;const t=this.store.data.pens.filter(n=>{var s;return n.container||((s=this.store.options.containerShapes)==null?void 0:s.includes(n.name))});if(t.length)for(let n=t.length-1;n>=0;--n){const s=t[n];if(!(s.visible==!1||s.calculative.inView==!1||s.locked===Ss.Disable)){if(Ny(e,s.calculative.worldRect))this.store.hoverContainer=s,(i=s==null?void 0:s.onMouseMove)==null||i.call(s,s,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(s===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+Jd];this.store.lastHoverContainer&&!a&&(this.store.lastHoverContainer.calculative.containerHover=!1,this.store.emitter.emit("leave",this.store.lastHoverContainer)),this.store.lastHoverContainer=this.store.hoverContainer}}}});Xe(this,"getHover",e=>{var n,s;if(this.dragRect||this.canvasImage.fitFlag)return;let t=Kr.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!==ya.AddAnchor&&this.activeRect&&!i&&!this.store.data.locked){const a=mse(this.store.active),o=nTe(this.store.active)||this.store.options.disableRotate,l=sTe(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&&fo(c,this.activeRect.rotate,this.activeRect.pivot||this.activeRect.center),!this.hotkeyType&&pP(e,c,this.pointSize)&&(t=Kr.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===ya.Resize||u&&!this.hotkeyType)&&pP(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=Kr.Resize,this.resizeIndex=c,this.externalElements.style.cursor=d[(c+f)%4];break}}}t===Kr.None&&(t=this.inPens(e,this.store.data.pens)),!t&&!i&&Ny(e,this.activeRect)&&(t=Kr.Node,this.externalElements.style.cursor="move"),this.hoverType=t,t===Kr.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,x9(pp(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,x9(pp(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),(s=(n=this.store.hover)==null?void 0:n.onMouseMove)==null||s.call(n,this.store.hover,this.mousePos)});Xe(this,"inPens",(e,t)=>{var n;let i=Kr.None;e:for(let s=t.length-1;s>=0;--s){const a=t[s];if(a.visible==!1||a.calculative.inView==!1||a.locked===Ss.Disable)continue;const o=sZ(a);if(!(!a.calculative.active&&!DS(e,a.calculative.worldRect,o)&&!Ny(e,a.calculative.worldRect))){if(!this.store.data.locked&&this.hotkeyType!==ya.Resize&&a.calculative.worldAnchors){for(const l of a.calculative.worldAnchors)if(i=this.inAnchor(e,a,l),i){let c=Zt(l);Object.assign(c,e),this.title.show(c,a);break e}}if(a.type){if(a.isRuleLine){let c=((n=this.store.options.ruleOptions)==null?void 0:n.height)||20;if(e.x+this.store.data.x>c&&e.y+this.store.data.y>c)break}const l=Dmt(e,a);if(l){!this.store.data.locked&&!a.locked?this.hotkeyType===ya.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=Kr.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=DS(e,a.calculative.worldRect,a.lineWidth):l=Ny(e,a.calculative.worldRect),l){if(a.type===sa.Node&&a.name==="line"&&!J0t(e,a.calculative.worldAnchors))continue;if(!this.store.data.locked&&!a.locked?this.hotkeyType===ya.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=Kr.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 g=[{x:c,y:u},{x:h,y:u},{x:h,y:d},{x:c,y:d}];g.forEach(_=>{fo(_,f,p)});let m=g[g.length-1];for(const _ of g){if(m.y>e.y!=_.y>e.y){const y=_.x+(e.y-_.y)*(m.x-_.x)/(m.y-_.y);Math.abs(y-this.store.pointAt.x)<10&&(this.store.pointAt.x=y)}m=_}}else this.store.pointAt.x-10h&&(this.store.pointAt.x=h),this.store.pointAt.y-10d&&(this.store.pointAt.y=d)}break}}}}return i});Xe(this,"dockInAnchor",e=>{var t,i;this.store.hover=void 0;for(let n=this.store.data.pens.length-1;n>=0;--n){const s=this.store.data.pens[n];if(s.visible==!1||s.locked===Ss.Disable||s===this.store.active[0])continue;let a=sZ(s);if(a+=2*this.store.options.anchorRadius,!!DS(e,s.calculative.worldRect,a)&&(this.store.hover=s,this.hotkeyType!==ya.Resize&&s.calculative.worldAnchors))for(const o of s.calculative.worldAnchors){if(o.twoWay===ch.In){const l=na(this.store.active[0]);if(this.store.activeAnchor.id!==l.id)continue}if(o.twoWay===ch.Out){const l=Wl(this.store.active[0]);if(this.store.activeAnchor.id!==l.id)continue}if(!(o.twoWay===ch.DisableConnected||o.twoWay===ch.Disable||((t=this.store.activeAnchor)==null?void 0:t.twoWay)===ch.DisableConnectTo||((i=this.store.activeAnchor)==null?void 0:i.twoWay)===ch.Disable)&&(this.title.hide(),this.inAnchor(e,s,o))){let l=Zt(o);return Object.assign(l,e),this.title.show(l,s),!0}}}});Xe(this,"imageTimer");Xe(this,"templateImageTimer");Xe(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=W9(this.store);for(const t of this.store.data.pens)isFinite(t.x)&&t.canvasLayer!==Rs.CanvasTemplate&&t.calculative.inView&&(t.canvasLayer===Rs.CanvasMain&&t.name!=="gif"&&t.image&&t.calculative.img&&(e.save(),PS(e,t),t.calculative.rotate&&Gv(e,t),wS(e,t),JP(e,t),e.restore()),aS(e,t));this.drawingLine&&aS(e,this.drawingLine),this.pencilLine&&aS(e,this.pencilLine),this.movingPens&&this.movingPens.forEach(t=>{this.renderPenContainChild(e,t)})});Xe(this,"renderPenContainChild",(e,t)=>{var i;t.calculative.inView&&aS(e,t),(i=t.children)==null||i.forEach(n=>{const s=this.store.pens[n];s&&this.renderPenContainChild(e,s)})});Xe(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.options.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,mse(this.store.active)||nTe(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.options.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()}});Xe(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!==ya.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===ya.AddAnchor&&t.push(this.store.pointAt),t&&(e.strokeStyle=this.store.hover.anchorColor||this.store.options.anchorColor,e.fillStyle=this.store.hover.anchorBackground||this.store.options.anchorBackground,t.forEach(i=>{if(i.hidden&&i.locked>Ss.DisableEdit)return;if(i===this.store.hoverAnchor){e.save();const s=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;e.strokeStyle=s,e.fillStyle=s}e.beginPath();let n=i.radius||this.store.hover.anchorRadius||this.store.options.anchorRadius;if(this.store.hover.type&&!i.radius&&!this.store.hover.anchorRadius&&(n=3,this.store.hover.calculative.lineWidth>3&&(n=this.store.hover.calculative.lineWidth)),i.type===vv.Line){let s=this.store.pens[i.penId].rotate||0;this.store.pens[i.penId].calculative.flipX&&(s*=-1),this.store.pens[i.penId].calculative.flipY&&(s*=-1);let a=i.rotate+s;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-n,i.length*this.store.data.scale,n*2),e.restore()}else e.arc(i.x,i.y,n,0,Math.PI*2);if(this.store.hover.type&&this.store.hoverAnchor===i?(e.save(),e.strokeStyle=this.store.hover.activeColor||this.store.options.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 s=this.store.hover.hoverAnchorColor||this.store.options.hoverAnchorColor;globalThis.pSBC&&(e.strokeStyle=globalThis.pSBC(.5,s)),e.arc(i.x,i.y,n+1.5,0,Math.PI*2),e.stroke(),e.restore()}}))}this.hotkeyType!==ya.AddAnchor&&!this.movingPens&&this.activeRect&&!(this.store.active.length===1&&this.store.active[0].type)&&!mse(this.store.active)&&!sTe(this.store.active)&&!this.store.options.disableSize&&(e.strokeStyle=this.store.options.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===ya.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=iZ(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()});Xe(this,"pastePen",(e,t)=>{const i=e.id;if(lTe(e),e.parentId=t,e.type===sa.Line?this.changeNodeConnectedLine(i,e,this.store.clipboard.pens):this.changeLineAnchors(i,e,this.store.clipboard.pens),!e.parentId){const s=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+s.x*l,e.y=o.y+s.y*l,e.width=s.width*l,e.height=s.height*l,a.x=o.x+a.x*l,a.y=o.y+a.y*l,Tl(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)||(e.x+=this.store.clipboard.offset*this.store.data.scale,e.y+=this.store.clipboard.offset*this.store.data.scale)}this.makePen(e);const n=[];if(Array.isArray(e.children))for(const s of e.children){const a=this.store.clipboard.pens.find(o=>o.id===s);a&&n.push(this.pastePen(a,e.id).id)}return e.children=n,Ev(e,!0),e});Xe(this,"ondblclick",e=>{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.showInput(this.store.hover)),this.store.emitter.emit("dblclick",{x:e.x,y:e.y,pen:this.store.hover})});Xe(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 n=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=n.x+this.store.data.x-(e.textLeft||0)+"px",this.inputParent.style.top=n.y+this.store.data.y-(e.textTop||0)+"px";let l=n.width+(e.textLeft||0);this.inputParent.style.width=(l<0?12:l)+"px",this.inputParent.style.height=n.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.store.data.locked||(this.inputRight.style.display="none"),this.setDropdownList()):this.inputRight.style.display="none",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()});Xe(this,"setInputStyle",e=>{e.text||(e.text="");let t;for(let l=0;l1?e.textLeft*s:e.textLeft*s/a}px;`),e.textTop&&(i+=`margin-top:${a>1?e.textTop*s:e.textTop*s/a}px;`),e.lineHeight&&(i+=`line-height:${a>1?e.fontSize*e.lineHeight*a:e.fontSize*e.lineHeight*s}px;`),e.textHeight)i+=`height:${a>1?e.textHeight*s*a:e.textHeight*s}px;`;else{let l=e.calculative.worldRect.height/a-(e.textTop||0);l<0&&(l=0);let c=e.fontSize*a<12?l*s:l*a*s;c-1?e.textWidth*e.calculative.worldRect.width:e.textWidth,e.whiteSpace!=="pre-line"&&(o1?o*s*a:o*s}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*s:l*a}px;`}if(e.whiteSpace&&(e.whiteSpace==="pre-line"?i+="white-space:pre;":(i+=`white-space:${e.whiteSpace};`,e.whiteSpace==="nowrap"&&(n+="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{${n}}`)});Xe(this,"hideInput",()=>{if(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=[Zt(e,!0)];e.text=this.inputDiv.dataset.value,e.calculative.text=e.text,this.inputDiv.dataset.penId=void 0,e.name==="text"&&e.textAutoAdjust&&s0t(e),t_(e),this.patchFlags=!0,this.pushHistory({type:Vr.Update,pens:[Zt(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&&t_(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()});Xe(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",this.inputRight.style.display="block",setTimeout(()=>{this.inputRight.style.transform="rotate(315deg)",this.inputRight.style.zoom=this.store.data.scale}),!t||!t.dropdownList){this.dropdown.style.display="none",this.inputRight.style.display="none",this.inputRight.style.transform="rotate(135deg)";return}if(!t.dropdownList.length){const s=document.createElement("div");s.innerText="None",s.style.padding="5px 12px",s.style.color="#ddd",this.dropdown.appendChild(s);return}const i=this.inputDiv.innerHTML.replace(/\/g,` `).replace(/\<\/div\>/g,"").replace(/\/g,"");let n=0;for(const s of t.dropdownList){const a=typeof s=="string"?s:s.text;e&&i?a.includes(i)&&this.dropdownAppendOption(a,n):this.dropdownAppendOption(a,n),++n}if(!this.dropdown.hasChildNodes()){const s=document.createElement("div");s.innerText="None",s.style.padding="5px 12px",s.style.color="#ddd",this.dropdown.appendChild(s)}});Xe(this,"selectDropdown",e=>{const t=e.target,i=this.store.pens[this.inputDiv.dataset.penId];if(!t||!i||!i.dropdownList)return;const n=+t.dataset.i,s=i.dropdownList[n];if(!s)return;const a=[Zt(i,!0)];typeof s=="object"?(this.updateValue(i,{...s}),i.calculative.text=void 0,this.calcActiveRect()):i.text=s+"",this.inputDiv.innerText=i.text,this.hideInput(),this.pushHistory({type:Vr.Update,pens:[Zt(i,!0)],initPens:a}),this.render(),this.store.emitter.emit("change",i),this.store.emitter.emit("valueUpdate",i)});Xe(this,"inFitBorder",e=>{let t;const i=this.store.data.width||this.store.options.width,n=this.store.data.height||this.store.options.height;let s={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",s.y>n*a.y-10&&s.yn*(a.y+a.height)-10&&s.yi*a.x-10&&s.xi*(a.x+a.width)-10&&s.x{this.patchFlags=!0,this.store.lastHover&&(this.store.lastHover.calculative.hover=!1);let s=this.store.data.pens.find(a=>a.calculative.hover===!0);x9(s,!1)},this.dialog=new rgt(t),this.title=new aZ(t),this.store.options.scroll&&(this.scroll=new PFe(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 gS.Document:document.addEventListener("keydown",this.onkeydown),document.addEventListener("keyup",this.onkeyup);break;case gS.Canvas:this.externalElements.addEventListener("keydown",this.onkeydown),this.externalElements.addEventListener("keyup",this.onkeyup);break}}splitLine(e,t){const i=e.calculative.worldAnchors,n=i.findIndex(u=>u===t);if([-1,0,i.length-1].includes(n))return;const s=Zt(e,!0),a=Zt(e,!0),o=rs();a.id=o,a.calculative.canvas=this,a.calculative.active=!1,a.calculative.hover=!1;const l=Zt(i.slice(0,n+1)),c=Zt(i.slice(n)).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:Vr.Add,pens:[Zt(a,!0)],step:2}),this.pushHistory({type:Vr.Update,initPens:[s],pens:[Zt(e,!0)],step:2})}translateAnchor(e,t){this.movingAnchor.x+=e,this.movingAnchor.y+=t;const i=this.movingAnchor.penId;if(i){const n=this.store.pens[i],s=n.calculative.worldRect;this.movingAnchor.xs.ex&&(this.movingAnchor.x=s.ex),this.movingAnchor.ys.ey&&(this.movingAnchor.y=s.ey);const a=H9(this.movingAnchor,s),o=n.anchors.findIndex(l=>l.id===this.movingAnchor.id);n.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 o0t(e,this.store.options.uploadUrl,this.store.options.uploadParams,this.store.options.uploadHeaders):i=await a0t(e),new Promise((n,s)=>{const a=new Image;a.onload=()=>{un.htmlElements[i]=a,n({width:a.width,height:a.height,name:t?"gif":"image",image:i})},a.onerror=o=>{s(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=rs()),!c.calculative&&(c.calculative={canvas:this}),this.store.pens[c.id]=c;let i=0,n=0,s=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+s,c.y=t.y-c.height/2+n,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?s=c.width-40*this.store.data.scale:s=0,i++,i%2===0&&(n+=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=>Ny(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 n=null;e.type?(e.anchors[0].connectTo||e.anchors[e.anchors.length-1].connectTo)&&(n=[e.id,e.anchors[0].id,e.anchors[e.anchors.length-1].id]):e.connectedLines&&e.connectedLines.length&&(n=[e.id]),lTe(e),n&&(n.length===1?this.randomIdObj[n[0]]=e.id:(this.randomIdObj[n[0]]=e.id,this.randomIdObj[n[1]]=e.anchors[0].id,this.randomIdObj[n[2]]=e.anchors[e.anchors.length-1].id)),e.parentId=i;const s=[];if(Array.isArray(e.children))for(const a of e.children){const o=t.find(l=>l.id===a);o&&s.push(this.randomCombineId(o,t,e.id).id)}return e.children=s,e}async addPens(e,t){if(this.beforeAddPens&&await this.beforeAddPens(e)!=!0)return[];const i=[];for(const n of e)this.beforeAddPen&&this.beforeAddPen(n)!=!0||(this.makePen(n),i.push(n));return this.render(),this.store.emitter.emit("add",i),t&&this.pushHistory({type:Vr.Add,pens:Zt(i,!0)}),i}getInitPencilLine(e){const{data:t,options:i}=this.store,n=t.scale,s=t.lineWidth||1;return{id:e.penId,name:"line",x:e.x,y:e.y,type:sa.Line,calculative:{canvas:this,pencil:!0,active:!0,worldAnchors:[e],lineWidth:s*n},fromArrow:t.fromArrow||i.fromArrow,toArrow:t.toArrow||i.toArrow,lineWidth:s}}createDrawingLine(e){this.inactive();const{data:t,options:i}=this.store,n=t.scale,s=t.lineWidth||1;return e.penId=rs(),{id:e.penId,name:"line",lineName:this.drawingLineName,x:e.x,y:e.y,type:sa.Line,calculative:{canvas:this,active:!0,worldAnchors:[e],lineWidth:s*n},fromArrow:t.fromArrow||i.fromArrow,toArrow:t.toArrow||i.toArrow,lineWidth:s}}addRuleLine(e){const{x:t,y:i,scale:n,origin:s}=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-s.y)/(n*10))*(n*10)+s.y);else if(oe.isRuleLine)}alignPenToGrid(e){var i;if(this.store.options.autoAlignGrid&&this.store.data.grid&&!e.type){const n=this.store.data.gridSize||this.store.options.gridSize,{origin:s,scale:a}=this.store.data,{x:o,y:l}=e,c={x:o,y:l},u=this.getPenRect(e),h=parseInt((u.x/n).toFixed()),d=parseInt((u.y/n).toFixed()),f=h*n,p=d*n;c.x=s.x+f*a,c.y=s.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=Zt(t,!0),n=this.store.data.gridSize||this.store.options.gridSize,{origin:s,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+Jd);if(f<0)return;const{x:p,y:g}=this.movingPens[f],m={x:p,y:g};if(o&&!this.movingPens[f].type){const y=this.getPenRect(this.movingPens[f]),v=parseInt((y.x/n).toFixed()),x=parseInt((y.y/n).toFixed()),b=v*n,C=x*n;m.x=s.x+b*a,m.y=s.y+C*a}Object.assign(d,m),(_=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),mFe(d)}),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=Zt(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=Wl(u),f=na(u);if(l!=null&&l.anchorId){const p=this.store.pens[this.store.active[0].id+Jd].calculative.worldAnchors.find(g=>g.id===l.anchorId);p.x===d.x&&p.y===d.y?(i.push(Zt(u,!0)),Du(this.store.active[0],p,u,d),h.push(Zt(u,!0))):p.x===f.x&&p.y===f.y&&(i.push(Zt(u,!0)),Du(this.store.active[0],p,u,f),h.push(Zt(u,!0)))}else if(c!=null&&c.anchorId){const p=this.store.pens[this.store.active[0].id+Jd].calculative.worldAnchors.find(g=>g.id===c.anchorId);p.x===d.x&&p.y===d.y?(i.push(Zt(u,!0)),Du(this.store.active[0],p,u,d),h.push(Zt(u,!0))):p.x===f.x&&p.y===f.y&&(i.push(Zt(u,!0)),Du(this.store.active[0],p,u,f),h.push(Zt(u,!0)))}}o&&(this.calcActiveRect(),this.getSizeCPs()),this.pushHistory({type:Vr.Update,pens:h,initPens:i}),this.store.emitter.emit("translatePens",h)}copyMovedPens(){this.copy(this.store.active.map((e,t)=>{const{x:i,y:n}=this.movingPens[t];return this.updateLines(e),{...e,x:i,y:n}})),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===Rs.CanvasTemplate)&&this.canvasTemplate.init()}hasImage(e,t){var i;return e.image&&e.name!=="gif"?t?e.canvasLayer===Rs.CanvasImageBottom:e.canvasLayer===Rs.CanvasImage:(i=e.children)==null?void 0:i.some(n=>{const s=this.store.pens[n];return s&&this.hasImage(s,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,gP(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,gP(i,!1)}this.store.active=[],e.forEach(i=>{i.calculative.active=!0,gP(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=Wv(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:n,height:s,rotate:a,center:o}=this.activeRect;e.forEach(l=>{const c={x:l.x*n+t,y:l.y*s+i};fo(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.ySs.DisableEdit||!(t.type&&t.calculative.active)&&this.store.options.disableAnchor||t.disableAnchor)return Kr.None;if((this.mouseDown||this.drawingLine)&&t.name==="line"&&i.connectTo){const s=this.findOne(i.connectTo);if(s!=null&&s.calculative&&!(s!=null&&s.calculative.active)){t=s;const a=s.calculative.worldAnchors.find(o=>o.id===i.anchorId);a&&(i=a)}}if(i.twoWay===ch.Disable&&t.name!=="line")return Kr.None;if(t.name==="line"&&i.connectTo){let s=(n=this.findOne(i.connectTo))==null?void 0:n.anchors.find(a=>a.id===i.anchorId);if(s&&s.twoWay)return Kr.None}if(this.drawingLine){if(i.twoWay===ch.Out)return Kr.None}else if(!(this.mouseDown&&this.hoverType===Kr.LineAnchor)){if(i.twoWay===ch.In)return Kr.None}if(pP(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(s=>s.id===i.anchorId),this.store.hoverAnchor?(this.externalElements.style.cursor="crosshair",Kr.NodeAnchor):Kr.None):(this.hotkeyType===ya.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="pointer",Kr.LineAnchor):(this.hotkeyType===ya.AddAnchor?this.externalElements.style.cursor="vertical-text":this.externalElements.style.cursor="crosshair",Kr.NodeAnchor);if(!this.mouseDown&&t.type){if(t.calculative.active&&i.prev&&pP(e,i.prev,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",Kr.LineAnchorPrev;if(t.calculative.active&&i.next&&pP(e,i.next,this.pointSize))return this.store.hoverAnchor=i,this.store.hover=t,this.externalElements.style.cursor="pointer",Kr.LineAnchorNext}return Kr.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},Yl(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),Ev(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){if(!(this.beforeAddPens&&await this.beforeAddPens([e])!=!0)&&!(this.beforeAddPen&&this.beforeAddPen(e)!=!0))return this.makePen(e),this.active([e]),this.render(),i&&this.store.emitter.emit("add",[e]),t&&this.pushHistory({type:Vr.Add,pens:[e]}),e}pushHistory(e){var n;if(this.store.data.locked)return;const{origin:t,scale:i}=this.store.data;e.origin=Zt(t),e.scale=i,e.type!==Vr.Update&&e.pens&&e.pens.forEach(s=>{s.calculative&&(s.calculative.layer=this.store.data.pens.findIndex(a=>a.id===s.id))}),this.store.historyIndex{let a;if(e.initPens)for(const o of e.initPens)o.id===s.id&&(a=o);if(a)for(const o in s)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==Vr.Add||e.type==Vr.Delete||e.type==Vr.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==Vr.Add||e.type==Vr.Delete||e.type==Vr.Update)&&this.activeHistory()}activeHistory(){let e=this.store.histories[this.store.historyIndex+1];const t=[];if(e&&e.type===Vr.Update){e.pens.forEach(n=>{t.push(this.store.pens[n.id])}),this.active(t);return}let i=this.store.histories[this.store.historyIndex];i&&(i.type===Vr.Add||i.type===Vr.Delete)&&(i.pens.forEach(n=>{t.push(this.store.pens[n.id])}),this.active(t))}doEditAction(e,t){switch(this.inactive(),this.store.hoverAnchor=void 0,this.store.hover=void 0,e.type){case Vr.Add:e.pens.forEach(s=>{var l;const a=Zt(s,!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=Vr.Delete;break;case Vr.Update:const i=t?e.initPens:e.pens,n=t?e.pens:e.initPens;i.forEach(s=>{const a=Zt(s,!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)this.store.pens[c]&&(this.store.pens[c].connectedLines=this.store.data.pens[o].lastConnected[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=n.find(u=>u.id===a.id);ZNe.forEach(u=>{a[u]!==c[u]&&this.parent.setValue({id:a.id,[u]:a[u]},{render:!0,doEvent:!1})})}}});break;case Vr.Delete:e.pens.reverse().forEach(s=>{var o,l;const a=Zt(s,!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(s=>{const a=this.store.pens[s.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=Vr.Add;break;case Vr.Replace:{const s=t?e.initPens:e.pens;(t?e.pens:e.initPens).forEach(o=>{var u;const l=Zt(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)}}),s.reverse().forEach(o=>{var c,u;const l=Zt(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}),s.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=Vr.Replace;break}}if(e.type===Vr.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 n;if(e.id||(e.id=rs()),Math.abs(this.store.lastScale-this.store.data.scale)<1e-4&&this.store.sameTemplate&&this.store.templatePens[e.id]&&e.canvasLayer===Rs.CanvasTemplate){e=this.store.templatePens[e.id],this.store.data.pens.push(e),this.updatePenRect(e);return}if(this.store.data.pens.push(e),this.store.pens[e.id]=e,e.path){!e.pathId&&(e.pathId=rs());const s=this.store.data.paths;!s[e.pathId]&&(s[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=Rs.CanvasImageBottom:e.canvasLayer=Rs.CanvasImage,delete e.isBottom),e.template&&(e.canvasLayer=Rs.CanvasTemplate),e.calculative={canvas:this,singleton:(n=e.calculative)==null?void 0:n.singleton},(e.video||e.audio)&&(e.calculative.onended=s=>{this.nextAnimate(s)});for(const s in e)(typeof e[s]!="object"||s==="lineDash")&&(e.calculative[s]=e[s]);if(e.calculative.image=void 0,e.calculative.backgroundImage=void 0,e.calculative.strokeImage=void 0,!e.anchors&&un.anchors[e.name]&&(e.anchors||(e.anchors=[]),un.anchors[e.name](e)),!e.anchors){const s=Zt(this.store.options.defaultAnchors);s.forEach((a,o)=>{a.id=`${o}`,a.penId=e.id}),e.anchors=s}this.updatePenRect(e),!e.anchors&&e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(s=>H9(s,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,un.path2dDraws.line(this.drawingLine)),this.patchFlags=!0)}initLineRect(e){var s;if(!e)return;if(!((s=e.calculative.worldAnchors)!=null&&s.length)){this._del([e]);return}if(!isFinite(e.x)||!isFinite(e.x)||e.x==null||e.y==null)return;const t=Sue(e);e.parentId||Object.assign(e,t);const{fontSize:i,lineHeight:n}=this.store.options;e.fontSize||(e.fontSize=i>=0?i:12,e.calculative.fontSize=e.fontSize*this.store.data.scale),e.lineHeight||(e.lineHeight=n,e.calculative.lineHeight=e.lineHeight),Tl(t),e.calculative.worldRect=t,Bge(e,t),t_(e),Ev(e),e.calculative&&(e.calculative.gradientAnimatePath=void 0),this.store.path2dMap.set(e,un.path2dDraws[e.name](e)),e.calculative.worldAnchors&&(e.anchors=e.calculative.worldAnchors.map(a=>H9(a,e.calculative.worldRect)))}drawingPencil(){wFe(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=Wl(this.drawingLine);let i=na(this.drawingLine);if(i.isTemp&&(this.drawingLine.calculative.worldAnchors.pop(),i=na(this.drawingLine)),!e&&(!i.connectTo&&this.drawingLine.calculative.worldAnchors.pop(),Wl(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=Wl(o),c=na(o);return Z6e(l,t)&&Z6e(c,i)}})){this.drawingLine=void 0,this.render();return}const n=Sue(this.drawingLine);Object.assign(this.drawingLine,n),this.drawingLine.calculative.worldRect=n,this.drawingLine.calculative.activeAnchor=na(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:Vr.Add,pens:Zt([this.drawingLine],!0)})),this.store.path2dMap.set(this.drawingLine,un.path2dDraws[this.drawingLine.name](this.drawingLine)),this.drawingLine=void 0,this.drawingLineName=void 0,this.render()}async finishPencil(){if(this.pencilLine){const e=Tue(this.pencilLine.calculative.worldAnchors,10,0,this.pencilLine.calculative.worldAnchors.length-1);let t=Wl(this.pencilLine);e.unshift({id:t.id,penId:t.penId,x:t.x,y:t.y}),t=na(this.pencilLine),e.push({id:t.id,penId:t.penId,x:t.x,y:t.y}),this.pencilLine.calculative.worldAnchors=Gmt(e),this.pencilLine.calculative.worldAnchors.length>1&&(this.pencilLine.calculative.pencil=!1,this.store.path2dMap.set(this.pencilLine,un.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:Vr.Add,pens:Zt([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,un.htmlElements[e.image]=t,this.imageLoaded(),e.canvasLayer===Rs.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(un.htmlElements[e.image]){const t=un.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===Rs.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,un.htmlElements[e.image]=t,this.imageLoaded(),e.canvasLayer===Rs.CanvasTemplate&&this.templateImageLoaded()}}e.calculative.image=e.image}if(e.backgroundImage!==e.calculative.backgroundImage){if(e.calculative.backgroundImg=void 0,e.backgroundImage)if(un.htmlElements[e.backgroundImage]){const t=un.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,un.htmlElements[e.backgroundImage]=t,this.imageLoaded(),e.canvasLayer===Rs.CanvasTemplate&&this.templateImageLoaded()}}e.calculative.backgroundImage=e.backgroundImage}if(e.strokeImage!==e.calculative.strokeImage){if(e.calculative.strokeImg=void 0,e.strokeImage)if(un.htmlElements[e.strokeImage]){const t=un.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,un.htmlElements[e.strokeImage]=t,this.imageLoaded(),e.canvasLayer===Rs.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===sa.Line&&e.borderWidth&&(e.calculative.borderWidth=e.borderWidth*t)}updatePenRect(e,{worldRectIsReady:t,playingAnimate:i}={}){t?$Y(e):pFe(e),i||this.setCalculativeByScale(e),K9(e),eTe(this.store.pens,e),t_(e),Ev(e),un.path2dDraws[e.name]&&this.store.path2dMap.set(e,un.path2dDraws[e.name](e)),e.calculative.patchFlags=!0,this.patchFlags=!0,e.children&&e.children.forEach(n=>{const s=this.store.pens[n];s&&this.updatePenRect(s,{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)}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=Sv(this.store.options.padding);const n=this.store.data.width||this.store.options.width,s=this.store.data.height||this.store.options.height;this.width<(n+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+n*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+s*this.store.data.scale=i&&e<=n))return;this.calibrateMouse(t);const s=e/this.store.data.scale;this.store.data.scale=e,this.store.data.center=t,(o=this.store.clipboard)!=null&&o.pos&&tZ(this.store.clipboard.pos,s,t),tZ(this.store.data.origin,s,t),this.store.data.pens.forEach(l=>{if(!l.parentId){if(TI(l,s,t),l.onScale&&l.onScale(l),l.isRuleLine){const c=1/s,u=l.calculative.worldRect.center;l.width&&l.height||TI(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:n}=this.store.options;if(!(e>=i&&e<=n))return;const s=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(TI(a,s,t),a.onScale&&a.onScale(a),a.isRuleLine){const o=s>1?1:1/s/s,l=a.calculative.worldRect.center;a.width&&a.height||TI(a,o,l)}this.execPenResize(a)}}),this.calcActiveRect()}rotatePens(e){this.initPens||(this.initPens=Zt(this.getAllByPens(this.store.active))),this.activeRect.rotate=R0(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:Vr.Update,pens:Zt(this.getAllByPens(this.store.active)),initPens:this.initPens}),this.initPens=void 0},200)}resizePens(e){if(this.initPens||(this.initPens=Zt(this.store.active,!0)),!this.initActiveRect){this.initActiveRect=Zt(this.activeRect);return}const t={x:this.mouseDown.x,y:this.mouseDown.y},i={x:e.x,y:e.y};let n=i.x-t.x,s=i.y-t.y;const a=Zt(this.initActiveRect);if(cTe(a,n,s,this.resizeIndex),Tl(a),!this.store.options.disableDock){this.clearDock();const f=this.customResizeDock||K0t;this.dock=f(this.store,a,this.store.active,this.resizeIndex);const{xDock:p,yDock:g}=this.dock;if(p){n+=p.step;const m=this.store.pens[p.penId];m.calculative.isDock=!0}if(g){s+=g.step;const m=this.store.pens[g.penId];m.calculative.isDock=!0}}const o=this.activeRect.width,l=this.activeRect.height;let c=n-this.lastOffsetX,u=s-this.lastOffsetY;if(this.lastOffsetX=n,this.lastOffsetY=s,(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,cTe(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 g={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.xg.x+g.width&&(this.activeRect.width=this.activeRect.width-(this.activeRect.x+this.activeRect.width-(g.x+g.width)),this.activeRect.x=g.x+g.width-this.activeRect.width,this.activeRect.ex=this.activeRect.x+this.activeRect.width),this.activeRect.y+this.activeRect.height>g.y+g.height&&(this.activeRect.height=this.activeRect.height-(this.activeRect.y+this.activeRect.height-(g.y+g.height)),this.activeRect.y=g.y+g.height-this.activeRect.height,this.activeRect.ey=this.activeRect.y+this.activeRect.height)}}Tl(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),Yl(f.calculative.worldRect),Tl(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:Vr.Update,pens:Zt(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=Zt(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=>{x9(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 n=Zt(this.initActiveRect);_S(n,t,i);let s=!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};n.xh.x+h.width&&(n.x=h.x+h.width-n.width,s=!0),n.y+n.height>h.y+h.height&&(n.y=h.y+h.height-n.height,s=!0)}}const a={x:n.x-this.activeRect.x,y:n.y-this.activeRect.y};if(!this.store.options.disableDock&&!s){this.clearDock();const c=this.customMoveDock||W0t;this.dock=c(this.store,n,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+=Jd,e.parentId&&t.find(i=>i.id===e.parentId)&&(e.parentId+=Jd),e.children&&(e.children=e.children.map(i=>i+Jd)),e.connectedLines&&(e.connectedLines=e.connectedLines.map(i=>(t.find(n=>n.id===i.lineId)&&(i.lineId+=Jd),i))),e.type&&e.calculative.worldAnchors&&(e.calculative.worldAnchors=e.calculative.worldAnchors.map(i=>(i.connectTo&&t.find(n=>n.id===i.connectTo)&&(i.connectTo+=Jd),i)))}initMovingPens(){var i,n;if(!this.store.options.moveConnectedLine&&!this.canMoveLine)for(let s=0;s{this.changeIdsByMoving(s,t),this.store.pens[s.id]=s,s.calculative.canvas=this;const a={globalAlpha:.5};s.lineWidth===0&&(a.lineWidth=1),(s.name.endsWith("Dom")||Dpt.includes(s.name)||this.store.options.domShapes.includes(s.name)||s.image)&&(a.name="rectangle",a.onDestroy=void 0),this.updateValue(s,a),s.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=Zt(this.store.active,!0)),(o=this.store.activeAnchor)!=null&&o.connectTo){const d=this.store.pens[this.store.activeAnchor.connectTo];EP(d,oS(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,n=(u=(c=this.store.pens[this.store.activeAnchor.penId])==null?void 0:c.connectedLines)==null?void 0:u.filter(d=>d.anchor===i);n&&n.length>0&&n.forEach(d=>{const f=this.store.pens[d.lineId];EP(this.store.pens[this.store.activeAnchor.penId],this.store.activeAnchor,f,oS(f,d.lineAnchor))});const s=this.store.active[0];Wl(s);const a=na(s);if(s.lineName==="polyline"&&!t.shiftKey)Vmt(s,this.store.activeAnchor,e);else{let d=0,f=0;if(s.lineName==="line"){let p=s.calculative.worldAnchors.findIndex(m=>m.id===this.store.activeAnchor.id);p===0&&(p=2);let g=s.calculative.worldAnchors[p-1];if(t.ctrlKey&&t.shiftKey){let m=Zt(e);this.getSpecialAngle(m,g),d=m.x-this.store.activeAnchor.x,f=m.y-this.store.activeAnchor.y}else if(!t.ctrlKey&&t.shiftKey){let m={x:e.x,y:g.y};d=m.x-this.store.activeAnchor.x,f=m.y-this.store.activeAnchor.y}else if(t.ctrlKey&&!t.shiftKey){let m={x:g.x,y:e.y};d=m.x-this.store.activeAnchor.x,f=m.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);G9(this.store.activeAnchor,d,f),this.store.hover&&this.store.hoverAnchor&&this.store.hoverAnchor.penId!==this.store.activeAnchor.penId&&(this.store.hoverAnchor.type===vv.Line?(d=e.x-this.store.activeAnchor.x,f=e.y-this.store.activeAnchor.y,sX(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),G9(this.store.activeAnchor,d,f),a.prev=void 0,s.lineName!=="polyline"&&((h=this[s.lineName])==null||h.call(this,this.store,s)))}this.patchFlagsLines.add(s),this.store.path2dMap.set(s,un.path2dDraws[s.name](s)),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:Vr.Update,pens:Zt(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=Zt(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,fo(this.store.activeAnchor.next,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===IS.Bilateral&&this.prevAnchor){const i=R0(e,this.store.activeAnchor),n=R0(this.prevAnchor,this.store.activeAnchor);this.store.activeAnchor.next.x=this.nextAnchor.x,this.store.activeAnchor.next.y=this.nextAnchor.y,fo(this.store.activeAnchor.next,i-n,this.store.activeAnchor)}}const t=this.store.active[0];this.patchFlagsLines.add(t),this.store.path2dMap.set(t,un.path2dDraws[t.name](t)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:Vr.Update,pens:Zt(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=Zt(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,fo(this.store.activeAnchor.prev,180,this.store.activeAnchor);else if(this.store.activeAnchor.prevNextType===IS.Bilateral&&this.nextAnchor){const i=R0(e,this.store.activeAnchor),n=R0(this.nextAnchor,this.store.activeAnchor);this.store.activeAnchor.prev.x=this.prevAnchor.x,this.store.activeAnchor.prev.y=this.prevAnchor.y,fo(this.store.activeAnchor.prev,i-n,this.store.activeAnchor)}}const t=this.store.active[0];this.patchFlagsLines.add(t),this.store.path2dMap.set(t,un.path2dDraws[t.name](t)),this.render(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.pushHistory({type:Vr.Update,pens:Zt(this.store.active,!0),initPens:this.initPens}),this.initPens=void 0},200)}async setAnchor(e){var n;const t=[Zt(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===sa.Line&&((n=i.calculative.worldAnchors)==null?void 0:n.length)<=2?this.delete([i]):(D0t(i,this.store.hoverAnchor),i.type===sa.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===sa.Line){this.store.activeAnchor=w0t(i,this.store.pointAt,this.store.pointAtIndex),this.initLineRect(i);const s={x:e.x,y:e.y};this.getHover(s)}else{const s={id:rs(),x:e.x,y:e.y};this.store.activeAnchor=P0t(i,s)}}this.hotkeyType=ya.None,this.render(),i&&this.pushHistory({type:Vr.Update,pens:[Zt(i,!0)],initPens:t})}checkDisconnect(e,t){if(e.id.indexOf(Jd)>0){const i=e.id;e=this.store.pens[i.replace(Jd,"")]}e.anchors.forEach(i=>{if(i.connectTo&&!t.find(n=>n.id===i.connectTo||n.id===i.connectTo+Jd)){const n=this.store.pens[i.connectTo];if(!n||n.type)return;EP(n,oS(n,i.anchorId),e,i)}})}translatePens(e=this.store.active,t,i,n){if(!e||!e.length||e.some(l=>{if(l.locked>=Ss.DisableMove)return!0}))return;const a=!n&&Zt(e,!0);this.activeRect&&_S(this.activeRect,t,i);const o=this.getAllByPens(e);e.forEach(l=>{var c,u;if(!(l.locked>=Ss.DisableMove)){if(l.type===sa.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine||l.isRuleLine)return;tTe(l,t,i),this.checkDisconnect(l,o),this.store.path2dMap.set(l,un.path2dDraws[l.name](l)),n||(this.initLineRect(l),(c=l.connectedLines)==null||c.forEach(h=>{const d=this.store.pens[h.lineId];this.initLineRect(d)}))}else _S(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),n||(this.pushHistory({type:Vr.Update,pens:Zt(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 n=this.getAllByPens(e);e.forEach(s=>{var a;if(s.type===sa.Line){if(!this.store.options.moveConnectedLine&&!this.canMoveLine)return;tTe(s,t,i),this.checkDisconnect(s,n),this.store.path2dMap.set(s,un.path2dDraws[s.name](s))}else _S(s.calculative.worldRect,t,i),this.updatePenRect(s,{worldRectIsReady:!0}),s.calculative.x=s.x,s.calculative.y=s.y,s.calculative.initRect&&(s.calculative.initRect.x=s.calculative.x,s.calculative.initRect.y=s.calculative.y,s.calculative.initRect.ex=s.calculative.x+s.calculative.width,s.calculative.initRect.ey=s.calculative.y+s.calculative.height);(a=s.onMove)==null||a.call(s,s)})}calcAutoAnchor(e,t,i,n){const s=Wl(e),a=na(e),o=SP(i,t===s?a:s);o&&(t.x=o.x,t.y=o.y,t.prev=void 0,t.next=void 0,n?n.anchor=o.id:Du(i,o,e,t),this[e.lineName]&&this[e.lineName](this.store,e),this.store.path2dMap.set(e,un.path2dDraws.line(e)),this.initLineRect(e))}restoreNodeAnimate(e){var t,i;if(e.calculative.initRect){if(e.keepAnimateState)for(const n in e)e.calculative[n]!==void 0&&n!=="x"&&n!=="y"&&n!=="width"&&n!=="height"&&n!=="initRect"&&(typeof e[n]!="object"||n==="lineDash")&&(n==="fontSize"||n==="lineWidth"?e[n]=e.calculative[n]/e.calculative.canvas.store.data.scale:e[n]=e.calculative[n]);else{const n=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?n&&_Fe(e,n,e.calculative.worldRect):e.calculative.rotate=e.rotate;const s=Zt(this.store.animateMap.get(e));s&&(s.id=e.id,this.parent.setValue(s,{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,xz(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(n=>{const s=this.store.pens[n];s&&this.updateLines(s,t)}),e.connectedLines&&e.connectedLines.forEach((n,s)=>{const a=this.store.pens[n.lineId];if(!a||a.calculative.active)return;const o=oS(a,n.lineAnchor);if(!o)return;if(!o.connectTo){e.connectedLines.splice(s,1);return}if(a.autoFrom){const d=Wl(a);d.id===o.id&&this.calcAutoAnchor(a,d,e,n)}if(a.autoTo){const d=na(a);d.id===o.id&&this.calcAutoAnchor(a,d,e,n)}const l=oS(e,n.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),G9(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=Wl(a),f=na(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,un.path2dDraws[a.name](a)),this.patchFlagsLines.add(a),a.calculative.gradientSmooth&&(a.calculative.gradientAnimatePath=Fge(a)),t&&Eue(a)})}calcActiveRect(){const e=this.store.active.filter(t=>(!t.locked||t.locked{fo(n,t,i.center)}),this.initLineRect(e),$Y(e)):(e.calculative.rotate?e.calculative.rotate+=t:e.calculative.rotate=t,fo(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(n=>{const s=this.store.pens[n];this.rotatePen(s,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 n,s,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,(n=i.calculative.media)==null||n.play(),(s=i.onStartVideo)==null||s.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=Zt(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=Zt(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 n in i)!["duration","x","y","width","height","rotate"].includes(n)&&!t[n]&&(t[n]=e[n])}),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 n of this.store.animates)if(!n.calculative.pause){if(n.calculative.active&&!n.type&&!this.movingPens&&(i=!0),!n.type)O0t(n,e)?n.calculative.patchFlags&&(Tl(n.calculative.worldRect),this.updatePenRect(n,{worldRectIsReady:!0,playingAnimate:!0})):(requestAnimationFrame(()=>{this.restoreNodeAnimate(n)}),t.push(n),this.nextAnimate(n)),this.updateLines(n,!0);else if(!N0t(n)){if(n.keepAnimateState){for(const s in n)n.calculative[s]!==void 0&&s!=="length"&&(typeof n[s]!="object"||s==="lineDash")&&(s==="lineWidth"?n[s]=n.calculative[s]/n.calculative.canvas.store.data.scale:n[s]=n.calculative[s]);$Y(n)}else for(const s in n)(typeof n[s]!="object"||s==="lineDash")&&(s==="lineWidth"?n.calculative[s]=n[s]*n.calculative.canvas.store.data.scale:n.calculative[s]=n[s]);t.push(n),this.nextAnimate(n)}this.patchFlags=!0}i&&this.calcActiveRect(),t.forEach(n=>{this.store.animates.delete(n)}),this.render(!1),this.animateRendering=!1,this.animate()})}get clipboardName(){return"meta2d-clipboard"}async copy(e,t=!0){const i=rs(),{origin:n,scale:s}=this.store.data;this.store.clipboard=void 0,localStorage.removeItem(this.clipboardName),sessionStorage.setItem("page",i);let a=this.getAllByPens(Zt(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),a.forEach(l=>{delete l.copyIndex});const o={meta2d:!0,pens:a,origin:Zt(n),scale:s,page:i,initRect:Zt(this.activeRect),offset:10};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 o;let e,t;if(navigator.clipboard&&!this.store.options.disableClipboard&&!navigator.userAgent.includes("Firefox"))try{e=await((o=navigator.clipboard)==null?void 0:o.readText())}catch{e=localStorage.getItem(this.clipboardName)}else e=localStorage.getItem(this.clipboardName);if(e){try{t=JSON.parse(e)}catch(l){console.warn("剪切板数据不是json",l.message);return}if(!t||!t.meta2d)return}else return;if(this.beforeAddPens&&await this.beforeAddPens(t.pens)!=!0)return;let i,n;this.store.clipboard&&(i=this.store.clipboard.offset+10,n=this.store.clipboard.pos),this.store.clipboard=Zt(t),sessionStorage.getItem("page")!==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),n&&(this.store.clipboard.pos=n)):(this.store.clipboard.offset=0,this.pasteOffset=!0);const a=this.store.clipboard.pens.filter(l=>!l.parentId);for(const l of a)this.pastePen(l,void 0);sessionStorage.setItem("page",t.page),this.active(a),this.pushHistory({type:Vr.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(...Zt(j1(i,this.store),!0));return t.concat(e)}getAllFollowersByPens(e,t=!0){const i=e;for(const n of e){let s=Lge(n,this.store);t&&(s=Zt(s,!0));for(const a of s)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(n=>n.id);t.pop();const i=e[e.length-1];i.followers?t.forEach(n=>{i.followers.includes(n)||i.followers.push(n)}):i.followers=t}}changeLineAnchors(e,t,i){if(Array.isArray(t.connectedLines))for(let n=0;no.id===s);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(n,1),n--}}changeNodeConnectedLine(e,t,i){var o;const n=t.anchors[0],s=t.anchors[t.anchors.length-1],a=[n,s];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(s=>!s.locked)),!e||!e.length))return;const n=[];if(this._del(e,n,t),this.initImageCanvas(n),this.initTemplateCanvas(n),this.inactive(),this.clearHover(),this.render(),i){if(n.length===0)return;this.pushHistory({type:Vr.Delete,pens:n})}this.store.emitter.emit("delete",e)}_del(e,t,i){e&&e.forEach(n=>{if(n.type&&(n.lastConnected={}),n.parentId)if(this.getLockedParent(n)){console.warn("父节点锁定");return}else{const a=pp(n),o=a.children.indexOf(n.id);a.children.splice(o,1),t&&this.getDelPens(n,t),this.delForce(n)}else{if(!i&&n.locked)return;t&&this.getDelPens(n,t),this.delForce(n)}})}getDelPens(e,t){if(!e)return;if(this.store.data.pens.findIndex(n=>n.id===e.id)>-1){const n=this.store.pens[e.id];n.calculative.active=void 0,t.push(n)}e.children&&e.children.forEach(n=>{this.getDelPens(this.store.pens[n],t)})}getLockedParent(e){if(!e.parentId)return!1;const t=pp(e);if(t.locked)return t;this.getLockedParent(t)}delForce(e){var i;if(!e)return;const t=this.store.data.pens.findIndex(n=>n.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]),this.store.animates.delete(e),this.store.animateMap.delete(e),e.children&&e.children.forEach(n=>{this.delForce(this.store.pens[n])}),(i=e.onDestroy)==null||i.call(e,e)}delConnectedLines(e){var t;if(e.connectedLines)for(let i=0;il.id===s);(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=oS(a,s),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,n)=>{var a;if(!i.connectTo)return;const s=this.store.pens[i.connectTo];s&&((a=s.calculative.worldAnchors)==null||a.forEach(o=>{EP(s,o,e,i)}))}))}convertSpecialCharacter(e){var t={lt:"<",gt:">",nbsp:" ",amp:"&",quot:'"'};return e.replace(/&(lt|gt|nbsp|amp|quot);/gi,function(i,n){return t[n]})}createInput(){this.inputParent.classList.add("meta2d-input"),this.inputRight.classList.add("right"),this.inputDiv.classList.add("input-div"),this.inputParent.appendChild(this.inputDiv),this.inputParent.appendChild(this.inputRight),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.inputRight.onmousedown=this.stopPropagation,this.dropdown.onmousedown=this.stopPropagation,this.inputRight.style.transform="rotate(135deg)";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 n=t.target.innerText,s=n.replace(/[^0-9]/g,"");n!==s&&(t.preventDefault(),t.target.innerText=s)}if(navigator.userAgent.includes("Firefox")){if(!t.target.innerText.trim()){let n=this.inputDiv.offsetWidth/2;window.getComputedStyle(this.inputDiv,null).textAlign!=="center"&&(n=0),this.inputDiv.innerHTML=`
`}}else if(t.target.innerText)this.inputDiv.style.paddingTop="";else{let n=window.getComputedStyle(this.inputDiv,null);n.justifyContent==="center"&&(this.inputDiv.style.paddingTop=` ${this.inputDiv.offsetHeight/2-parseFloat(n.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",this.inputRight.style.transform="rotate(135deg)"):i!=null&&i.dropdownList&&this.store.data.locked&&(this.dropdown.style.display="block",this.inputRight.style.transform="rotate(315deg)"),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;et.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 n,s,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],(n=i.onChangeId)==null||n.call(i,i,e,t),delete this.store.pens[e],i.parentId){const h=this.store.pens[i.parentId],d=(s=h.children)==null?void 0:s.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.type===sa.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];K9(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,g;const i=this.getPenRect(e),n=e.name;Object.assign(e,t);const s=n!==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 m in t)m.indexOf(".")===-1?(m==="rotate"?d=e.calculative.rotate||0:m==="canvasLayer"||m==="isBottom"||m==="showChild"?h=!0:m==="image"&&(f=!0),(typeof e[m]!="object"||m==="lineDash")&&(e.calculative[m]=t[m]),Rpt.includes(m)&&(o=!0),["name","borderRadius","lineSmooth","close"].includes(m)&&(a=!0),Ipt.includes(m)&&(u=!0),Ppt.includes(m)&&(l=!0),wpt.includes(m)&&(c=!0),e.image&&e.name!=="gif"&&["globalAlpha","flipY","flipX","x","y","width","height","iconWidth","iconHeight","imageRatio","iconLeft","iconTop","iconAlign"].includes(m)&&(f=!0)):(delete e[m],yue(e,m,t[m])),m.split(".")[0]==="anchors"&&K9(e);if(this.setCalculativeByScale(e),s&&((p=e.onDestroy)==null||p.call(e,e),Opt(e)),u){const m={x:t.x??i.x,y:t.y??i.y,width:t.width??i.width,height:t.height??i.height};this.setPenRect(e,m,!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&&t_(e),c&&eTe(this.store.pens,e),a&&un.path2dDraws[e.name]&&this.store.path2dMap.set(e,un.path2dDraws[e.name](e)));if(d!==void 0){const m=e.calculative.rotate;e.calculative.rotate=d,this.rotatePen(e,m-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=Rs.CanvasImageBottom,e.calculative.canvasLayer=Rs.CanvasImageBottom),e.canvasLayer===Rs.CanvasImageBottom?this.canvasImageBottom.init():e.canvasLayer===Rs.CanvasImage&&this.canvasImage.init()),(t.canvasLayer!==void 0||e.canvasLayer===Rs.CanvasTemplate)&&this.initTemplateCanvas([e]),t.zIndex!==void 0&&(g=e.calculative.singleton)!=null&&g.div&&Po(e,e.calculative.singleton.div)}execPenResize(e){var t,i;(t=e.onResize)==null||t.call(e,e),(i=e.children)==null||i.forEach(n=>{const s=this.store.pens[n];s&&this.execPenResize(s)})}setPenRect(e,t,i=!0){if(e.parentId)Object.assign(e,t);else{const{origin:n,scale:s}=this.store.data;e.x=n.x+t.x*s,e.y=n.y+t.y*s,e.width=t.width*s,e.height=t.height*s}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,n){const s=u_(this.store.data.pens),a=this.store.data.scale;if(!isFinite(s.width))throw new Error("can not to png, because width is not finite");const o=Zt(s),l=this.store.data,c=i&&!l.background&&this.store.bkImg;let u=!1,h=!1;if(c){if(s.x+=l.x,s.y+=l.y,Yl(s),Jy(s,this.canvasRect,!0))Object.assign(s,this.canvasRect);else{const b=bz([...Wv(s),...Wv(this.canvasRect)]);Object.assign(s,b)}u=s.x===0,h=s.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&&(s.x=this.store.data.origin.x,s.y=this.store.data.origin.y,s.width=d*this.store.data.scale,s.height=f*this.store.data.scale);const g=Zt(s),m=Sv(e);s.x-=m[3]*a,s.y-=m[0]*a,s.width+=(m[3]+m[1])*a,s.height+=(m[0]+m[2])*a;const _=(n||1920)/s.width;s.width*=_,s.height*=_,Yl(s);const y=document.createElement("canvas");if(y.width=s.width,y.height=s.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.options.background;if(x&&(v.save(),v.fillStyle=x,p?v.fillRect(0,0,g.width+(m[1]+m[3])*a,g.height+(m[0]+m[2])*a):v.fillRect(0,0,o.width+(m[3]+m[1])*a,o.height+(m[0]+m[2])*a),v.restore()),c)if(p)v.drawImage(this.store.bkImg,m[3]*a||0,m[0]*a||0,g.width,g.height);else{const b=s.x<0?-s.x:0,C=s.y<0?-s.y:0;v.drawImage(this.store.bkImg,b,C,this.canvasRect.width,this.canvasRect.height)}c?p?v.translate(-o.x+m[3]*a||0,-o.y+m[0]*a||0):v.translate((u?l.x:-o.x)+m[3]*a||0,(h?l.y:-o.y)+m[0]*a||0):v.translate(-s.x,-s.y);for(const b of this.store.data.pens){if(!nZ(b,this.store)||b.visible==!1)continue;const{active:C}=b.calculative;b.calculative.active=!1,b.calculative.img?rZ(v,b):aS(v,b,!0),b.calculative.active=C}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 n=this.getAllByPens(e);let s=n.map(f=>f.id);const a=u_(n);if(!isFinite(a.width))throw new Error("can not to png, because width is not finite");const o=Zt(a),l=Sv(t);a.x-=l[3],a.y-=l[0],a.width+=l[3]+l[1],a.height+=l[0]+l[2],Yl(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.options.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(s.includes(f.id)){if(!nZ(f,this.store)||f.visible==!1)continue;const{active:p}=f.calculative;f.calculative.active=!1,f.calculative.img?rZ(h,f):aS(h,f),f.calculative.active=p}return u.toDataURL()}toggleAnchorMode(){var e;if(this.hotkeyType)this.hotkeyType===ya.AddAnchor&&(this.hotkeyType=ya.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=ya.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=[Zt(this.store.active[0],!0)];this.store.activeAnchor.prev?this.store.activeAnchor.next||(this.store.activeAnchor.next={...this.store.activeAnchor.prev},fo(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},fo(this.store.activeAnchor.prev,180,this.store.activeAnchor),this.initLineRect(this.store.active[0]),this.patchFlags=!0),this.pushHistory({type:Vr.Update,pens:[Zt(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=[Zt(this.store.active[0],!0)];this.hoverType===Kr.LineAnchorPrev?(this.store.activeAnchor.prev=void 0,this.initLineRect(this.store.active[0]),this.patchFlags=!0):this.hoverType===Kr.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:Vr.Update,pens:[Zt(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=IS.Mirror),this.store.activeAnchor.prevNextType=(this.store.activeAnchor.prevNextType+1)%3)}gotoView(e,t){let i=u_(this.store.data.pens);if(!isFinite(i.width))throw new Error("can not move view, because width is not finite");const n=this.store.data.width||this.store.options.width,s=this.store.data.height||this.store.options.height;n&&s&&(i={x:this.store.data.origin.x,y:this.store.data.origin.y,width:n*this.store.data.scale,height:s*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.magnifier=!0,this.externalElements.style.cursor="default",this.render()}hideMagnifier(){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(Jy(c.calculative.worldRect,this.dragRect,!0))return c.type===sa.Line&&!this.store.options.dragAllIn?vse(c,this.dragRect):!0});if(!e.length)return;const t=this.parent.getRect(e),i=this.store.data.scale,n=this.store.data.width||this.store.options.width,s=this.store.data.height||this.store.options.height;let a=(Math.floor(t.x)-this.store.data.origin.x)/i/n,o=(Math.floor(t.y)-this.store.data.origin.y)/i/s,l={x:a,y:o,width:(Math.ceil(t.width)+1)/i/n,height:(Math.ceil(t.height)+1)/i/s,children:e.map(c=>c.id),id:rs(),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*n,l.rightValue=(1-(l.x+l.width))*i*n):l.x<.5?(l.left=!0,l.leftValue=(l.x-0)*i*n):(l.right=!0,l.rightValue=(1-(l.x+l.width))*i*n),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*s,l.bottomValue=(1-(l.y+l.height))*i*s):l.y<.5?(l.top=!0,l.topValue=(l.y-0)*i*s):(l.bottom=!0,l.bottomValue=(1-(l.y+l.height))*i*s),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,n=this.store.data.height||this.store.options.height;let s=(e.x-this.store.data.origin.x)/t/i,a=(e.y-this.store.data.origin.y)/t/n;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"){s<-.1&&(s=-.1);let u=s-o.x;if(o.width-=u,o.width<.01){o.width=.01;return}o.x=s}this.canvasImage.currentFit==="right"&&(s>1.1&&(s=1.1),o.width=s-o.x,o.width<=.01&&(o.width=.01));let l={x:o.x*i*t+this.store.data.origin.x,y:o.y*n*t+this.store.data.origin.y,width:o.width*i*t,height:o.height*n*t};Yl(l);const c=this.store.data.pens.filter(u=>{if(u.parentId||u.isRuleLine)return!1;if(Jy(u.calculative.worldRect,l,!0))return u.type===sa.Line&&!this.store.options.dragAllIn?vse(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*n,o.bottomValue=(1-(o.y+o.height))*t*n):o.y<.5?(o.top=!0,o.topValue=(o.y-0)*t*n):(o.bottom=!0,o.bottomValue=(1-(o.y+o.height))*t*n),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,n=(this.mouseDown.y-this.store.data.origin.y)/this.store.data.scale/t,s=-1,a=-1;(o=this.store.data.fits)==null||o.forEach((l,c)=>{l.ex=null,l.ey=null,Ny({x:i,y:n},l)&&(s=c),l.active&&(a=c)}),s!==-1&&s!==a?(this.canvasImage.activeFit=this.store.data.fits[s],this.store.data.fits[s].active=!0,a!==-1&&(this.store.data.fits[a].active=!1),this.store.emitter.emit("fit",this.store.data.fits[s])):s===-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;switch(this.scroll&&this.scroll.destroy(),(e=this.tooltip)==null||e.destroy(),(t=this.dialog)==null||t.destroy(),(i=this.title)==null||i.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 gS.Document:document.removeEventListener("keydown",this.onkeydown),document.removeEventListener("keyup",this.onkeyup);break;case gS.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)}}function sgt(r,e){const t=e||new Path2D;r.onDestroy||(r.onDestroy=lgt,r.onMove=bTe,r.onRotate=bTe,r.onMouseEnter=cgt,r.onMouseLeave=ugt,r.onMouseMove=dgt,r.onMouseUp=hgt,r.onInput=ogt);let i=r.calculative.borderRadius||0,n=i;const{x:s,y:a,width:o,height:l,ex:c,ey:u}=r.calculative.worldRect,{x:h}=r.calculative.worldTextRect;i<1&&(i=o*i,n=l*n);let d=i{if(r.followers){let i=r.followers.findIndex(n=>n===t.id);if(i!==-1){const n=r.calculative.canvas.store.pens[t.id+Jd];n&&n.calculative&&(Jy(n.calculative.worldRect,r.calculative.worldRect,!0)||r.followers.splice(i,1))}}})}function hgt(r){const e=r.calculative.canvas.store.active;e&&e.length&&e.forEach(t=>{const i=r.calculative.canvas.store.pens[t.id+Jd];if(i&&i.calculative){let n=Zt(r.calculative.worldRect);n.x-=1,n.y-=1,n.width+=2,n.height+=2,Jy(i.calculative.worldRect,n,!0)&&(r.followers||(r.followers=[]),r.followers.includes(t.id)||r.followers.push(t.id))}})}function dgt(r,e){}const $c={};function fgt(r){r.onDestroy||(r.onDestroy=pgt,r.onMove=CTe,r.onResize=mgt,r.onRotate=CTe,r.onValue=ggt,r.onChangeId=_gt);const e=new Path2D;if(r.image){if(!$c[r.id]){const t=new Image;t.crossOrigin="anonymous",t.src=r.image,r.calculative.canvas.parent.store.options.cdn&&!(r.image.startsWith("http")||r.image.startsWith("//")||r.image.startsWith("data:image"))&&(t.src=r.calculative.canvas.parent.store.options.cdn+r.image),$c[r.id]=t,t.onload=()=>{var i;$c[r.id]===t&&(r.calculative.img=t,r.calculative.imgNaturalWidth=t.naturalWidth||r.iconWidth,r.calculative.imgNaturalHeight=t.naturalHeight||r.iconHeight,(i=r.calculative.canvas.externalElements)==null||i.parentElement.appendChild(t),Kk(r,t))}}return r.calculative.patchFlags&&$c[r.id]&&Kk(r,$c[r.id]),e}}function pgt(r){$c[r.id]&&($c[r.id].remove(),$c[r.id]=void 0)}function CTe(r){$c[r.id]&&Kk(r,$c[r.id])}function mgt(r){$c[r.id]&&Kk(r,$c[r.id])}function ggt(r){$c[r.id]&&(Kk(r,$c[r.id]),$c[r.id].getAttribute("src")!==r.image&&($c[r.id].src=r.image))}function _gt(r,e,t){$c[e]&&($c[t]=$c[e],delete $c[e])}function Kk(r,e){e.style.objectFit=r.imageRatio?"contain":"fill",Po(r,e)}function vgt(r,e){return r.onResize||(r.onResize=DFe,r.onValue=ygt),J5(r,e)}function DFe(r){const e=r.anchors.filter(t=>t.flag!==1);OFe(r),r.anchors=r.anchors.concat(...e)}function ygt(r){DFe(r),K9(r)}function OFe(r){const e=[],{x:t,y:i,width:n,height:s}=r,a=xgt(r),o=5;for(let h=0;ht+n-a&&(f=hX(t+n-a,f+a,d,a,-1)),e.push({id:String(e.length),flag:1,penId:r.id,x:(d-t)/n,y:(f-i)/s})}const l=3;for(let h=0;hi+s-a&&(f=uX(f-a,i+s-a,d,a)),e.push({id:String(e.length),flag:1,penId:r.id,x:(f-t)/n,y:(d-i)/s})}const c=5;for(let h=0;ht+n-a&&(f=hX(t+n-a,f-a,d,a)),e.push({id:String(e.length),flag:1,penId:r.id,x:(d-t)/n,y:(f-i)/s})}const u=3;for(let h=0;hi+s-a&&(f=uX(f+a,i+s-a,d,a,-1)),e.push({id:String(e.length),flag:1,penId:r.id,x:(f-t)/n,y:(d-i)/s})}r.anchors=e}function xgt(r){let e=r.calculative.borderRadius||0,t=r.calculative.borderRadius||0;const{width:i,height:n}=r;r.calculative.borderRadius<1&&(e=i*r.calculative.borderRadius,t=n*r.calculative.borderRadius);let s=e({id:n+"",x:t,y:i,penId:r.id}))}function Agt(){return{rectangle:J5,square:Tpt,circle:Mpt,svgPath:umt,diamond:hmt,triangle:dmt,pentagon:pmt,pentagram:gmt,hexagon:vmt,leftArrow:ymt,rightArrow:xmt,twowayArrow:bmt,message:Cmt,cloud:Amt,file:Smt,people:Tmt,line:Pmt,iframe:jmt,video:Zmt,gif:fgt,mindNode:vgt,mindLine:bgt,mindNode2:J5,panel:sgt}}function Sgt(){return{triangle:fmt,pentagon:mmt,pentagram:bFe,mindNode:OFe,mindLine:Cgt}}var Wc;(function(r){r[r.Link=0]="Link",r[r.SetProps=1]="SetProps",r[r.StartAnimate=2]="StartAnimate",r[r.PauseAnimate=3]="PauseAnimate",r[r.StopAnimate=4]="StopAnimate",r[r.JS=5]="JS",r[r.GlobalFn=6]="GlobalFn",r[r.Emit=7]="Emit",r[r.StartVideo=8]="StartVideo",r[r.PauseVideo=9]="PauseVideo",r[r.StopVideo=10]="StopVideo",r[r.SendPropData=11]="SendPropData",r[r.SendVarData=12]="SendVarData",r[r.Navigator=13]="Navigator",r[r.Dialog=14]="Dialog",r[r.SendData=15]="SendData",r[r.PostMessage=16]="PostMessage",r[r.PostMessageToParent=17]="PostMessageToParent"})(Wc||(Wc={}));class Egt{constructor(e){Xe(this,"parent");Xe(this,"box");Xe(this,"boxWidth",320);Xe(this,"boxHeight",180);Xe(this,"ratio",this.boxWidth/this.boxHeight);Xe(this,"padding",5);Xe(this,"img");Xe(this,"isShow");Xe(this,"isDown");Xe(this,"view");Xe(this,"onMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDown=!0});Xe(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}});Xe(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}});Xe(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:n}=e;const s=this.parent.store.data.width||this.parent.store.options.width,a=this.parent.store.data.height||this.parent.store.options.height;if(s&&a)i=i/this.boxWidth*s*this.parent.store.data.scale+this.parent.store.data.origin.x+this.parent.store.data.x,n=n/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,n=n/this.boxHeight*o.height+o.y+this.parent.store.data.y}this.parent.scale(this.parent.store.data.scale+t,{x:i,y:n})});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 n=0;nthis.ratio){const h=t.width/this.ratio;t.y-=(h-t.height)/2,t.height=h,Yl(t)}else{const h=t.height*this.ratio;t.x-=(h-t.width)/2,t.width=h,Yl(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 h_(r){throw new Error('Could not dynamically require "'+r+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var LFe={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){return function(){return function t(i,n,s){function a(c,u){if(!n[c]){if(!i[c]){var h=typeof h_=="function"&&h_;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=n[c]={exports:{}};i[c][0].call(f.exports,function(p){return a(i[c][1][p]||p)},f,f.exports,t,i,n,s)}return n[c].exports}for(var o=typeof h_=="function"&&h_,l=0;l0&&(D.topicAliasMaximum>65535?v("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new c(D.topicAliasMaximum)),this.on("connect",function(){const W=this.queue;v("connect :: sending queued packets"),function K(){const U=W.shift();v("deliver :: entry %o",U);let j=null;if(!U)return void z._resubscribe();j=U.packet,v("deliver :: call _sendPacket for %o",j);let B=!0;j.messageId&&j.messageId!==0&&(z.messageIdProvider.register(j.messageId)||(B=!1)),B?z._sendPacket(j,function(G){U.cb&&U.cb(G),K()}):(v("messageId: %d has already used. The message is skipped and removed.",j.messageId),K())}()}),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"),z.pingTimer!==null&&(z.pingTimer.clear(),z.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,D=new f,k=h.parser(this.options);let z=null;const W=[];function K(){if(W.length)x(U);else{const B=z;z=null,B()}}function U(){v("work :: getting next packet in queue");const B=W.shift();if(B)v("work :: packet pulled from queue"),I._handlePacket(B,K);else{v("work :: no packets in queue");const G=z;z=null,v("work :: done flag is %s",!!G),G&&G()}}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(B){v("parser :: on packet push to packets array."),W.push(B)}),D._write=function(B,G,Y){z=Y,v("writable stream :: parsing buffer"),k.parse(B),U()},v("_setupStream :: pipe stream to writable stream"),this.stream.pipe(D),this.stream.on("error",function(B){v("streamErrorHandler :: error",B.message),B.code?(v("streamErrorHandler :: emitting error"),I.emit("error",B)):M(B)}),this.stream.on("close",function(){var B;v("(%s)stream :: on close",I.options.clientId),(B=I.outgoing)&&(v("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(B).forEach(function(G){B[G].volatile&&typeof B[G].cb=="function"&&(B[G].cb(new Error("Connection closed")),delete B[G])})),v("stream: emit close to MqttClient"),I.emit("close")}),v("_setupStream: sending packet `connect`");const j=Object.create(this.options);if(j.cmd="connect",this.topicAliasRecv&&(j.properties||(j.properties={}),this.topicAliasRecv&&(j.properties.topicAliasMaximum=this.topicAliasRecv.max)),P(this,j),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"&&P(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,D){const k=this.options;if(k.protocolVersion===5&&k.properties&&k.properties.maximumPacketSize&&k.properties.maximumPacketSize0||!U())&&this._storeProcessingQueue.push({invoke:U,cbStorePut:k.cbStorePut,callback:z}),this},R.prototype.subscribe=function(){const I=this,D=new Array(arguments.length);for(let Z=0;Z0){const ue={qos:ce.qos};j===5&&(ue.nl=ce.nl||!1,ue.rap=ce.rap||!1,ue.rh=ce.rh||0,ue.properties=ce.properties),I._resubscribeTopics[ce.topic]=ue,le.push(ce.topic)}}),I.messageIdToTopic[te.messageId]=le}return I.outgoing[te.messageId]={volatile:!0,cb:function(le,ce){if(!le){const ue=ce.granted;for(let N=0;N0||!Y())&&this._storeProcessingQueue.push({invoke:Y,callback:K}),this},R.prototype.unsubscribe=function(){const I=this,D=new Array(arguments.length);for(let j=0;j0||!U())&&this._storeProcessingQueue.push({invoke:U,callback:z}),this},R.prototype.end=function(I,D,k){const z=this;function W(){v("end :: (%s) :: finish :: calling _cleanUp with force %s",z.options.clientId,I),z._cleanUp(I,()=>{v("end :: finish :: calling process.nextTick on closeStores"),x((function(){v("end :: closeStores: closing incoming and outgoing stores"),z.disconnected=!0,z.incomingStore.close(function(K){z.outgoingStore.close(function(U){if(v("end :: closeStores: emitting end"),z.emit("end"),k){const j=K||U;v("end :: closeStores: invoking callback with args"),k(j)}})}),z._deferredReconnect&&z._deferredReconnect()}).bind(z))},D)}return v("end :: (%s)",this.options.clientId),I!=null&&typeof I=="boolean"||(k=D||M,D=I,I=!1,typeof D!="object"&&(k=D,D=null,typeof k!="function"&&(k=M))),typeof D!="object"&&(k=D,D=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",z.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,W,10))):(v("end :: (%s) :: immediately calling finish",z.options.clientId),W()),this)},R.prototype.removeOutgoingMessage=function(I){const D=this.outgoing[I]?this.outgoing[I].cb:null;return delete this.outgoing[I],this.outgoingStore.del({messageId:I},function(){D(new Error("Message removed"))}),this},R.prototype.reconnect=function(I){v("client reconnect");const D=this,k=function(){I?(D.options.incomingStore=I.incomingStore,D.options.outgoingStore=I.outgoingStore):(D.options.incomingStore=null,D.options.outgoingStore=null),D.incomingStore=D.options.incomingStore||new l,D.outgoingStore=D.options.outgoingStore||new l,D.disconnecting=!1,D.disconnected=!1,D._deferredReconnect=null,D._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,D){const k=arguments[2];if(D&&(v("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",D)),v("_cleanUp :: forced? %s",I),I)this.options.reconnectPeriod===0&&this.options.clean&&(z=this.outgoing)&&(v("flush: queue exists? %b",!!z),Object.keys(z).forEach(function(W){typeof z[W].cb=="function"&&(z[W].cb(new Error("Connection closed")),delete z[W])})),v("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const W=y({cmd:"disconnect"},k);v("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(W,b.bind(null,this.stream.end.bind(this.stream)))}var z;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),D&&!this.connected&&(v("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",D),D())},R.prototype._sendPacket=function(I,D,k){v("_sendPacket :: (%s) :: start",this.options.clientId),k=k||M,D=D||M;const z=function(W,K){if(W.options.protocolVersion===5&&K.cmd==="publish"){let U;K.properties&&(U=K.properties.topicAlias);const j=K.topic.toString();if(W.topicAliasSend)if(U){if(j.length!==0&&(v("applyTopicAlias :: register topic: %s - alias: %d",j,U),!W.topicAliasSend.put(j,U)))return v("applyTopicAlias :: error out of range. topic: %s - alias: %d",j,U),new Error("Sending Topic Alias out of range")}else j.length!==0&&(W.options.autoAssignTopicAlias?(U=W.topicAliasSend.getAliasByTopic(j))?(K.topic="",K.properties={...K.properties,topicAlias:U},v("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",j,U)):(U=W.topicAliasSend.getLruAlias(),W.topicAliasSend.put(j,U),K.properties={...K.properties,topicAlias:U},v("applyTopicAlias :: auto assign topic: %s - alias: %d",j,U)):W.options.autoUseTopicAlias&&(U=W.topicAliasSend.getAliasByTopic(j))&&(K.topic="",K.properties={...K.properties,topicAlias:U},v("applyTopicAlias :: auto use topic: %s - alias: %d",j,U)));else if(U)return v("applyTopicAlias :: error out of range. topic: %s - alias: %d",j,U),new Error("Sending Topic Alias out of range")}}(this,I);if(z)D(z);else{if(!this.connected)return I.cmd==="auth"?(this._shiftPingInterval(),void P(this,I,D)):(v("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(I,D,k));switch(this._shiftPingInterval(),I.cmd){case"publish":break;case"pubrel":return void w(this,I,D,k);default:return void P(this,I,D)}switch(I.qos){case 2:case 1:w(this,I,D,k);break;case 0:default:P(this,I,D)}v("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(I,D,k){v("_storePacket :: packet: %o",I),v("_storePacket :: cb? %s",!!D),k=k||M;let z=I;if(z.cmd==="publish"){const W=E(this,z=m(I));if(W)return D&&D(W)}(z.qos||0)===0&&this.queueQoSZero||z.cmd!=="publish"?this.queue.push({packet:z,cb:D}):z.qos>0?(D=this.outgoing[z.messageId]?this.outgoing[z.messageId].cb:null,this.outgoingStore.put(z,function(W){if(W)return D&&D(W);k()})):D&&D(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=g(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 D=this.options,k=D.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&&D.keepalive&&(D.keepalive=I.properties.serverKeepAlive,this._shiftPingInterval()),I.properties.maximumPacketSize&&(D.properties||(D.properties={}),D.properties.maximumPacketSize=I.properties.maximumPacketSize)}if(k===0)this.reconnecting=!1,this._onConnect(I);else if(k>0){const z=new Error("Connection refused: "+A[k]);z.code=k,this.emit("error",z)}},R.prototype._handleAuth=function(I){const D=this.options.protocolVersion,k=D===5?I.reasonCode:I.returnCode;if(D!==5){const W=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+D);return W.code=k,void this.emit("error",W)}const z=this;this.handleAuth(I,function(W,K){if(W)z.emit("error",W);else if(k===24)z.reconnecting=!1,z._sendPacket(K);else{const U=new Error("Connection refused: "+A[k]);W.code=k,z.emit("error",U)}})},R.prototype.handleAuth=function(I,D){D()},R.prototype._handlePublish=function(I,D){v("_handlePublish: packet %o",I),D=D!==void 0?D:M;let k=I.topic.toString();const z=I.payload,W=I.qos,K=I.messageId,U=this,j=this.options,B=[0,16,128,131,135,144,145,151,153];if(this.options.protocolVersion===5){let G;if(I.properties&&(G=I.properties.topicAlias),G!==void 0)if(k.length===0){if(!(G>0&&G<=65535))return v("_handlePublish :: topic alias out of range. alias: %d",G),void this.emit("error",new Error("Received Topic Alias is out of range"));{const Y=this.topicAliasRecv.getTopicByAlias(G);if(!Y)return v("_handlePublish :: unregistered topic alias. alias: %d",G),void this.emit("error",new Error("Received unregistered Topic Alias"));v("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",k=Y,G)}}else{if(!this.topicAliasRecv.put(k,G))return v("_handlePublish :: topic alias out of range. alias: %d",G),void this.emit("error",new Error("Received Topic Alias is out of range"));v("_handlePublish :: registered topic: %s - alias: %d",k,G)}}switch(v("_handlePublish: qos %d",W),W){case 2:j.customHandleAcks(k,z,I,function(G,Y){return G instanceof Error||(Y=G,G=null),G?U.emit("error",G):B.indexOf(Y)===-1?U.emit("error",new Error("Wrong reason code for pubrec")):void(Y?U._sendPacket({cmd:"pubrec",messageId:K,reasonCode:Y},D):U.incomingStore.put(I,function(){U._sendPacket({cmd:"pubrec",messageId:K},D)}))});break;case 1:j.customHandleAcks(k,z,I,function(G,Y){return G instanceof Error||(Y=G,G=null),G?U.emit("error",G):B.indexOf(Y)===-1?U.emit("error",new Error("Wrong reason code for puback")):(Y||U.emit("message",k,z,I),void U.handleMessage(I,function(Z){if(Z)return D&&D(Z);U._sendPacket({cmd:"puback",messageId:K,reasonCode:Y},D)}))});break;case 0:this.emit("message",k,z,I),this.handleMessage(I,D);break;default:v("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(I,D){D()},R.prototype._handleAck=function(I){const D=I.messageId,k=I.cmd;let z=null;const W=this.outgoing[D]?this.outgoing[D].cb:null,K=this;let U;if(W){switch(v("_handleAck :: packet type",k),k){case"pubcomp":case"puback":{const j=I.reasonCode;j&&j>0&&j!==16&&((U=new Error("Publish error: "+A[j])).code=j,W(U,I)),delete this.outgoing[D],this.outgoingStore.del(I,W),this.messageIdProvider.deallocate(D),this._invokeStoreProcessingQueue();break}case"pubrec":{z={cmd:"pubrel",qos:2,messageId:D};const j=I.reasonCode;j&&j>0&&j!==16?((U=new Error("Publish error: "+A[j])).code=j,W(U,I)):this._sendPacket(z);break}case"suback":delete this.outgoing[D],this.messageIdProvider.deallocate(D);for(let j=0;j0)if(this.options.resubscribe)if(this.options.protocolVersion===5){v("_resubscribe: protocolVersion 5");for(let D=0;D0){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 Ri<"u"?Ri: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,n){const{Buffer:s}=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(m){m.hostname||(m.hostname="localhost"),m.path||(m.path="/"),m.wsOptions||(m.wsOptions={})})(f);const g=function(m,_){const y=m.protocol==="alis"?"wss":"ws";let v=y+"://"+m.hostname+m.path;return m.port&&m.port!==80&&m.port!==443&&(v=y+"://"+m.hostname+":"+m.port+m.path),typeof m.transformWsUrl=="function"&&(v=m.transformWsUrl(v,m,_)),v}(f,d);return(l=f.my).connectSocket({url:g,protocols:p}),c=function(){const m=new a;return m._write=function(_,y,v){l.sendSocketMessage({data:_.buffer,success:function(){v()},fail:function(){v(new Error)}})},m._flush=function(_){l.closeSocket({success:function(){_()}})},m}(),u=o.obj(),h||(h=!0,l.onSocketOpen(function(){u.setReadable(c),u.setWritable(c),u.emit("connect")}),l.onSocketMessage(function(m){if(typeof m.data=="string"){const _=s.from(m.data,"base64");c.push(_)}else{const _=new FileReader;_.addEventListener("load",function(){let y=_.result;y=y instanceof ArrayBuffer?s.from(y):s.from(y,"utf8"),c.push(y)}),_.readAsArrayBuffer(m.data)}}),l.onSocketClose(function(){u.end(),u.destroy()}),l.onSocketError(function(m){u.destroy(m)})),u}},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(t,i,n){const s=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),s.createConnection(c,u)}},{debug:18,net:16}],4:[function(t,i,n){const s=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=s.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,n){(function(s){(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=s!==void 0&&s.title==="browser"||typeof __webpack_require__=="function";function f(g,m){let _=g.protocol+"://"+g.hostname+":"+g.port+g.path;return typeof g.transformWsUrl=="function"&&(_=g.transformWsUrl(_,g,m)),_}function p(g){const m=g;return g.hostname||(m.hostname="localhost"),g.port||(g.protocol==="wss"?m.port=443:m.port=80),g.path||(m.path="/"),g.wsOptions||(m.wsOptions={}),d||g.protocol!=="wss"||h.forEach(function(_){Object.prototype.hasOwnProperty.call(g,_)&&!Object.prototype.hasOwnProperty.call(g.wsOptions,_)&&(m.wsOptions[_]=g[_])}),m}i.exports=d?function(g,m){let _;l("browserStreamBuilder");const y=function(I){const D=p(I);if(D.hostname||(D.hostname=D.host),!D.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");const k=new URL(document.URL);D.hostname=k.hostname,D.port||(D.port=k.port)}return D.objectMode===void 0&&(D.objectMode=!(D.binary===!0||D.binary===void 0)),D}(m).browserBufferSize||524288,v=m.browserBufferTimeout||1e3,x=!m.objectMode,b=function(I,D){const k=D.protocolId==="MQIsdp"&&D.protocolVersion===3?"mqttv3.1":"mqtt",z=f(D,I),W=new WebSocket(z,[k]);return W.binaryType="arraybuffer",W}(g,m),C=function(I,D,k){const z=new u({objectModeMode:I.objectMode});return z._write=D,z._flush=k,z}(m,function I(D,k,z){b.bufferedAmount>y&&setTimeout(I,v,D,k,z),x&&typeof D=="string"&&(D=a.from(D,"utf8"));try{b.send(D)}catch(W){return z(W)}z()},function(I){b.close(),I()});m.objectMode||(C._writev=R),C.on("close",()=>{b.close()});const A=b.addEventListener!==void 0;function E(){_.setReadable(C),_.setWritable(C),_.emit("connect")}function P(){_.end(),_.destroy()}function w(I){_.destroy(I)}function M(I){let D=I.data;D=D instanceof ArrayBuffer?a.from(D):a.from(D,"utf8"),C.push(D)}function R(I,D){const k=new Array(I.length);for(let z=0;z{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,n){const{Buffer:s}=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(m){m.hostname||(m.hostname="localhost"),m.path||(m.path="/"),m.wsOptions||(m.wsOptions={})})(d);const p=function(m,_){const y=m.protocol==="wxs"?"wss":"ws";let v=y+"://"+m.hostname+m.path;return m.port&&m.port!==80&&m.port!==443&&(v=y+"://"+m.hostname+":"+m.port+m.path),typeof m.transformWsUrl=="function"&&(v=m.transformWsUrl(v,m,_)),v}(d,h);l=wx.connectSocket({url:p,protocols:[f]}),c=function(){const m=new a;return m._write=function(_,y,v){l.send({data:_.buffer,success:function(){v()},fail:function(x){v(new Error(x))}})},m._flush=function(_){l.close({success:function(){_()}})},m}(),(u=o.obj())._destroy=function(m,_){l.close({success:function(){_&&_(m)}})};const g=u.destroy;return u.destroy=(function(){u.destroy=g;const m=this;setTimeout(function(){l.close({fail:function(){m._destroy(new Error)}})},0)}).bind(u),l.onOpen(function(){u.setReadable(c),u.setWritable(c),u.emit("connect")}),l.onMessage(function(m){let _=m.data;_=_ instanceof ArrayBuffer?s.from(_):s.from(_,"utf8"),c.push(_)}),l.onClose(function(){u.end(),u.destroy()}),l.onError(function(m){u.destroy(new Error(m.errMsg))}),u}},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(t,i,n){function s(){if(!(this instanceof s))return new s;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}s.prototype.allocate=function(){const a=this.nextId++;return this.nextId===65536&&(this.nextId=1),a},s.prototype.getLastAllocated=function(){return this.nextId===1?65535:this.nextId-1},s.prototype.register=function(a){return!0},s.prototype.deallocate=function(a){},s.prototype.clear=function(){},i.exports=s},{}],8:[function(t,i,n){const s=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=s(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,g){h.push(p)}),u._read=function(){!d&&fthis.max)&&(this.aliasToTopic[o]=a,this.length=Object.keys(this.aliasToTopic).length,!0)},s.prototype.getTopicByAlias=function(a){return this.aliasToTopic[a]},s.prototype.clear=function(){this.aliasToTopic={}},i.exports=s},{}],10:[function(t,i,n){const s=t("lru-cache"),a=t("number-allocator").NumberAllocator;function o(l){if(!(this instanceof o))return new o(l);l>0&&(this.aliasToTopic=new s({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,n){function s(a){const o=a.split("/");for(let l=0;l0?_-4:_;for(g=0;g>16&255,v[x++]=p>>8&255,v[x++]=255&p;return y===2&&(p=a[f.charCodeAt(g)]<<2|a[f.charCodeAt(g+1)]>>4,v[x++]=255&p),y===1&&(p=a[f.charCodeAt(g)]<<10|a[f.charCodeAt(g+1)]<<4|a[f.charCodeAt(g+2)]>>2,v[x++]=p>>8&255,v[x++]=255&p),v},n.fromByteArray=function(f){for(var p,g=f.length,m=g%3,_=[],y=0,v=g-m;yv?v:y+16383));return m===1?(p=f[g-1],_.push(s[p>>2]+s[p<<4&63]+"==")):m===2&&(p=(f[g-2]<<8)+f[g-1],_.push(s[p>>10]+s[p>>4&63]+s[p<<2&63]+"=")),_.join("")};for(var s=[],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 g=f.indexOf("=");return g===-1&&(g=p),[g,g===p?0:4-g%4]}function d(f,p,g){for(var m,_,y=[],v=p;v>18&63]+s[_>>12&63]+s[_>>6&63]+s[63&_]);return y.join("")}a[45]=62,a[95]=63},{}],14:[function(t,i,n){const{Buffer:s}=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||s.alloc(0);const d=!!l,f=this._offset(u),p=h-u;let g=p,m=d&&c||0,_=f[1];if(u===0&&h===this.length){if(!d)return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length);for(let y=0;yv)){this._bufs[y].copy(l,m,_,_+g),m+=v;break}this._bufs[y].copy(l,m,_),m+=v,g-=v,_&&(_=0)}return l.length>m?l.slice(0,m):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 g=p.indexOf(l,f);if(g!==-1)return this._reverseOffset([d,g]);f=p.length-l.length+1}else{const g=this._reverseOffset([d,f]);if(this._match(g,l))return g;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 F=new Uint8Array(N);return F.__proto__=u.prototype,F}function u(N,F,X){if(typeof N=="number"){if(typeof F=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return f(N)}return h(N,F,X)}function h(N,F,X){if(typeof N=="string")return function(ne,he){if(typeof he=="string"&&he!==""||(he="utf8"),!u.isEncoding(he))throw new TypeError("Unknown encoding: "+he);var fe=0|m(ne,he),ye=c(fe),Se=ye.write(ne,he);return Se!==fe&&(ye=ye.slice(0,Se)),ye}(N,F);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(ce(N,ArrayBuffer)||N&&ce(N.buffer,ArrayBuffer))return function(ne,he,fe){if(he<0||ne.byteLength=l)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+l.toString(16)+" bytes");return 0|N}function m(N,F){if(u.isBuffer(N))return N.length;if(ArrayBuffer.isView(N)||ce(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 X=N.length,J=arguments.length>2&&arguments[2]===!0;if(!J&&X===0)return 0;for(var ae=!1;;)switch(F){case"ascii":case"latin1":case"binary":return X;case"utf8":case"utf-8":return Z(N).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*X;case"hex":return X>>>1;case"base64":return te(N).length;default:if(ae)return J?-1:Z(N).length;F=(""+F).toLowerCase(),ae=!0}}function _(N,F,X){var J=N[F];N[F]=N[X],N[X]=J}function y(N,F,X,J,ae){if(N.length===0)return-1;if(typeof X=="string"?(J=X,X=0):X>2147483647?X=2147483647:X<-2147483648&&(X=-2147483648),ue(X=+X)&&(X=ae?0:N.length-1),X<0&&(X=N.length+X),X>=N.length){if(ae)return-1;X=N.length-1}else if(X<0){if(!ae)return-1;X=0}if(typeof F=="string"&&(F=u.from(F,J)),u.isBuffer(F))return F.length===0?-1:v(N,F,X,J,ae);if(typeof F=="number")return F&=255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(N,F,X):Uint8Array.prototype.lastIndexOf.call(N,F,X):v(N,[F],X,J,ae);throw new TypeError("val must be string, number or Buffer")}function v(N,F,X,J,ae){var ne,he=1,fe=N.length,ye=F.length;if(J!==void 0&&((J=String(J).toLowerCase())==="ucs2"||J==="ucs-2"||J==="utf16le"||J==="utf-16le")){if(N.length<2||F.length<2)return-1;he=2,fe/=2,ye/=2,X/=2}function Se(Je,ke){return he===1?Je[ke]:Je.readUInt16BE(ke*he)}if(ae){var De=-1;for(ne=X;nefe&&(X=fe-ye),ne=X;ne>=0;ne--){for(var ze=!0,Le=0;Leae&&(J=ae):J=ae;var ne=F.length;J>ne/2&&(J=ne/2);for(var he=0;he>8,ye=he%256,Se.push(ye),Se.push(fe);return Se}(F,N.length-X),N,X,J)}function w(N,F,X){return F===0&&X===N.length?a.fromByteArray(N):a.fromByteArray(N.slice(F,X))}function M(N,F,X){X=Math.min(N.length,X);for(var J=[],ae=F;ae239?4:Se>223?3:Se>191?2:1;if(ae+ze<=X)switch(ze){case 1:Se<128&&(De=Se);break;case 2:(192&(ne=N[ae+1]))==128&&(ye=(31&Se)<<6|63&ne)>127&&(De=ye);break;case 3:ne=N[ae+1],he=N[ae+2],(192&ne)==128&&(192&he)==128&&(ye=(15&Se)<<12|(63&ne)<<6|63&he)>2047&&(ye<55296||ye>57343)&&(De=ye);break;case 4:ne=N[ae+1],he=N[ae+2],fe=N[ae+3],(192&ne)==128&&(192&he)==128&&(192&fe)==128&&(ye=(15&Se)<<18|(63&ne)<<12|(63&he)<<6|63&fe)>65535&&ye<1114112&&(De=ye)}De===null?(De=65533,ze=1):De>65535&&(De-=65536,J.push(De>>>10&1023|55296),De=56320|1023&De),J.push(De),ae+=ze}return function(Le){var Je=Le.length;if(Je<=R)return String.fromCharCode.apply(String,Le);for(var ke="",We=0;We"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,F,X){return h(N,F,X)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(N,F,X){return function(J,ae,ne){return d(J),J<=0?c(J):ae!==void 0?typeof ne=="string"?c(J).fill(ae,ne):c(J).fill(ae):c(J)}(N,F,X)},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,F){if(ce(N,Uint8Array)&&(N=u.from(N,N.offset,N.byteLength)),ce(F,Uint8Array)&&(F=u.from(F,F.offset,F.byteLength)),!u.isBuffer(N)||!u.isBuffer(F))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(N===F)return 0;for(var X=N.length,J=F.length,ae=0,ne=Math.min(X,J);aethis.length||((J===void 0||J>this.length)&&(J=this.length),J<=0)||(J>>>=0)<=(X>>>=0))return"";for(F||(F="utf8");;)switch(F){case"hex":return k(this,X,J);case"utf8":case"utf-8":return M(this,X,J);case"ascii":return I(this,X,J);case"latin1":case"binary":return D(this,X,J);case"base64":return w(this,X,J);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,X,J);default:if(ae)throw new TypeError("Unknown encoding: "+F);F=(F+"").toLowerCase(),ae=!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="",F=n.INSPECT_MAX_BYTES;return N=this.toString("hex",0,F).replace(/(.{2})/g,"$1 ").trim(),this.length>F&&(N+=" ... "),""},u.prototype.compare=function(N,F,X,J,ae){if(ce(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(F===void 0&&(F=0),X===void 0&&(X=N?N.length:0),J===void 0&&(J=0),ae===void 0&&(ae=this.length),F<0||X>N.length||J<0||ae>this.length)throw new RangeError("out of range index");if(J>=ae&&F>=X)return 0;if(J>=ae)return-1;if(F>=X)return 1;if(F>>>=0,X>>>=0,J>>>=0,ae>>>=0,this===N)return 0;for(var ne=ae-J,he=X-F,fe=Math.min(ne,he),ye=this.slice(J,ae),Se=N.slice(F,X),De=0;De>>=0,isFinite(X)?(X>>>=0,J===void 0&&(J="utf8")):(J=X,X=void 0)}var ae=this.length-F;if((X===void 0||X>ae)&&(X=ae),N.length>0&&(X<0||F<0)||F>this.length)throw new RangeError("Attempt to write outside buffer bounds");J||(J="utf8");for(var ne=!1;;)switch(J){case"hex":return x(this,N,F,X);case"utf8":case"utf-8":return b(this,N,F,X);case"ascii":return C(this,N,F,X);case"latin1":case"binary":return A(this,N,F,X);case"base64":return E(this,N,F,X);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,N,F,X);default:if(ne)throw new TypeError("Unknown encoding: "+J);J=(""+J).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,F,X){var J="";X=Math.min(N.length,X);for(var ae=F;aeJ)&&(X=J);for(var ae="",ne=F;neX)throw new RangeError("Trying to access beyond buffer length")}function K(N,F,X,J,ae,ne){if(!u.isBuffer(N))throw new TypeError('"buffer" argument must be a Buffer instance');if(F>ae||FN.length)throw new RangeError("Index out of range")}function U(N,F,X,J,ae,ne){if(X+J>N.length)throw new RangeError("Index out of range");if(X<0)throw new RangeError("Index out of range")}function j(N,F,X,J,ae){return F=+F,X>>>=0,ae||U(N,0,X,4),o.write(N,F,X,J,23,4),X+4}function B(N,F,X,J,ae){return F=+F,X>>>=0,ae||U(N,0,X,8),o.write(N,F,X,J,52,8),X+8}u.prototype.slice=function(N,F){var X=this.length;N=~~N,F=F===void 0?X:~~F,N<0?(N+=X)<0&&(N=0):N>X&&(N=X),F<0?(F+=X)<0&&(F=0):F>X&&(F=X),F>>=0,F>>>=0,X||W(N,F,this.length);for(var J=this[N],ae=1,ne=0;++ne>>=0,F>>>=0,X||W(N,F,this.length);for(var J=this[N+--F],ae=1;F>0&&(ae*=256);)J+=this[N+--F]*ae;return J},u.prototype.readUInt8=function(N,F){return N>>>=0,F||W(N,1,this.length),this[N]},u.prototype.readUInt16LE=function(N,F){return N>>>=0,F||W(N,2,this.length),this[N]|this[N+1]<<8},u.prototype.readUInt16BE=function(N,F){return N>>>=0,F||W(N,2,this.length),this[N]<<8|this[N+1]},u.prototype.readUInt32LE=function(N,F){return N>>>=0,F||W(N,4,this.length),(this[N]|this[N+1]<<8|this[N+2]<<16)+16777216*this[N+3]},u.prototype.readUInt32BE=function(N,F){return N>>>=0,F||W(N,4,this.length),16777216*this[N]+(this[N+1]<<16|this[N+2]<<8|this[N+3])},u.prototype.readIntLE=function(N,F,X){N>>>=0,F>>>=0,X||W(N,F,this.length);for(var J=this[N],ae=1,ne=0;++ne=(ae*=128)&&(J-=Math.pow(2,8*F)),J},u.prototype.readIntBE=function(N,F,X){N>>>=0,F>>>=0,X||W(N,F,this.length);for(var J=F,ae=1,ne=this[N+--J];J>0&&(ae*=256);)ne+=this[N+--J]*ae;return ne>=(ae*=128)&&(ne-=Math.pow(2,8*F)),ne},u.prototype.readInt8=function(N,F){return N>>>=0,F||W(N,1,this.length),128&this[N]?-1*(255-this[N]+1):this[N]},u.prototype.readInt16LE=function(N,F){N>>>=0,F||W(N,2,this.length);var X=this[N]|this[N+1]<<8;return 32768&X?4294901760|X:X},u.prototype.readInt16BE=function(N,F){N>>>=0,F||W(N,2,this.length);var X=this[N+1]|this[N]<<8;return 32768&X?4294901760|X:X},u.prototype.readInt32LE=function(N,F){return N>>>=0,F||W(N,4,this.length),this[N]|this[N+1]<<8|this[N+2]<<16|this[N+3]<<24},u.prototype.readInt32BE=function(N,F){return N>>>=0,F||W(N,4,this.length),this[N]<<24|this[N+1]<<16|this[N+2]<<8|this[N+3]},u.prototype.readFloatLE=function(N,F){return N>>>=0,F||W(N,4,this.length),o.read(this,N,!0,23,4)},u.prototype.readFloatBE=function(N,F){return N>>>=0,F||W(N,4,this.length),o.read(this,N,!1,23,4)},u.prototype.readDoubleLE=function(N,F){return N>>>=0,F||W(N,8,this.length),o.read(this,N,!0,52,8)},u.prototype.readDoubleBE=function(N,F){return N>>>=0,F||W(N,8,this.length),o.read(this,N,!1,52,8)},u.prototype.writeUIntLE=function(N,F,X,J){N=+N,F>>>=0,X>>>=0,J||K(this,N,F,X,Math.pow(2,8*X)-1,0);var ae=1,ne=0;for(this[F]=255&N;++ne>>=0,X>>>=0,J||K(this,N,F,X,Math.pow(2,8*X)-1,0);var ae=X-1,ne=1;for(this[F+ae]=255&N;--ae>=0&&(ne*=256);)this[F+ae]=N/ne&255;return F+X},u.prototype.writeUInt8=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,1,255,0),this[F]=255&N,F+1},u.prototype.writeUInt16LE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,2,65535,0),this[F]=255&N,this[F+1]=N>>>8,F+2},u.prototype.writeUInt16BE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,2,65535,0),this[F]=N>>>8,this[F+1]=255&N,F+2},u.prototype.writeUInt32LE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,4,4294967295,0),this[F+3]=N>>>24,this[F+2]=N>>>16,this[F+1]=N>>>8,this[F]=255&N,F+4},u.prototype.writeUInt32BE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,4,4294967295,0),this[F]=N>>>24,this[F+1]=N>>>16,this[F+2]=N>>>8,this[F+3]=255&N,F+4},u.prototype.writeIntLE=function(N,F,X,J){if(N=+N,F>>>=0,!J){var ae=Math.pow(2,8*X-1);K(this,N,F,X,ae-1,-ae)}var ne=0,he=1,fe=0;for(this[F]=255&N;++ne>0)-fe&255;return F+X},u.prototype.writeIntBE=function(N,F,X,J){if(N=+N,F>>>=0,!J){var ae=Math.pow(2,8*X-1);K(this,N,F,X,ae-1,-ae)}var ne=X-1,he=1,fe=0;for(this[F+ne]=255&N;--ne>=0&&(he*=256);)N<0&&fe===0&&this[F+ne+1]!==0&&(fe=1),this[F+ne]=(N/he>>0)-fe&255;return F+X},u.prototype.writeInt8=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,1,127,-128),N<0&&(N=255+N+1),this[F]=255&N,F+1},u.prototype.writeInt16LE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,2,32767,-32768),this[F]=255&N,this[F+1]=N>>>8,F+2},u.prototype.writeInt16BE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,2,32767,-32768),this[F]=N>>>8,this[F+1]=255&N,F+2},u.prototype.writeInt32LE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,4,2147483647,-2147483648),this[F]=255&N,this[F+1]=N>>>8,this[F+2]=N>>>16,this[F+3]=N>>>24,F+4},u.prototype.writeInt32BE=function(N,F,X){return N=+N,F>>>=0,X||K(this,N,F,4,2147483647,-2147483648),N<0&&(N=4294967295+N+1),this[F]=N>>>24,this[F+1]=N>>>16,this[F+2]=N>>>8,this[F+3]=255&N,F+4},u.prototype.writeFloatLE=function(N,F,X){return j(this,N,F,!0,X)},u.prototype.writeFloatBE=function(N,F,X){return j(this,N,F,!1,X)},u.prototype.writeDoubleLE=function(N,F,X){return B(this,N,F,!0,X)},u.prototype.writeDoubleBE=function(N,F,X){return B(this,N,F,!1,X)},u.prototype.copy=function(N,F,X,J){if(!u.isBuffer(N))throw new TypeError("argument should be a Buffer");if(X||(X=0),J||J===0||(J=this.length),F>=N.length&&(F=N.length),F||(F=0),J>0&&J=this.length)throw new RangeError("Index out of range");if(J<0)throw new RangeError("sourceEnd out of bounds");J>this.length&&(J=this.length),N.length-F=0;--ne)N[ne+F]=this[ne+X];else Uint8Array.prototype.set.call(N,this.subarray(X,J),F);return ae},u.prototype.fill=function(N,F,X,J){if(typeof N=="string"){if(typeof F=="string"?(J=F,F=0,X=this.length):typeof X=="string"&&(J=X,X=this.length),J!==void 0&&typeof J!="string")throw new TypeError("encoding must be a string");if(typeof J=="string"&&!u.isEncoding(J))throw new TypeError("Unknown encoding: "+J);if(N.length===1){var ae=N.charCodeAt(0);(J==="utf8"&&ae<128||J==="latin1")&&(N=ae)}}else typeof N=="number"&&(N&=255);if(F<0||this.length>>=0,X=X===void 0?this.length:X>>>0,N||(N=0),typeof N=="number")for(ne=F;ne55295&&X<57344){if(!ae){if(X>56319){(F-=3)>-1&&ne.push(239,191,189);continue}if(he+1===J){(F-=3)>-1&&ne.push(239,191,189);continue}ae=X;continue}if(X<56320){(F-=3)>-1&&ne.push(239,191,189),ae=X;continue}X=65536+(ae-55296<<10|X-56320)}else ae&&(F-=3)>-1&&ne.push(239,191,189);if(ae=null,X<128){if((F-=1)<0)break;ne.push(X)}else if(X<2048){if((F-=2)<0)break;ne.push(X>>6|192,63&X|128)}else if(X<65536){if((F-=3)<0)break;ne.push(X>>12|224,X>>6&63|128,63&X|128)}else{if(!(X<1114112))throw new Error("Invalid code point");if((F-=4)<0)break;ne.push(X>>18|240,X>>12&63|128,X>>6&63|128,63&X|128)}}return ne}function te(N){return a.toByteArray(function(F){if((F=(F=F.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;F.length%4!=0;)F+="=";return F}(N))}function le(N,F,X,J){for(var ae=0;ae=F.length||ae>=N.length);++ae)F[ae+X]=N[ae];return ae}function ce(N,F){return N instanceof F||N!=null&&N.constructor!=null&&N.constructor.name!=null&&N.constructor.name===F.name}function ue(N){return N!=N}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(t,i,n){(function(s){(function(){n.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)},n.save=function(o){try{o?n.storage.setItem("debug",o):n.storage.removeItem("debug")}catch{}},n.load=function(){let o;try{o=n.storage.getItem("debug")}catch{}return!o&&s!==void 0&&"env"in s&&(o=s.env.DEBUG),o},n.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+)/)},n.storage=function(){try{return localStorage}catch{}}(),n.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`."))}})(),n.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"],n.log=console.debug||console.log||(()=>{}),i.exports=t("./common")(n);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,n){i.exports=function(s){function a(c){let u,h,d,f=null;function p(...g){if(!p.enabled)return;const m=p,_=Number(new Date),y=_-(u||_);m.diff=y,m.prev=u,m.curr=_,u=_,g[0]=a.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let v=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(x,b)=>{if(x==="%%")return"%";v++;const C=a.formatters[b];if(typeof C=="function"){const A=g[v];x=C.call(m,A),g.splice(v,1),v--}return x}),a.formatArgs.call(m,g),(m.log||a.log).apply(m,g)}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:g=>{f=g}}),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]=s[c]}),a.names=[],a.skips=[],a.formatters={},a.selectColor=function(c){let u=0;for(let h=0;h0&&P.length>A){P.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+P.length+' "'+String(x)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');w.name="MaxListenersExceededWarning",w.emitter=v,w.type=x,w.count=P.length,typeof console=="object"&&console.warn&&console.warn("%s: %s",w.name,w.message)}}else P=E[x]=b,++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(!(b=P[v]))return!1;var R=typeof b=="function";switch(C=arguments.length){case 1:(function(I,D,k){if(D)I.call(k);else for(var z=I.length,W=y(I,z),K=0;K=0;E--)if(b[E]===x||b[E].listener===x){P=b[E].listener,A=E;break}if(A<0)return this;A===0?b.shift():function(w,M){for(var R=M,I=R+1,D=w.length;I=0;C--)this.removeListener(v,x[C]);return this},l.prototype.listeners=function(v){return m(this,v,!0)},l.prototype.rawListeners=function(v){return m(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,n){n.read=function(s,a,o,l,c){var u,h,d=8*c-l-1,f=(1<>1,g=-7,m=o?c-1:0,_=o?-1:1,y=s[a+m];for(m+=_,u=y&(1<<-g)-1,y>>=-g,g+=d;g>0;u=256*u+s[a+m],m+=_,g-=8);for(h=u&(1<<-g)-1,u>>=-g,g+=l;g>0;h=256*h+s[a+m],m+=_,g-=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)},n.write=function(s,a,o,l,c,u){var h,d,f,p=8*u-c-1,g=(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=g):(h=Math.floor(Math.log(a)/Math.LN2),a*(f=Math.pow(2,-h))<1&&(h--,f*=2),(a+=h+m>=1?_/f:_*Math.pow(2,1-m))*f>=2&&(h++,f/=2),h+m>=g?(d=0,h=g):h+m>=1?(d=(a*f-1)*Math.pow(2,c),h+=m):(d=a*Math.pow(2,m-1)*Math.pow(2,c),h=0));c>=8;s[o+y]=255&d,y+=v,d/=256,c-=8);for(h=h<0;s[o+y]=255&h,y+=v,h/=256,p-=8);s[o+y-v]|=128*x}},{}],24:[function(t,i,n){typeof Object.create=="function"?i.exports=function(s,a){a&&(s.super_=a,s.prototype=Object.create(a.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}))}:i.exports=function(s,a){if(a){s.super_=a;var o=function(){};o.prototype=a.prototype,s.prototype=new o,s.prototype.constructor=s}}},{}],25:[function(t,i,n){Object.defineProperty(n,"__esModule",{value:!0});var s=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(s),n.default=s},{}],26:[function(t,i,n){var s=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(g){return function(m){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]b)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=m(y),x=v.curNodeBucketIndex,b=v.curNodePointerIndex;return c[x][b]},this.eraseElementByPos=function(y){var v=this;if(y<0||y>g)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=[],b=y+1;b0?--f:u0&&--g)},this.setElementByPos=function(y,v){var x=m(y),b=x.curNodeBucketIndex,C=x.curNodePointerIndex;c[b][C]=v},this.insert=function(y,v,x){var b=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 C=[],A=y;A0?--h:u>0&&(--u,h=a.bucketSize-1)),++g,c[u][h]=y},this.popFront=function(){this.empty()||(this.size()!==1&&(h0&&--g)},this.shrinkToFit=function(){var y=this,v=[];this.forEach(function(A){v.push(A)});var x=v.length;c=[];for(var b=Math.ceil(x/a.bucketSize),C=0;C0&&p[p.length-1])&&(x[0]===6||x[0]===2)){m=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(n,"__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,b="";if(typeof _=="number")x=((x=Math.floor(_))<<5)-x,x&=x;else{b=typeof _!="string"?JSON.stringify(_):_;try{for(var C=a(b),A=C.next();!A.done;A=C.next())x=(x<<5)-x+A.value.charCodeAt(0),x&=x}catch(E){y={error:E}}finally{try{A&&!A.done&&(v=C.return)&&v.call(C)}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,g=[],m=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,m=h,g=[]},this.forEach=function(_){var y=0;g.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 b=d(_)&m-1;if(g[b]){var C=g[b].size();if(g[b]instanceof o.default){try{for(var A=a(g[b]),E=A.next();!E.done;E=A.next()){var P=E.value;if(P.key===_)return void(P.value=y)}}catch(M){v={error:M}}finally{try{E&&!E.done&&(x=A.return)&&x.call(A)}finally{if(v)throw v.error}}g[b].pushBack({key:_,value:y}),g[b].size()>=c.treeifyThreshold&&(g[b]=new l.default(g[b]))}else g[b].setElement(_,y);var w=g[b].size();p+=w-C}else++p,g[b]=new o.default([{key:_,value:y}]);p>m*c.sigma&&(function(M){if(!(M>=c.maxSize)){m=2*M;var R=[];g.forEach(function(I,D){if(!I.empty()){if(I instanceof o.default&&I.size()===1){var k=I.front(),z=k.key,W=k.value;R[d(z)&m-1]=new o.default([{key:z,value:W}])}else if(I instanceof l.default){var K=new o.default,U=new o.default;I.forEach(function(G){d(G.key)&M?U.pushBack(G):K.pushBack(G)}),K.size()>c.untreeifyThreshold?R[D]=new l.default(K):K.size()&&(R[D]=K),U.size()>c.untreeifyThreshold?R[D+M]=new l.default(U):U.size()&&(R[D+M]=U)}else{var j=new o.default,B=new o.default;I.forEach(function(G){d(G.key)&M?B.pushBack(G):j.pushBack(G)}),j.size()&&(R[D]=j),B.size()&&(R[D+M]=B)}g[D].clear()}}),g=R}}).call(this,m)}else this.eraseElementByKey(_)},this.getElementByKey=function(_){var y,v,x=d(_)&m-1;if(g[x]){if(g[x]instanceof l.default)return g[x].getElementByKey(_);try{for(var b=a(g[x]),C=b.next();!C.done;C=b.next()){var A=C.value;if(A.key===_)return A.value}}catch(E){y={error:E}}finally{try{C&&!C.done&&(v=b.return)&&v.call(b)}finally{if(y)throw y.error}}}},this.eraseElementByKey=function(_){var y,v,x=d(_)&m-1;if(g[x]){var b=g[x].size();if(g[x]instanceof l.default)g[x].eraseElementByKey(_),g[x].size()<=c.untreeifyThreshold&&(g[x]=new o.default(g[x]));else{var C=-1;try{for(var A=a(g[x]),E=A.next();!E.done;E=A.next())if(++C,E.value.key===_){g[x].eraseElementByPos(C);break}}catch(w){y={error:w}}finally{try{E&&!E.done&&(v=A.return)&&v.call(A)}finally{if(y)throw y.error}}}var P=g[x].size();p+=P-b}},this.find=function(_){var y,v,x=d(_)&m-1;if(!g[x])return!1;if(g[x]instanceof l.default)return g[x].find(_);try{for(var b=a(g[x]),C=b.next();!C.done;C=b.next())if(C.value.key===_)return!0}catch(A){y={error:A}}finally{try{C&&!C.done&&(v=b.return)&&v.call(b)}finally{if(y)throw y.error}}return!1},this[Symbol.iterator]=function(){return function(){var _,y,v,x,b,C;return s(this,function(A){switch(A.label){case 0:_=0,A.label=1;case 1:if(!(_=m)return[3,10];A.label=2;case 2:A.trys.push([2,7,8,9]),b=void 0,y=a(g[_]),v=y.next(),A.label=3;case 3:return v.done?[3,6]:[4,v.value];case 4:A.sent(),A.label=5;case 5:return v=y.next(),[3,3];case 6:return[3,9];case 7:return x=A.sent(),b={error:x},[3,9];case 8:try{v&&!v.done&&(C=y.return)&&C.call(y)}finally{if(b)throw b.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),n.default=c},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(t,i,n){var s=this&&this.__generator||function(u,h){var d,f,p,g,m={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return g={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function _(y){return function(v){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;m;)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 m.label++,{value:x[1],done:!1};case 5:m.label++,f=x[1],x=[0];continue;case 7:x=m.ops.pop(),m.trys.pop();continue;default:if(!(p=(p=m.trys).length>0&&p[p.length-1])&&(x[0]===6||x[0]===2)){m=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(n,"__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,g=[],m=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,m=h,g=[]},this.forEach=function(_){var y=0;g.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(_)&m-1;if(g[y]){var v=g[y].size();if(g[y]instanceof l.default){if(g[y].find(_))return;g[y].pushBack(_),g[y].size()>=c.treeifyThreshold&&(g[y]=new o.default(g[y]))}else g[y].insert(_);var x=g[y].size();p+=x-v}else g[y]=new l.default([_]),++p;p>m*c.sigma&&(function(b){if(!(b>=c.maxSize)){m=2*b;var C=[];g.forEach(function(A,E){if(!A.empty()){if(A instanceof l.default&&A.size()===1){var P=A.front();if(P===void 0)throw new Error("unknown error");C[d(P)&m-1]=new l.default([P])}else if(A instanceof o.default){var w=new l.default,M=new l.default;A.forEach(function(D){d(D)&b?M.pushBack(D):w.pushBack(D)}),w.size()>c.untreeifyThreshold?C[E]=new o.default(w):w.size()&&(C[E]=w),M.size()>c.untreeifyThreshold?C[E+b]=new o.default(M):M.size()&&(C[E+b]=M)}else{var R=new l.default,I=new l.default;A.forEach(function(D){d(D)&b?I.pushBack(D):R.pushBack(D)}),R.size()&&(C[E]=R),I.size()&&(C[E+b]=I)}g[E].clear()}}),g=C}}).call(this,m)},this.eraseElementByValue=function(_){var y=d(_)&m-1;if(g[y]){var v=g[y].size();g[y].eraseElementByValue(_),g[y]instanceof o.default&&g[y].size()<=c.untreeifyThreshold&&(g[y]=new l.default(g[y]));var x=g[y].size();p+=x-v}},this.find=function(_){var y=d(_)&m-1;return!!g[y]&&g[y].find(_)},this[Symbol.iterator]=function(){return function(){var _,y,v,x,b,C;return s(this,function(A){switch(A.label){case 0:_=0,A.label=1;case 1:if(!(_=m)return[3,10];A.label=2;case 2:A.trys.push([2,7,8,9]),b=void 0,y=a(g[_]),v=y.next(),A.label=3;case 3:return v.done?[3,6]:[4,v.value];case 4:A.sent(),A.label=5;case 5:return v=y.next(),[3,3];case 6:return[3,9];case 7:return x=A.sent(),b={error:x},[3,9];case 8:try{v&&!v.done&&(C=y.return)&&C.call(y)}finally{if(b)throw b.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),n.default=c},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(t,i,n){var s=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function g(m){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 g=p.pre,m=p.next;m.pre=g,g.next=m,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 g=p.pre,m=p.next;m&&(m.pre=g),g&&(g.next=m),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 g=h;f--;){if(!g)throw new Error("unknown error");g=g.next}g&&(g.value=p)},this.insert=function(f,p,g){if(g===void 0&&(g=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(g<0)throw new Error("insert size must more than 0");if(f===0)for(;g--;)this.pushFront(p);else if(f===u)for(;g--;)this.pushBack(p);else{for(var m=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(m){p.push(m)}),p.sort(f);var g=h;p.forEach(function(m){g&&(g.value=m,g=g.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,g=h;f.forEach(function(m){for(;g&&g.value!==void 0&&g.value<=m;)g=g.next;if(g===void 0)p.pushBack(m),g=d;else if(g===h)p.pushFront(m),g=h;else{++u;var _=g.pre;_&&(_.next=new a(m),_.next.pre=_,_.next.next=g,g&&(g.pre=_.next))}})},this[Symbol.iterator]=function(){return function(){var f;return s(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),n.default=o},{}],30:[function(t,i,n){var s=this&&this.__generator||function(c,u){var h,d,f,p,g={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function m(_){return function(y){return function(v){if(h)throw new TypeError("Generator is already executing.");for(;g;)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 g.label++,{value:v[1],done:!1};case 5:g.label++,d=v[1],v=[0];continue;case 7:v=g.ops.pop(),g.trys.pop();continue;default:if(!(f=(f=g.trys).length>0&&f[f.length-1])&&(v[0]===6||v[0]===2)){g=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(n,"__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},g=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?g(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=g(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,D=0;try{for(var k=a(this),z=k.next();!z.done;z=k.next())M(z.value,D++)}catch(W){R={error:W}}finally{try{z&&!z.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 D=0;try{for(var k=a(this),z=k.next();!z.done;z=k.next()){var W=z.value;if(D===M)return W;++D}}catch(K){R={error:K}}finally{try{z&&!z.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}throw new Error("unknown Error")};var m=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?m(M.rightChild,R):m(M.leftChild,R)||{key:M.key,value:M.value}}};this.lowerBound=function(M){return m(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 D=R.rotateLeft();f===R&&(f=D),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),D=R.rotateLeft(),f===R&&(f=D),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),D=I.rotateRight(),f===I&&(f=D),x(M)));else M===R.rightChild&&(I.color===o.default.TreeNodeColorType.red?(I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red,D=R.rotateRight(),f===R&&(f=D),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),D=R.rotateRight(),f===R&&(f=D),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),D=I.rotateLeft(),f===I&&(f=D),x(M))))}else M.color=o.default.TreeNodeColorType.black},b=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 D=M.value;M.value=R.value,R.value=D,M=R}R.leftChild&&(R=g(R.leftChild),I=M.key,M.key=R.key,R.key=I,D=M.value,M.value=R.value,R.value=D,M=R)}x(R),R&&R.remove(),--d,f.color=o.default.TreeNodeColorType.black},C=function(M,R){return!(!M||M.key===void 0)&&(!!C(M.leftChild,R)||!!R(M)||C(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;C(f,function(I){return M===R?(b(I),!0):(++R,!1)})},this.eraseElementByKey=function(M){if(!this.empty()){var R=P(f,M);R!==void 0&&R.key!==void 0&&u(R.key,M)===0&&b(R)}};var A=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?A(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?A(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},E=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,D=R.parent;if(!D)throw new Error("unknown error");if(I&&I.color===o.default.TreeNodeColorType.red)I.color=R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red,E(D);else if(!I||I.color===o.default.TreeNodeColorType.black)if(R===D.leftChild)if(M===R.leftChild){R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red;var k=D.rotateRight();D===f&&(f=k)}else M===R.rightChild&&(k=R.rotateLeft(),D===f&&(f=k),E(R));else R===D.rightChild&&(M===R.leftChild?(k=R.rotateRight(),D===f&&(f=k),E(R)):M===R.rightChild&&(R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red,k=D.rotateLeft(),D===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=A(f,M);I.key===void 0||u(I.key,M)!==0?(++d,I.key=M,I.value=R,E(I),f.color=o.default.TreeNodeColorType.black):I.value=R}else this.eraseElementByKey(M)};var P=function(M,R){if(M&&M.key!==void 0){var I=u(R,M.key);return I<0?P(M.leftChild,R):I>0?P(M.rightChild,R):M}};this.find=function(M){return!!P(f,M)},this.getElementByKey=function(M){var R=P(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 D=I.key,k=I.value;return R.setElement(D,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 w=function(M){return s(this,function(R){switch(R.label){case 0:return M&&M.key!==void 0&&M.value!==void 0?[5,a(w(M.leftChild))]:[2];case 1:return R.sent(),[4,{key:M.key,value:M.value}];case 2:return R.sent(),[5,a(w(M.rightChild))];case 3:return R.sent(),[2]}})};this[Symbol.iterator]=function(){return w(f)},c.forEach(function(M){var R=M.key,I=M.value;return h.setElement(R,I)}),Object.freeze(this)}Object.freeze(l),n.default=l},{"../Base/TreeNode":25}],31:[function(t,i,n){function s(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&&(m=g),o(l[f],l[m])<=0)break;u(f,m),p=2*(f=m)+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 m=p;if(g0&&(m=g),o(l[m],d)>=0)break;l[f]=l[m],f=m}l[f]=d}else--c},this.top=function(){return l[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(s),n.default=s},{}],32:[function(t,i,n){Object.defineProperty(n,"__esModule",{value:!0});var s=t("../LinkList/LinkList");function a(o){o===void 0&&(o=[]);var l=new s.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),n.default=a},{"../LinkList/LinkList":29}],33:[function(t,i,n){var s=this&&this.__generator||function(c,u){var h,d,f,p,g={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return p={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function m(_){return function(y){return function(v){if(h)throw new TypeError("Generator is already executing.");for(;g;)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 g.label++,{value:v[1],done:!1};case 5:g.label++,d=v[1],v=[0];continue;case 7:v=g.ops.pop(),g.trys.pop();continue;default:if(!(f=(f=g.trys).length>0&&f[f.length-1])&&(v[0]===6||v[0]===2)){g=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(n,"__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},g=function(M){if(!M||M.key===void 0)throw new Error("unknown error");return M.rightChild?g(M.rightChild):M};this.front=function(){if(!this.empty())return p(f).key},this.back=function(){if(!this.empty())return g(f).key},this.forEach=function(M){var R,I,D=0;try{for(var k=a(this),z=k.next();!z.done;z=k.next())M(z.value,D++)}catch(W){R={error:W}}finally{try{z&&!z.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 D=0;try{for(var k=a(this),z=k.next();!z.done;z=k.next()){var W=z.value;if(D===M)return W;++D}}catch(K){R={error:K}}finally{try{z&&!z.done&&(I=k.return)&&I.call(k)}finally{if(R)throw R.error}}throw new Error("unknown error")};var m=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 D=R.rotateLeft();f===R&&(f=D),m(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),D=R.rotateLeft(),f===R&&(f=D),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,m(R)):(I.color=o.default.TreeNodeColorType.red,I.leftChild&&(I.leftChild.color=o.default.TreeNodeColorType.black),D=I.rotateRight(),f===I&&(f=D),m(M)));else M===R.rightChild&&(I.color===o.default.TreeNodeColorType.red?(I.color=o.default.TreeNodeColorType.black,R.color=o.default.TreeNodeColorType.red,D=R.rotateRight(),f===R&&(f=D),m(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),D=R.rotateRight(),f===R&&(f=D),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,m(R)):(I.color=o.default.TreeNodeColorType.red,I.rightChild&&(I.rightChild.color=o.default.TreeNodeColorType.black),D=I.rotateLeft(),f===I&&(f=D),m(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=g(R.leftChild),I=M.key,M.key=R.key,R.key=I,M=R)}m(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=b(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,D=R.parent;if(!D)throw new Error("unknown error");if(I&&I.color===o.default.TreeNodeColorType.red)I.color=R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red,x(D);else if(!I||I.color===o.default.TreeNodeColorType.black)if(R===D.leftChild)if(M===R.leftChild){R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red;var k=D.rotateRight();D===f&&(f=k)}else M===R.rightChild&&(k=R.rotateLeft(),D===f&&(f=k),x(R));else R===D.rightChild&&(M===R.leftChild?(k=R.rotateRight(),D===f&&(f=k),x(R)):M===R.rightChild&&(R.color=o.default.TreeNodeColorType.black,D.color=o.default.TreeNodeColorType.red,k=D.rotateLeft(),D===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 b=function(M,R){if(M&&M.key!==void 0){var I=u(R,M.key);return I<0?b(M.leftChild,R):I>0?b(M.rightChild,R):M}};this.find=function(M){var R=b(f,M);return R!==void 0&&R.key!==void 0&&u(R.key,M)===0};var C=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 C(M.rightChild,R);var D=C(M.leftChild,R);return D!==void 0?D:M.key}};this.lowerBound=function(M){return C(f,M)};var A=function(M,R){if(M&&M.key!==void 0){if(u(M.key,R)<=0)return A(M.rightChild,R);var I=A(M.leftChild,R);return I!==void 0?I:M.key}};this.upperBound=function(M){return A(f,M)};var E=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 E(M.leftChild,R);var D=E(M.rightChild,R);return D!==void 0?D:M.key}};this.reverseLowerBound=function(M){return E(f,M)};var P=function(M,R){if(M&&M.key!==void 0){if(u(M.key,R)>=0)return P(M.leftChild,R);var I=P(M.rightChild,R);return I!==void 0?I:M.key}};this.reverseUpperBound=function(M){return P(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 w=function(M){return s(this,function(R){switch(R.label){case 0:return M&&M.key!==void 0?[5,a(w(M.leftChild))]:[2];case 1:return R.sent(),[4,M.key];case 2:return R.sent(),[5,a(w(M.rightChild))];case 3:return R.sent(),[2]}})};this[Symbol.iterator]=function(){return w(f)},c.forEach(function(M){return h.insert(M)}),Object.freeze(this)}Object.freeze(l),n.default=l},{"../Base/TreeNode":25}],34:[function(t,i,n){function s(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(n,"__esModule",{value:!0}),Object.freeze(s),n.default=s},{}],35:[function(t,i,n){var s=this&&this.__generator||function(u,h){var d,f,p,g,m={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return g={next:_(0),throw:_(1),return:_(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function _(y){return function(v){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;m;)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 m.label++,{value:x[1],done:!1};case 5:m.label++,f=x[1],x=[0];continue;case 7:x=m.ops.pop(),m.trys.pop();continue;default:if(!(p=(p=m.trys).length>0&&p[p.length-1])&&(x[0]===6||x[0]===2)){m=0;continue}if(x[0]===3&&(!p||x[1]>p[0]&&x[1]0)&&!(f=g.next()).done;)m.push(f.value)}catch(_){p={error:_}}finally{try{f&&!f.done&&(d=g.return)&&d.call(g)}finally{if(p)throw p.error}}return m},o=this&&this.__spreadArray||function(u,h,d){if(d||arguments.length===2)for(var f,p=0,g=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 g=p;gm;)this.popBack()},this.pushBack=function(p){f.push(p),++d},this.popBack=function(){f.pop(),d>0&&--d},this.setElementByPos=function(p,g){if(p<0||p>=d)throw new Error("pos must more than 0 and less than vector's size");f[p]=g},this.insert=function(p,g,m){if(m===void 0&&(m=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(m).fill(g)),!1)),d+=m},this.find=function(p){return f.includes(p)},this.reverse=function(){f.reverse()},this.unique=function(){var p,g=[];this.forEach(function(_,y){y!==0&&_===p||(g.push(_),p=_)}),g.forEach(function(_,y){f[y]=_});for(var m=g.length;d>m;)this.popBack()},this.sort=function(p){f.sort(p)},this[Symbol.iterator]=function(){return function(){return s(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(n,"__esModule",{value:!0}),Object.freeze(c),n.default=c},{}],36:[function(t,i,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var s=t("./Vector/Vector");n.Vector=s.default;var a=t("./Stack/Stack");n.Stack=a.default;var o=t("./Queue/Queue");n.Queue=o.default;var l=t("./LinkList/LinkList");n.LinkList=l.default;var c=t("./Deque/Deque");n.Deque=c.default;var u=t("./PriorityQueue/PriorityQueue");n.PriorityQueue=u.default;var h=t("./Set/Set");n.Set=h.default;var d=t("./Map/Map");n.Map=d.default;var f=t("./HashSet/HashSet");n.HashSet=f.default;var p=t("./HashMap/HashMap");n.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,n){const s=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"),g=Symbol("updateAgeOnGet"),m=()=>1,_=(A,E,P)=>{const w=A[p].get(E);if(w){const M=w.value;if(y(A,M)){if(x(A,w),!A[c])return}else P&&(A[g]&&(w.value.now=Date.now()),A[f].unshiftNode(w));return M.value}},y=(A,E)=>{if(!E||!E.maxAge&&!A[u])return!1;const P=Date.now()-E.now;return E.maxAge?P>E.maxAge:A[u]&&P>A[u]},v=A=>{if(A[o]>A[a])for(let E=A[f].tail;A[o]>A[a]&&E!==null;){const P=E.prev;x(A,E),E=P}},x=(A,E)=>{if(E){const P=E.value;A[h]&&A[h](P.key,P.value),A[o]-=P.length,A[p].delete(P.key),A[f].removeNode(E)}};class b{constructor(E,P,w,M,R){this.key=E,this.value=P,this.length=w,this.now=M,this.maxAge=R||0}}const C=(A,E,P,w)=>{let M=P.value;y(A,M)&&(x(A,P),A[c]||(M=void 0)),M&&E.call(w,M.value,M.key,A)};i.exports=class{constructor(A){if(typeof A=="number"&&(A={max:A}),A||(A={}),A.max&&(typeof A.max!="number"||A.max<0))throw new TypeError("max must be a non-negative number");this[a]=A.max||1/0;const E=A.length||m;if(this[l]=typeof E!="function"?m:E,this[c]=A.stale||!1,A.maxAge&&typeof A.maxAge!="number")throw new TypeError("maxAge must be a number");this[u]=A.maxAge||0,this[h]=A.dispose,this[d]=A.noDisposeOnSet||!1,this[g]=A.updateAgeOnGet||!1,this.reset()}set max(A){if(typeof A!="number"||A<0)throw new TypeError("max must be a non-negative number");this[a]=A||1/0,v(this)}get max(){return this[a]}set allowStale(A){this[c]=!!A}get allowStale(){return this[c]}set maxAge(A){if(typeof A!="number")throw new TypeError("maxAge must be a non-negative number");this[u]=A,v(this)}get maxAge(){return this[u]}set lengthCalculator(A){typeof A!="function"&&(A=m),A!==this[l]&&(this[l]=A,this[o]=0,this[f].forEach(E=>{E.length=this[l](E.value,E.key),this[o]+=E.length})),v(this)}get lengthCalculator(){return this[l]}get length(){return this[o]}get itemCount(){return this[f].length}rforEach(A,E){E=E||this;for(let P=this[f].tail;P!==null;){const w=P.prev;C(this,A,P,E),P=w}}forEach(A,E){E=E||this;for(let P=this[f].head;P!==null;){const w=P.next;C(this,A,P,E),P=w}}keys(){return this[f].toArray().map(A=>A.key)}values(){return this[f].toArray().map(A=>A.value)}reset(){this[h]&&this[f]&&this[f].length&&this[f].forEach(A=>this[h](A.key,A.value)),this[p]=new Map,this[f]=new s,this[o]=0}dump(){return this[f].map(A=>!y(this,A)&&{k:A.key,v:A.value,e:A.now+(A.maxAge||0)}).toArray().filter(A=>A)}dumpLru(){return this[f]}set(A,E,P){if((P=P||this[u])&&typeof P!="number")throw new TypeError("maxAge must be a number");const w=P?Date.now():0,M=this[l](E,A);if(this[p].has(A)){if(M>this[a])return x(this,this[p].get(A)),!1;const I=this[p].get(A).value;return this[h]&&(this[d]||this[h](A,I.value)),I.now=w,I.maxAge=P,I.value=E,this[o]+=M-I.length,I.length=M,this.get(A),v(this),!0}const R=new b(A,E,M,w,P);return R.length>this[a]?(this[h]&&this[h](A,E),!1):(this[o]+=R.length,this[f].unshift(R),this[p].set(A,this[f].head),v(this),!0)}has(A){if(!this[p].has(A))return!1;const E=this[p].get(A).value;return!y(this,E)}get(A){return _(this,A,!0)}peek(A){return _(this,A,!1)}pop(){const A=this[f].tail;return A?(x(this,A),A.value):null}del(A){x(this,this[p].get(A))}load(A){this.reset();const E=Date.now();for(let P=A.length-1;P>=0;P--){const w=A[P],M=w.e||0;if(M===0)this.set(w.k,w.v);else{const R=M-E;R>0&&this.set(w.k,w.v,R)}}}prune(){this[p].forEach((A,E)=>_(this,E,!1))}}},{yallist:83}],38:[function(t,i,n){(function(s){(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=s.from([a.SESSIONPRESENT_MASK]),a.CONNACK_HEADER=s.from([a.codes.connack<[0,1].map(u=>[0,1].map(h=>{const d=s.alloc(1);return d.writeUInt8(a.codes[l]<s.from([l])),a.EMPTY={pingreq:s.from([a.codes.pingreq<<4,0]),pingresp:s.from([a.codes.pingresp<<4,0]),disconnect:s.from([a.codes.disconnect<<4,0])}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],39:[function(t,i,n){(function(s){(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=s.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=s.allocUnsafe(4);return h.writeUInt32BE(u,0),h}}}).call(this)}).call(this,t("buffer").Buffer)},{buffer:17}],42:[function(t,i,n){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,n){const s=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=s(),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,g;c("_parseConnect");const m={},_=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(m.username=this._list.readUInt8(this._pos)&l.USERNAME_MASK,m.password=this._list.readUInt8(this._pos)&l.PASSWORD_MASK,m.will=this._list.readUInt8(this._pos)&l.WILL_FLAG_MASK,m.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),m.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(m.username){if((g=this._parseString())===null)return this._emitError(new Error("Cannot parse username"));_.username=g,c("_parseConnect: packet.username: %s",_.username)}if(m.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,g,m,_,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"));g=(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,m=p>>l.SUBSCRIBE_OPTIONS_RH_SHIFT&l.SUBSCRIBE_OPTIONS_RH_MASK,v={topic:f,qos:g},this.settings.protocolVersion===5?(v.nl=y,v.rap=_,v.rh=m):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 g=this._list.toString("utf8",this._pos,p);return this._pos+=f,c("_parseString: result: %s",g),g}_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,g=1,m=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:m}:m)),_}_parseByte(){let d;return this._pos=4)&&(F||ue))ne+=s.byteLength(F)+2;else{if(le<4)return G.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*ue==0)return G.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 G.emit("error",new Error("Invalid keepalive")),!1;if(ne+=2,ne+=1,le===5){var he=R(G,ae);if(!he)return!1;ne+=he.length}if(ce){if(typeof ce!="object")return G.emit("error",new Error("Invalid will")),!1;if(!ce.topic||typeof ce.topic!="string")return G.emit("error",new Error("Invalid will topic")),!1;if(ne+=s.byteLength(ce.topic)+2,ne+=2,ce.payload){if(!(ce.payload.length>=0))return G.emit("error",new Error("Invalid will payload")),!1;typeof ce.payload=="string"?ne+=s.byteLength(ce.payload):ne+=ce.payload.length}var fe={};if(le===5){if(!(fe=R(G,ce.properties)))return!1;ne+=fe.length}}let ye=!1;if(X!=null){if(!W(X))return G.emit("error",new Error("Invalid username")),!1;ye=!0,ne+=s.byteLength(X)+2}if(J!=null){if(!ye)return G.emit("error",new Error("Username is required to use password")),!1;if(!W(J))return G.emit("error",new Error("Invalid password")),!1;ne+=z(J)+2}G.write(a.CONNECT_HEADER),C(G,ne),M(G,te),Z.bridgeMode&&(le+=128),G.write(le===131?a.VERSION131:le===132?a.VERSION132:le===4?a.VERSION4:le===5?a.VERSION5:a.VERSION3);let Se=0;return Se|=X!=null?a.USERNAME_MASK:0,Se|=J!=null?a.PASSWORD_MASK:0,Se|=ce&&ce.retain?a.WILL_RETAIN_MASK:0,Se|=ce&&ce.qos?ce.qos<0&&_(G,F),ae!=null&&ae.write(),h("publish: payload: %o",N),G.write(N)}(K,U,j);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(B,G,Y){const Z=Y?Y.protocolVersion:4,te=B||{},le=te.cmd||"puback",ce=te.messageId,ue=te.dup&&le==="pubrel"?a.DUP_MASK:0;let N=0;const F=te.reasonCode,X=te.properties;let J=Z===5?3:2;if(le==="pubrel"&&(N=1),typeof ce!="number")return G.emit("error",new Error("Invalid messageId")),!1;let ae=null;if(Z===5&&typeof X=="object"){if(!(ae=I(G,X,Y,J)))return!1;J+=ae.length}return G.write(a.ACKS[le][N][ue][0]),C(G,J),_(G,ce),Z===5&&G.write(s.from([F])),ae!==null&&ae.write(),!0}(K,U,j);case"subscribe":return function(B,G,Y){h("subscribe: packet: ");const Z=Y?Y.protocolVersion:4,te=B||{},le=te.dup?a.DUP_MASK:0,ce=te.messageId,ue=te.subscriptions,N=te.properties;let F=0;if(typeof ce!="number")return G.emit("error",new Error("Invalid messageId")),!1;F+=2;let X=null;if(Z===5){if(!(X=R(G,N)))return!1;F+=X.length}if(typeof ue!="object"||!ue.length)return G.emit("error",new Error("Invalid subscriptions")),!1;for(let ae=0;ae2)return G.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}F+=s.byteLength(ne)+2+1}h("subscribe: writing to stream: %o",a.SUBSCRIBE_HEADER),G.write(a.SUBSCRIBE_HEADER[1][le?1:0][0]),C(G,F),_(G,ce),X!==null&&X.write();let J=!0;for(const ae of ue){const ne=ae.topic,he=ae.qos,fe=+ae.nl,ye=+ae.rap,Se=ae.rh;let De;A(G,ne),De=a.SUBSCRIBE_OPTIONS_QOS[he],Z===5&&(De|=fe?a.SUBSCRIBE_OPTIONS_NL:0,De|=ye?a.SUBSCRIBE_OPTIONS_RAP:0,De|=Se?a.SUBSCRIBE_OPTIONS_RH[Se]:0),J=G.write(s.from([De]))}return J}(K,U,j);case"suback":return function(B,G,Y){const Z=Y?Y.protocolVersion:4,te=B||{},le=te.messageId,ce=te.granted,ue=te.properties;let N=0;if(typeof le!="number")return G.emit("error",new Error("Invalid messageId")),!1;if(N+=2,typeof ce!="object"||!ce.length)return G.emit("error",new Error("Invalid qos vector")),!1;for(let X=0;X_===P,set(K){K?(d&&Object.keys(d).length!==0||(y=!0),_=P):(y=!1,_=w)}});const b={};function C(K,U){if(U>a.VARBYTEINT_MAX)return K.emit("error",new Error(`Invalid variable byte integer: ${U}`)),!1;let j=b[U];return j||(j=g(U),U<16384&&(b[U]=j)),h("writeVarByteInt: writing to stream: %o",j),K.write(j)}function A(K,U){const j=s.byteLength(U);return _(K,j),h("writeString: %s",U),K.write(U,"utf8")}function E(K,U,j){A(K,U),A(K,j)}function P(K,U){return h("writeNumberCached: number: %d",U),h("writeNumberCached: %o",d[U]),K.write(d[U])}function w(K,U){const j=f(U);return h("writeNumberGenerated: %o",j),K.write(j)}function M(K,U){typeof U=="string"?A(K,U):U?(_(K,U.length),K.write(U)):_(K,0)}function R(K,U){if(typeof U!="object"||U.length!=null)return{length:1,write(){k(K,{},0)}};let j=0;function B(G,Y){let Z=0;switch(a.propertiesTypes[G]){case"byte":if(typeof Y!="boolean")return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=2;break;case"int8":if(typeof Y!="number"||Y<0||Y>255)return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=2;break;case"binary":if(Y&&Y===null)return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=1+s.byteLength(Y)+2;break;case"int16":if(typeof Y!="number"||Y<0||Y>65535)return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=3;break;case"int32":if(typeof Y!="number"||Y<0||Y>4294967295)return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=5;break;case"var":if(typeof Y!="number"||Y<0||Y>268435455)return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=1+s.byteLength(g(Y));break;case"string":if(typeof Y!="string")return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=3+s.byteLength(Y.toString());break;case"pair":if(typeof Y!="object")return K.emit("error",new Error(`Invalid ${G}: ${Y}`)),!1;Z+=Object.getOwnPropertyNames(Y).reduce((te,le)=>{const ce=Y[le];return Array.isArray(ce)?te+=ce.reduce((ue,N)=>ue+=3+s.byteLength(le.toString())+2+s.byteLength(N.toString()),0):te+=3+s.byteLength(le.toString())+2+s.byteLength(Y[le].toString()),te},0);break;default:return K.emit("error",new Error(`Invalid property ${G}: ${Y}`)),!1}return Z}if(U)for(const G in U){let Y=0,Z=0;const te=U[G];if(Array.isArray(te))for(let le=0;leY;){const te=G.shift();if(!te||!U[te])return!1;delete U[te],Z=R(K,U)}return Z}function D(K,U,j){switch(a.propertiesTypes[U]){case"byte":K.write(s.from([a.properties[U]])),K.write(s.from([+j]));break;case"int8":K.write(s.from([a.properties[U]])),K.write(s.from([j]));break;case"binary":K.write(s.from([a.properties[U]])),M(K,j);break;case"int16":K.write(s.from([a.properties[U]])),_(K,j);break;case"int32":K.write(s.from([a.properties[U]])),function(B,G){const Y=m(G);h("write4ByteNumber: %o",Y),B.write(Y)}(K,j);break;case"var":K.write(s.from([a.properties[U]])),C(K,j);break;case"string":K.write(s.from([a.properties[U]])),A(K,j);break;case"pair":Object.getOwnPropertyNames(j).forEach(B=>{const G=j[B];Array.isArray(G)?G.forEach(Y=>{K.write(s.from([a.properties[U]])),E(K,B.toString(),Y.toString())}):(K.write(s.from([a.properties[U]])),E(K,B.toString(),G.toString()))});break;default:return K.emit("error",new Error(`Invalid property ${U} value: ${j}`)),!1}}function k(K,U,j){C(K,j);for(const B in U)if(Object.prototype.hasOwnProperty.call(U,B)&&U[B]!==null){const G=U[B];if(Array.isArray(G))for(let Y=0;Y=1.5*p;return Math.round(d/p)+" "+g+(m?"s":"")}i.exports=function(d,f){f=f||{};var p=typeof d;if(p==="string"&&d.length>0)return function(g){if(!((g=String(g)).length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(g);if(m){var _=parseFloat(m[1]);switch((m[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 _*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return _;default:return}}}}(d);if(p==="number"&&isFinite(d))return f.long?function(g){var m=Math.abs(g);return m>=l?h(g,m,l,"day"):m>=o?h(g,m,o,"hour"):m>=a?h(g,m,a,"minute"):m>=s?h(g,m,s,"second"):g+" ms"}(d):function(g){var m=Math.abs(g);return m>=l?Math.round(g/l)+"d":m>=o?Math.round(g/o)+"h":m>=a?Math.round(g/a)+"m":m>=s?Math.round(g/s)+"s":g+"ms"}(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))}},{}],46:[function(t,i,n){const s=t("./lib/number-allocator.js");i.exports.NumberAllocator=s},{"./lib/number-allocator.js":47}],47:[function(t,i,n){const s=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 s([],(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,n){var s=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=s(a),i.exports.strict=s(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,n){(function(s){(function(){s===void 0||!s.version||s.version.indexOf("v0.")===0||s.version.indexOf("v1.")===0&&s.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 s.nextTick(a);case 2:return s.nextTick(function(){a.call(null,o)});case 3:return s.nextTick(function(){a.call(null,o,l)});case 4:return s.nextTick(function(){a.call(null,o,l,c)});default:for(u=new Array(d-1),h=0;h1)for(var b=1;b= 0x80 (not a basic code point)","invalid-input":"Invalid input"},P=f-p,w=Math.floor,M=String.fromCharCode;function R(B){throw new RangeError(E[B])}function I(B,G){for(var Y=B.length,Z=[];Y--;)Z[Y]=G(B[Y]);return Z}function D(B,G){var Y=B.split("@"),Z="";return Y.length>1&&(Z=Y[0]+"@",B=Y[1]),Z+I((B=B.replace(A,".")).split("."),G).join(".")}function k(B){for(var G,Y,Z=[],te=0,le=B.length;te=55296&&G<=56319&&te65535&&(Y+=M((G-=65536)>>>10&1023|55296),G=56320|1023&G),Y+=M(G)}).join("")}function W(B,G){return B+22+75*(B<26)-((G!=0)<<5)}function K(B,G,Y){var Z=0;for(B=Y?w(B/_):B>>1,B+=w(B/G);B>P*g>>1;Z+=f)B=w(B/P);return w(Z+(P+1)*B/(B+m))}function U(B){var G,Y,Z,te,le,ce,ue,N,F,X,J,ae=[],ne=B.length,he=0,fe=v,ye=y;for((Y=B.lastIndexOf(x))<0&&(Y=0),Z=0;Z=128&&R("not-basic"),ae.push(B.charCodeAt(Z));for(te=Y>0?Y+1:0;te=ne&&R("invalid-input"),((N=(J=B.charCodeAt(te++))-48<10?J-22:J-65<26?J-65:J-97<26?J-97:f)>=f||N>w((d-he)/ce))&&R("overflow"),he+=N*ce,!(N<(F=ue<=ye?p:ue>=ye+g?g:ue-ye));ue+=f)ce>w(d/(X=f-F))&&R("overflow"),ce*=X;ye=K(he-le,G=ae.length+1,le==0),w(he/G)>d-fe&&R("overflow"),fe+=w(he/G),he%=G,ae.splice(he++,0,fe)}return z(ae)}function j(B){var G,Y,Z,te,le,ce,ue,N,F,X,J,ae,ne,he,fe,ye=[];for(ae=(B=k(B)).length,G=v,Y=0,le=y,ce=0;ce=G&&Jw((d-Y)/(ne=Z+1))&&R("overflow"),Y+=(ue-G)*ne,G=ue,ce=0;ced&&R("overflow"),J==G){for(N=Y,F=f;!(N<(X=F<=le?p:F>=le+g?g:F-le));F+=f)fe=N-X,he=f-X,ye.push(M(W(X+fe%he,0))),N=w(fe/he);ye.push(M(W(N,0))),le=K(Y,ne,Z==te),Y=0,++Z}++Y,++G}return ye.join("")}if(u={version:"1.4.1",ucs2:{decode:k,encode:z},decode:U,encode:j,toASCII:function(B){return D(B,function(G){return C.test(G)?"xn--"+j(G):G})},toUnicode:function(B){return D(B,function(G){return b.test(G)?U(G.slice(4).toLowerCase()):G})}},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 Ri<"u"?Ri:typeof self<"u"?self:typeof window<"u"?window:{})},{}],52:[function(t,i,n){function s(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 g=0;g=0?(m=x.substr(0,b),_=x.substr(b+1)):(m=x,_=""),y=decodeURIComponent(m),v=decodeURIComponent(_),s(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,n){var s=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(s(f))+h;return a(c[f])?o(c[f],function(g){return p+encodeURIComponent(s(g))}).join(u):p+encodeURIComponent(s(c[f]))}).join(u):d?encodeURIComponent(s(d))+h+encodeURIComponent(s(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(g,m,_){return(_===void 0||_>g.length)&&(_=g.length),g.substring(_-m.length,_)===m}(l," argument"))f="The ".concat(l," ").concat(h," ").concat(o(c,"type"));else{var p=function(g,m,_){return typeof _!="number"&&(_=0),!(_+m.length>g.length)&&g.indexOf(m,_)!==-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=s},{}],56:[function(t,i,n){(function(s){(function(){var a=Object.keys||function(g){var m=[];for(var _ in g)m.push(_);return m};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 F=="string"||he.objectMode||Object.getPrototypeOf(F)===u.prototype||(F=function(fe){return u.from(fe)}(F)),J)he.endEmitted?P(N,new E):D(N,he,F,!0);else if(he.ended)P(N,new C);else{if(he.destroyed)return!1;he.reading=!1,he.decoder&&!X?(F=he.decoder.write(F),he.objectMode||F.length!==0?D(N,he,F,!1):U(N,he)):D(N,he,F,!1)}else J||(he.reading=!1,U(N,he));return!he.ended&&(he.lengthF.highWaterMark&&(F.highWaterMark=function(X){return X>=k?X=k:(X--,X|=X>>>1,X|=X>>>2,X|=X>>>4,X|=X>>>8,X|=X>>>16,X++),X}(N)),N<=F.length?N:F.ended?F.length:(F.needReadable=!0,0))}function W(N){var F=N._readableState;d("emitReadable",F.needReadable,F.emittedReadable),F.needReadable=!1,F.emittedReadable||(d("emitReadable",F.flowing),F.emittedReadable=!0,s.nextTick(K,N))}function K(N){var F=N._readableState;d("emitReadable_",F.destroyed,F.length,F.ended),F.destroyed||!F.length&&!F.ended||(N.emit("readable"),F.emittedReadable=!1),F.needReadable=!F.flowing&&!F.ended&&F.length<=F.highWaterMark,Z(N)}function U(N,F){F.readingMore||(F.readingMore=!0,s.nextTick(j,N,F))}function j(N,F){for(;!F.reading&&!F.ended&&(F.length0,F.resumeScheduled&&!F.paused?F.flowing=!0:N.listenerCount("data")>0&&N.resume()}function G(N){d("readable nexttick read 0"),N.read(0)}function Y(N,F){d("resume",F.reading),F.reading||N.read(0),F.resumeScheduled=!1,N.emit("resume"),Z(N),F.flowing&&!F.reading&&N.read(0)}function Z(N){var F=N._readableState;for(d("flow",F.flowing);F.flowing&&N.read()!==null;);}function te(N,F){return F.length===0?null:(F.objectMode?X=F.buffer.shift():!N||N>=F.length?(X=F.decoder?F.buffer.join(""):F.buffer.length===1?F.buffer.first():F.buffer.concat(F.length),F.buffer.clear()):X=F.buffer.consume(N,F.decoder),X);var X}function le(N){var F=N._readableState;d("endReadable",F.endEmitted),F.endEmitted||(F.ended=!0,s.nextTick(ce,F,N))}function ce(N,F){if(d("endReadableNT",N.endEmitted,N.length),!N.endEmitted&&N.length===0&&(N.endEmitted=!0,F.readable=!1,F.emit("end"),N.autoDestroy)){var X=F._writableState;(!X||X.autoDestroy&&X.finished)&&F.destroy()}}function ue(N,F){for(var X=0,J=N.length;X=F.highWaterMark:F.length>0)||F.ended))return d("read: emitReadable",F.length,F.ended),F.length===0&&F.ended?le(this):W(this),null;if((N=z(N,F))===0&&F.ended)return F.length===0&&le(this),null;var J,ae=F.needReadable;return d("need readable",ae),(F.length===0||F.length-N0?te(N,F):null)===null?(F.needReadable=F.length<=F.highWaterMark,N=0):(F.length-=N,F.awaitDrain=0),F.length===0&&(F.ended||(F.needReadable=!0),X!==N&&F.ended&&le(this)),J!==null&&this.emit("data",J),J},R.prototype._read=function(N){P(this,new A("_read()"))},R.prototype.pipe=function(N,F){var X=this,J=this._readableState;switch(J.pipesCount){case 0:J.pipes=N;break;case 1:J.pipes=[J.pipes,N];break;default:J.pipes.push(N)}J.pipesCount+=1,d("pipe count=%d opts=%j",J.pipesCount,F);var ae=(!F||F.end!==!1)&&N!==s.stdout&&N!==s.stderr?he:Je;function ne(ke,We){d("onunpipe"),ke===X&&We&&We.hasUnpiped===!1&&(We.hasUnpiped=!0,d("cleanup"),N.removeListener("close",ze),N.removeListener("finish",Le),N.removeListener("drain",fe),N.removeListener("error",De),N.removeListener("unpipe",ne),X.removeListener("end",he),X.removeListener("end",Je),X.removeListener("data",Se),ye=!0,!J.awaitDrain||N._writableState&&!N._writableState.needDrain||fe())}function he(){d("onend"),N.end()}J.endEmitted?s.nextTick(ae):X.once("end",ae),N.on("unpipe",ne);var fe=function(ke){return function(){var We=ke._readableState;d("pipeOnDrain",We.awaitDrain),We.awaitDrain&&We.awaitDrain--,We.awaitDrain===0&&l(ke,"data")&&(We.flowing=!0,Z(ke))}}(X);N.on("drain",fe);var ye=!1;function Se(ke){d("ondata");var We=N.write(ke);d("dest.write",We),We===!1&&((J.pipesCount===1&&J.pipes===N||J.pipesCount>1&&ue(J.pipes,N)!==-1)&&!ye&&(d("false write response, pause",J.awaitDrain),J.awaitDrain++),X.pause())}function De(ke){d("onerror",ke),Je(),N.removeListener("error",De),l(N,"error")===0&&P(N,ke)}function ze(){N.removeListener("finish",Le),Je()}function Le(){d("onfinish"),N.removeListener("close",ze),Je()}function Je(){d("unpipe"),X.unpipe(N)}return X.on("data",Se),function(ke,We,it){if(typeof ke.prependListener=="function")return ke.prependListener(We,it);ke._events&&ke._events[We]?Array.isArray(ke._events[We])?ke._events[We].unshift(it):ke._events[We]=[it,ke._events[We]]:ke.on(We,it)}(N,"error",De),N.once("close",ze),N.once("finish",Le),N.emit("pipe",X),J.flowing||(d("pipe resume"),X.resume()),N},R.prototype.unpipe=function(N){var F=this._readableState,X={hasUnpiped:!1};if(F.pipesCount===0)return this;if(F.pipesCount===1)return N&&N!==F.pipes?this:(N||(N=F.pipes),F.pipes=null,F.pipesCount=0,F.flowing=!1,N&&N.emit("unpipe",this,X),this);if(!N){var J=F.pipes,ae=F.pipesCount;F.pipes=null,F.pipesCount=0,F.flowing=!1;for(var ne=0;ne0,J.flowing!==!1&&this.resume()):N==="readable"&&(J.endEmitted||J.readableListening||(J.readableListening=J.needReadable=!0,J.flowing=!1,J.emittedReadable=!1,d("on readable",J.length,J.reading),J.length?W(this):J.reading||s.nextTick(G,this))),X},R.prototype.addListener=R.prototype.on,R.prototype.removeListener=function(N,F){var X=c.prototype.removeListener.call(this,N,F);return N==="readable"&&s.nextTick(B,this),X},R.prototype.removeAllListeners=function(N){var F=c.prototype.removeAllListeners.apply(this,arguments);return N!=="readable"&&N!==void 0||s.nextTick(B,this),F},R.prototype.resume=function(){var N=this._readableState;return N.flowing||(d("resume"),N.flowing=!N.readableListening,function(F,X){X.resumeScheduled||(X.resumeScheduled=!0,s.nextTick(Y,F,X))}(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 F=this,X=this._readableState,J=!1;for(var ae in N.on("end",function(){if(d("wrapped end"),X.decoder&&!X.ended){var he=X.decoder.end();he&&he.length&&F.push(he)}F.push(null)}),N.on("data",function(he){d("wrapped data"),X.decoder&&(he=X.decoder.write(he)),(!X.objectMode||he!=null)&&(X.objectMode||he&&he.length)&&(F.push(he)||(J=!0,N.pause()))}),N)this[ae]===void 0&&typeof N[ae]=="function"&&(this[ae]=function(he){return function(){return N[he].apply(N,arguments)}}(ae));for(var ne=0;ne-1))throw new E(U);return this._writableState.defaultEncoding=U,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(U,j,B){B(new y("_write()"))},R.prototype._writev=null,R.prototype.end=function(U,j,B){var G=this._writableState;return typeof U=="function"?(B=U,U=null,j=null):typeof j=="function"&&(B=j,j=null),U!=null&&this.write(U,j),G.corked&&(G.corked=1,this.uncork()),G.ending||function(Y,Z,te){Z.ending=!0,K(Y,Z),te&&(Z.finished?s.nextTick(te):Y.once("finish",te)),Z.ended=!0,Y.writable=!1}(this,G,B),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(U){this._writableState&&(this._writableState.destroyed=U)}}),R.prototype.destroy=p.destroy,R.prototype._undestroy=p.undestroy,R.prototype._destroy=function(U,j){j(U)}}).call(this)}).call(this,t("_process"),typeof Ri<"u"?Ri: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,n){(function(s){(function(){var a;function o(x,b,C){return b in x?Object.defineProperty(x,b,{value:C,enumerable:!0,configurable:!0,writable:!0}):x[b]=C,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"),g=Symbol("stream");function m(x,b){return{value:x,done:b}}function _(x){var b=x[c];if(b!==null){var C=x[g].read();C!==null&&(x[f]=null,x[c]=null,x[u]=null,b(m(C,!1)))}}var y=Object.getPrototypeOf(function(){}),v=Object.setPrototypeOf((o(a={get stream(){return this[g]},next:function(){var x=this,b=this[h];if(b!==null)return Promise.reject(b);if(this[d])return Promise.resolve(m(void 0,!0));if(this[g].destroyed)return new Promise(function(P,w){s.nextTick(function(){x[h]?w(x[h]):P(m(void 0,!0))})});var C,A=this[f];if(A)C=new Promise(function(P,w){return function(M,R){P.then(function(){w[d]?M(m(void 0,!0)):w[p](M,R)},R)}}(A,this));else{var E=this[g].read();if(E!==null)return Promise.resolve(m(E,!1));C=new Promise(this[p])}return this[f]=C,C}},Symbol.asyncIterator,function(){return this}),o(a,"return",function(){var x=this;return new Promise(function(b,C){x[g].destroy(null,function(A){A?C(A):b(m(void 0,!0))})})}),a),y);i.exports=function(x){var b,C=Object.create(v,(o(b={},g,{value:x,writable:!0}),o(b,c,{value:null,writable:!0}),o(b,u,{value:null,writable:!0}),o(b,h,{value:null,writable:!0}),o(b,d,{value:x._readableState.endEmitted,writable:!0}),o(b,p,{value:function(A,E){var P=C[g].read();P?(C[f]=null,C[c]=null,C[u]=null,A(m(P,!1))):(C[c]=A,C[u]=E)},writable:!0}),b));return C[f]=null,l(x,function(A){if(A&&A.code!=="ERR_STREAM_PREMATURE_CLOSE"){var E=C[u];return E!==null&&(C[f]=null,C[c]=null,C[u]=null,E(A)),void(C[h]=A)}var P=C[c];P!==null&&(C[f]=null,C[c]=null,C[u]=null,P(m(void 0,!0))),C[d]=!0}),x.on("readable",(function(A){s.nextTick(_,A)}).bind(null,C)),C}}).call(this)}).call(this,t("_process"))},{"./end-of-stream":64,_process:50}],62:[function(t,i,n){function s(h,d){var f=Object.keys(h);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(h);d&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(h,g).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=g:this.head=g,this.tail=g,++this.length}},{key:"unshift",value:function(p){var g={data:p,next:this.head};this.length===0&&(this.tail=g),this.head=g,++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 g=this.head,m=""+g.data;g=g.next;)m+=p+g.data;return m}},{key:"concat",value:function(p){if(this.length===0)return l.alloc(0);for(var g,m,_,y=l.allocUnsafe(p>>>0),v=this.head,x=0;v;)g=v.data,m=y,_=x,l.prototype.copy.call(g,m,_),x+=v.data.length,v=v.next;return y}},{key:"consume",value:function(p,g){var m;return py.length?y.length:p;if(v===y.length?_+=y:_+=y.slice(0,p),(p-=v)===0){v===y.length?(++m,g.next?this.head=g.next:this.head=this.tail=null):(this.head=g,g.data=y.slice(v));break}++m}return this.length-=m,_}},{key:"_getBuffer",value:function(p){var g=l.allocUnsafe(p),m=this.head,_=1;for(m.data.copy(g),p-=m.data.length;m=m.next;){var y=m.data,v=p>y.length?y.length:p;if(y.copy(g,g.length-p,0,v),(p-=v)===0){v===y.length?(++_,m.next?this.head=m.next:this.head=this.tail=null):(this.head=m,m.data=y.slice(v));break}++_}return this.length-=_,g}},{key:u,value:function(p,g){return c(this,function(m){for(var _=1;_0,function(b){g||(g=b),b&&_.forEach(u),x||(_.forEach(u),m(g))})});return f.reduce(h)}},{"../../../errors":55,"./end-of-stream":64}],67:[function(t,i,n){var s=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 s(c?l:"highWaterMark",u);return Math.floor(u)}return a.objectMode?16:16384}}},{"../../../errors":55}],68:[function(t,i,n){i.exports=t("events").EventEmitter},{events:22}],69:[function(t,i,n){(n=i.exports=t("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=t("./lib/_stream_writable.js"),n.Duplex=t("./lib/_stream_duplex.js"),n.Transform=t("./lib/_stream_transform.js"),n.PassThrough=t("./lib/_stream_passthrough.js"),n.finished=t("./lib/internal/streams/end-of-stream.js"),n.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,n){i.exports=function(){if(typeof arguments[0]!="function")throw new Error("callback needed");if(typeof arguments[1]!="number")throw new Error("interval needed");var s;if(arguments.length>0){s=new Array(arguments.length-2);for(var a=0;a>5==6?2:m>>4==14?3:m>>3==30?4:m>>6==2?-1:-2}function c(m){var _=this.lastTotal-this.lastNeed,y=function(v,x,b){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,m);return y!==void 0?y:this.lastNeed<=m.length?(m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(m.copy(this.lastChar,_,0,m.length),void(this.lastNeed-=m.length))}function u(m,_){if((m.length-_)%2==0){var y=m.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]=m[m.length-2],this.lastChar[1]=m[m.length-1],y.slice(0,-1)}return y}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",_,m.length-1)}function h(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var y=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,y)}return _}function d(m,_){var y=(m.length-_)%3;return y===0?m.toString("base64",_):(this.lastNeed=3-y,this.lastTotal=3,y===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",_,m.length-y))}function f(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function p(m){return m.toString(this.encoding)}function g(m){return m&&m.length?this.write(m):""}n.StringDecoder=o,o.prototype.write=function(m){if(m.length===0)return"";var _,y;if(this.lastNeed){if((_=this.fillLast(m))===void 0)return"";y=this.lastNeed,this.lastNeed=0}else y=0;return y=0?(E>0&&(x.lastNeed=E-1),E):--A=0?(E>0&&(x.lastNeed=E-2),E):--A=0?(E>0&&(E===2?E=0:x.lastNeed=E-3),E):0}(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=y;var v=m.length-(y-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)},o.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length}},{"safe-buffer":73}],76:[function(t,i,n){var s=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}n.parse=b,n.resolve=function(C,A){return b(C,!1,!0).resolve(A)},n.resolveObject=function(C,A){return C?b(C,!1,!0).resolveObject(A):A},n.format=function(C){return a.isString(C)&&(C=b(C)),C instanceof o?C.format():o.prototype.format.call(C)},n.Url=o;var l=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,h=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r",` `," "]),d=["'"].concat(h),f=["%","/","?",";","#"].concat(d),p=["/","?","#"],g=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+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 b(C,A,E){if(C&&a.isObject(C)&&C instanceof o)return C;var P=new o;return P.parse(C,A,E),P}o.prototype.parse=function(C,A,E){if(!a.isString(C))throw new TypeError("Parameter 'url' must be a string, not "+typeof C);var P=C.indexOf("?"),w=P!==-1&&P127?le+="x":le+=te[ce];if(!le.match(g)){var N=Y.slice(0,j),F=Y.slice(j+1),X=te.match(m);X&&(N.push(X[1]),F.unshift(X[2])),F.length&&(R="/"+F.join(".")+R),this.hostname=N.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),G||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ae=this.hostname||"";this.host=ae+J,this.href+=this.host,G&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),R[0]!=="/"&&(R="/"+R))}if(!_[k])for(j=0,Z=d.length;j0)&&E.host.split("@"))&&(E.auth=X.shift(),E.host=E.hostname=X.shift())),E.search=C.search,E.query=C.query,a.isNull(E.pathname)&&a.isNull(E.search)||(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E;if(!te.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var ce=te.slice(-1)[0],ue=(E.host||C.host||te.length>1)&&(ce==="."||ce==="..")||ce==="",N=0,F=te.length;F>=0;F--)(ce=te[F])==="."?te.splice(F,1):ce===".."?(te.splice(F,1),N++):N&&(te.splice(F,1),N--);if(!Y&&!Z)for(;N--;N)te.unshift("..");!Y||te[0]===""||te[0]&&te[0].charAt(0)==="/"||te.unshift(""),ue&&te.join("/").substr(-1)!=="/"&&te.push("");var X,J=te[0]===""||te[0]&&te[0].charAt(0)==="/";return le&&(E.hostname=E.host=J?"":te.length?te.shift():"",(X=!!(E.host&&E.host.indexOf("@")>0)&&E.host.split("@"))&&(E.auth=X.shift(),E.host=E.hostname=X.shift())),(Y=Y||E.host&&te.length)&&!J&&te.unshift(""),te.length?E.pathname=te.join("/"):(E.pathname=null,E.path=null),a.isNull(E.pathname)&&a.isNull(E.search)||(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=C.auth||E.auth,E.slashes=E.slashes||C.slashes,E.href=E.format(),E},o.prototype.parseHost=function(){var C=this.host,A=c.exec(C);A&&((A=A[0])!==":"&&(this.port=A.substr(1)),C=C.substr(0,C.length-A.length)),C&&(this.hostname=C)}},{"./util":77,punycode:51,querystring:54}],77:[function(t,i,n){i.exports={isString:function(s){return typeof s=="string"},isObject:function(s){return typeof s=="object"&&s!==null},isNull:function(s){return s===null},isNullOrUndefined:function(s){return s==null}}},{}],78:[function(t,i,n){(function(s){(function(){function a(o){try{if(!s.localStorage)return!1}catch{return!1}var l=s.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 Ri<"u"?Ri:typeof self<"u"?self:typeof window<"u"?window:{})},{}],79:[function(t,i,n){i.exports=function s(a,o){if(a&&o)return s(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},s.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},s.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},s.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},s.prototype.slice=function(u,h){(h=h||this.length)<0&&(h+=this.length),(u=u||0)<0&&(u+=this.length);var d=new s;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},s.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{switch(e){case"add":t.forEach(i=>{var n;(n=i.onAdd)==null||n.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":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":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":this.store.data.locked&&t&&!t.disabled&&this.doEvent(t,e);break}this.doMessageEvent(e)});Xe(this,"doEvent",(e,t)=>{var s,a,o,l,c,u,h,d,f,p;if(!e)return;let i=!1,n=[];if((s=e.events)==null||s.forEach((g,m)=>{var _;if(g.actions&&g.actions.length){if(g.name===t){let y=!1;g.conditions&&g.conditions.length?g.conditionType==="and"?y=g.conditions.every(v=>this.judgeCondition(e,v.key,v)):g.conditionType==="or"&&(y=g.conditions.some(v=>this.judgeCondition(e,v.key,v))):y=!0,y&&n.push(m)}}else if(i=!0,this.events[g.action]&&g.name===t){let y=!((_=g.where)!=null&&_.type);if(g.where){const{fn:v,fnJs:x,comparison:b,key:C,value:A}=g.where;if(v)y=v(e,{meta2d:this});else if(x){try{g.where.fn=new Function("pen","context",x)}catch(E){console.error("Error: make function:",E)}g.where.fn&&(y=g.where.fn(e,{meta2d:this}))}else{let E=e[C];switch(["x","y","width","height"].includes(C)&&(E=this.getPenRect(e)[C]),b){case">":y=E>+A;break;case">=":y=E>=+A;break;case"<":y=E<+A;break;case"<=":y=E<=+A;break;case"=":case"==":y=E==A;break;case"!=":y=E!=A;break;case"[)":y=SI(+E,A);break;case"![)":y=!SI(+E,A);break;case"[]":y=EI(E,A);break;case"![]":y=!EI(E,A);break}}}y&&n.push(m)}}),i?(a=e.events)==null||a.forEach((g,m)=>{n.includes(m)&&this.events[g.action](e,g)}):(o=e.events)==null||o.forEach((g,m)=>{n.includes(m)&&g.actions.forEach(_=>{this.events[_.action]&&this.events[_.action](e,_)})}),t==="valueUpdate"){(l=e.realTimes)==null||l.forEach(m=>{var y,v;let _=[];(y=m.triggers)==null||y.forEach((x,b)=>{var A;let C=!1;(A=x.conditions)!=null&&A.length?x.conditionType==="and"?C=x.conditions.every(E=>this.judgeCondition(e,m.key,E)):x.conditionType==="or"&&(C=x.conditions.some(E=>this.judgeCondition(e,m.key,E))):C=!0,C&&_.push(b)}),(v=m.triggers)==null||v.forEach((x,b)=>{var C;_.includes(b)&&((C=x.actions)==null||C.forEach(A=>{this.events[A.action](e,A)}))})});let g=[];if((c=this.store.globalTriggers[e.id])==null||c.forEach((m,_)=>{var v;let y=!1;(v=m.conditions)!=null&&v.length?m.conditionType==="and"?y=m.conditions.every(x=>this.judgeCondition(this.store.pens[x.source],x.key,x)):m.conditionType==="or"&&(y=m.conditions.some(x=>this.judgeCondition(this.store.pens[x.source],x.key,x))):y=!0,y&&g.push(_)}),(u=this.store.globalTriggers[e.id])==null||u.forEach((m,_)=>{var y;g.includes(_)&&((y=m.actions)==null||y.forEach(v=>{this.events[v.action](e,v)}))}),(h=e.triggers)!=null&&h.length){for(let m of e.triggers)if((d=m.status)!=null&&d.length)for(let _ of m.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=>{this.events[v.action](e,v)});break}}}}this.doEvent(this.store.pens[e.parentId],t)});Xe(this,"doDataEvent",e=>{var n,s,a;if(!((n=this.store.data.dataEvents)!=null&&n.length))return;const t=e.reduce((o,{dataId:l,id:c,value:u})=>(o[c||l]=u,o),{});let i=[];(s=this.store.data.dataEvents)==null||s.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)}))})});Xe(this,"renderPenRaw",rZ);Xe(this,"setElemPosition",Po);Xe(this,"setLifeCycleFunc",j0t);this.store=i0t(rs()),this.setOptions(t),this.setDatabyOptions(t),this.init(e),this.register(Agt()),this.registerCanvasDraw({cube:Emt}),this.registerAnchors(Sgt()),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=ya.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 PFe(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}),this.render()}setDatabyOptions(e={}){const{color:t,activeColor:i,activeBackground:n,grid:s,gridColor:a,gridSize:o,fromArrow:l,toArrow:c,rule:u,ruleColor:h,textColor:d}=e;this.setRule({rule:u,ruleColor:h}),this.setGrid({grid:s,gridColor:a,gridSize:o}),this.store.data=Object.assign(this.store.data,{textColor:d,color:t,activeColor:i,activeBackground:n,fromArrow:l,toArrow:c})}init(e){typeof e=="string"?this.canvas=new xTe(this,document.getElementById(e),this.store):this.canvas=new xTe(this,e,this.store),this.resize(),this.canvas.listen()}initEventFns(){this.events[Wc.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[Wc.SetProps]=(e,t)=>{const i=t.value;if(i&&typeof i=="object"){(t.params?this.find(t.params):this.find(e.id)).forEach(s=>{i.hasOwnProperty("visible")&&s.visible!==i.visible&&this.setVisible(s,i.visible),this.setValue({id:s.id,...i},{render:!1,doEvent:!1})}),this.render();return}console.warn("[meta2d] SetProps value is not an object")},this.events[Wc.StartAnimate]=(e,t)=>{let i=e;if(t.value&&(i=this.findOne(t.value)),!(this.store.animates.has(i)&&!i.calculative.pause)){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[Wc.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[Wc.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[Wc.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[Wc.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[Wc.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[Wc.JS]=(e,t)=>{var i;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)}(i=t.fn)==null||i.call(t,e,t.params,{meta2d:this,eventName:t.name})},this.events[Wc.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[Wc.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[Wc.SendPropData]=(e,t)=>{const i=Zt(t.value);if(i&&typeof i=="object"){const n=t.params?this.findOne(t.params):e;for(let s in i)(i[s]===void 0||i[s]==="")&&(i[s]=n[s]);i.id=n.id,this.doSendDataEvent(i,t.extend);return}console.warn("[meta2d] SendPropData value is not an object")},this.events[Wc.SendVarData]=(e,t)=>{const i=Zt(t.value);if(i&&typeof i=="object"){const n=t.params?this.findOne(t.params):e;let s=[];for(let a in i){let o={dataId:a,value:i[a]};if(!o.value){let l=n.form.find(c=>c.dataIds&&c.dataIds.dataId===o.dataId);l&&(o.value=n[l.key])}s.push(o)}this.doSendDataEvent(s,t.extend);return}console.warn("[meta2d] SendVarData value is not an object")},this.events[Wc.Navigator]=(e,t)=>{t.value&&typeof t.value=="string"&&this.navigatorTo(t.value)},this.events[Wc.Dialog]=(e,t)=>{if(t.params&&typeof t.params=="string"){let i=t.params;if(t.params.includes("${")){let n=t.params.match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));n&&(n==null||n.forEach(s=>{i=i.replace(`\${${s}}`,e[s])}))}this.canvas.dialog.show(t.value,i,t.extend)}},this.events[Wc.SendData]=(e,t)=>{const i=Zt(t.value);if(i&&typeof i=="object"&&t.targetType==="id"){const n=t.params?this.findOne(t.params):e;for(let s in i)(i[s]===void 0||i[s]==="")&&(i[s]=n[s]);n.deviceId&&(i.deviceId=n.deviceId),this.sendDataToNetWork(i,e,t);return}},this.events[Wc.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 n=pse(i.iframe.split("?")[1]);i.calculative.singleton.div.children[0].contentWindow.postMessage(JSON.stringify({name:t.value,id:n.id}),"*")},this.events[Wc.PostMessageToParent]=(e,t)=>{if(typeof t.value!="string"){console.warn("[meta2d] Emit value must be a string");return}window.parent.postMessage(JSON.stringify(t.value),"*")}}navigatorTo(e){if(!e)return;let i=window.location.href.split("id=");if(i.length>1){let n=i[1].indexOf("&");n===-1?window.location.href=i[0]+"id="+e:window.location.href=i[0]+"id="+e+i[1].slice(n)}}doSendDataEvent(e,t){let i=JSON.stringify(e);this.mqttClient&&this.mqttClient.connected&&(t?t.split(",").forEach(n=>{this.mqttClient.publish(n,i)}):this.store.data.mqttTopics&&this.store.data.mqttTopics.split(",").forEach(n=>{this.mqttClient.publish(n,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 s;const n=Zt(i.network);if(n.data&&(Object.assign(n,n.data),delete n.data),!!n.url){if(n.protocol==="http"){if(typeof n.headers=="object"){for(let c in n.headers)if(typeof n.headers[c]=="string"){let u=n.headers[c].match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));u&&(n.headers[c]=n.headers[c].replace(`\${${u[0]}}`,this.getDynamicParam(u[0])))}}let a,o=n.url;if(n.method==="GET"&&(a="?"+Object.keys(e).map(c=>c+"="+e[c]).join("&")),n.method==="POST"&&o.indexOf("${")>-1){let c=o.match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));c&&c.forEach(u=>{o=o.replace(`\${${u}}`,AP(t,u)||this.getDynamicParam(u))})}const l=await fetch(o+(a||""),{headers:n.headers||{},method:n.method,body:n.method==="POST"?JSON.stringify(e):void 0});if(l.ok){if(i.callback){const c=await l.text();if(!i.fn)try{if(typeof i.callback!="string")throw new Error("[meta2d] Function callback must be string");const u=i.callback;i.fn=new Function("pen","data","context",u)}catch(u){console.error("[meta2d]: Error on make a function:",u)}(s=i.fn)==null||s.call(i,t,c,{meta2d:this,e:i})}console.info("http消息发送成功")}}else if(n.protocol==="mqtt"){const a=this.mqttClients.filter(o=>o.options.href===n.url);if(a&&a.length)a[0].connected&&n.topics.split(",").forEach(o=>{a[0].publish(o,e)});else{let o=xse.connect(n.url,n.options);o.on("connect",()=>{console.info("mqtt连接成功"),n.topics.split(",").forEach(l=>{o.publish(l,e),o==null||o.end()})})}}else if(n.protocol==="websocket"){const a=this.websockets.filter(o=>o.url===n.url);if(a&&a.length)a[0].readyState===1&&a[0].send(e);else{let o=new WebSocket(n.url,n.protocols||void 0);o.onopen=function(){console.info("websocket连接成功"),o.send(e),setTimeout(()=>{o.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){return await this.canvas.addPen(e,t,i)}async addPens(e,t){return await this.canvas.addPens(e,t)}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 n(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 s=(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(s&&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 n(e);this.store.bkImg=h,s&&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:n=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=n,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){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=rs()),!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=rs()),t||(this.canvas.opening=!0),this.initBindDatas(),this.initBinds(),this.initMessageEvents(),this.initGlobalTriggers(),this.render(),this.listenSocket(),this.connectSocket(),this.connectNetwork(),this.startDataMock(),this.startAnimate(),this.startVideo(),this.doInitJS(),this.doInitFn(),this.store.data.iconUrls)for(const i of this.store.data.iconUrls)l0t(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:Zt(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,un.path2dDraws[i.name]&&this.store.path2dMap.set(i,un.path2dDraws[i.name](i)),i.type&&this.store.path2dMap.set(i,un.path2dDraws[i.name](i)),i.image&&(i.calculative.imageDrawed=!1,this.canvas.loadImage(i))}),this.render())}initBindDatas(){this.store.bindDatas={},this.store.data.pens.forEach(e=>{var t;(t=e.form)==null||t.forEach(i=>{let n;i.dataIds&&(Array.isArray(i.dataIds)?n=i.dataIds:n=[i.dataIds]),n==null||n.forEach(s=>{this.store.bindDatas[s.dataId]||(this.store.bindDatas[s.dataId]=[]),this.store.bindDatas[s.dataId].push({id:e.id,formItem:i})})})})}initBinds(){this.store.bind={},this.store.data.pens.forEach(e=>{var t;(t=e.realTimes)==null||t.forEach(i=>{i.bind&&i.bind.id&&(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}))})})}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=pse(),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&&wFe(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&&Po(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=Wl(e),n=na(e);i.prev=void 0,i.next=void 0,n.prev=void 0,n.next=void 0,e.calculative.worldAnchors=[i,n],e.calculative.activeAnchor=i,this.canvas[t](this.store,e,n),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},n.prev={penId:n.penId,x:n.x-50,y:n.y},n.next={penId:n.penId,x:n.x+50,y:n.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 n of this.store.data.pens)(i=n.onDestroy)==null||i.call(n,n);r0t(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(n=>(n.type||n.frames)&&n.autoPlay||n.animations&&n.animations.length&&n.animations.findIndex(s=>s.autoPlay)!==-1),i.length&&(i.forEach(n=>{var s,a;if(n.calculative.pause){const o=Date.now()-n.calculative.pause;n.calculative.pause=void 0,n.calculative.frameStart+=o,n.calculative.frameEnd+=o}else{let o=-1;if(t!==void 0&&n.animations){if(typeof t=="string"){if(o=n.animations.findIndex(l=>l.name===t),o===-1)return}else if(typeof t=="number")if(n.animations.length>t)o=t;else return}else t===void 0&&(o=(s=n.animations)==null?void 0:s.findIndex(l=>l.autoPlay),o===-1&&((a=n.animations)!=null&&a.length)&&(o=0));if(o!==-1&&o!==void 0){const l=Zt(n.animations[o]);delete l.name,l.currentAnimation=o,!n.type&&l.frames&&(l.showDuration=this.calcAnimateDuration(l)),this.setValue({id:n.id,...l},{doEvent:!1,history:!1})}this.store.animates.add(n),n.type||this.store.animateMap.set(n,n.calculative.canvas.getFrameProps(n))}}),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 n,s;(n=i.calculative.media)==null||n.play(),(s=i.onStartVideo)==null||s.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 n,s;(n=i.calculative.media)==null||n.pause(),(s=i.onPauseVideo)==null||s.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 n;i.calculative.media&&(i.calculative.media.currentTime=0,i.calculative.media.pause()),(n=i.onStopVideo)==null||n.call(i,i)})}calcAnimateDuration(e){return e.frames.reduce((t,i)=>t+i.duration,0)}combine(e=this.store.active,t){if(!e||!e.length)return;const i=Zt(e);if(e.length===1&&e[0].type){e[0].type=sa.Node,this.canvas.active(e),this.pushHistory({type:Vr.Update,initPens:i,pens:Zt(e,!0)}),this.render();return}const n=u_(e);let s={id:rs(),name:"combine",...n,children:[],showChild:t};this.canvas.makePen(s);const a=Zt(s);let o=1/0;return e.forEach(l=>{const c=this.store.data.pens.findIndex(h=>h.id===l.id);if(c{Ev(l,!0)}),this.initImageCanvas([s])),this.store.emitter.emit("combine",[s]),this.render(),s}uncombine(e){if(!e&&this.store.active&&(e=this.store.active[0]),!e||!e.children)return;const t=e.children.map(s=>this.store.pens[s]);let i=Zt(t);t.forEach(s=>{s.parentId=void 0,s.x=s.calculative.worldRect.x,s.y=s.calculative.worldRect.y,s.width=s.calculative.worldRect.width,s.height=s.calculative.worldRect.height,s.locked=Ss.None,s.calculative.active=void 0,s.calculative.hover=!1,this.setVisible(s,!0)});const n=this.isCombine(e)?3:2;this.pushHistory({type:Vr.Update,initPens:i,pens:t,step:n}),i=[Zt(e)],e.children=void 0,this.pushHistory({type:Vr.Update,initPens:i,pens:[e],step:n}),this.isCombine(e)&&(this.delete([e]),this.store.histories[this.store.histories.length-1].step=n),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];this.pushChildren(i,[...e.slice(0,t),...e.slice(t+1)]),e.forEach(n=>{Ev(n,!0)}),this.initImageCanvas(e),this.render()}else console.warn("Invalid operation!")}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!==Ss.Disable)),this.render()}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 pp(e,t)}getAllChildren(e){return j1(e,this.store)}getAllFollowers(e){return Lge(e,this.store)}data(){const e=Zt(this.store.data),{pens:t,paths:i}=this.store.data;e.version=qNe.version,e.paths={};for(const n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.find(s=>s.pathId===n)&&(e.paths[n]=i[n]);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=rs());const t={...this.store.data.mqttOptions};t.username||delete t.username,t.password||delete t.password;const{username:i,password:n}=t;i&&n||!i&&!n?(this.mqttClient=xse.connect(this.store.data.mqtt,t),this.mqttClient.on("message",(s,a)=>{this.socketCallback(a.toString(),{topic:s,type:"mqtt",url:this.store.data.mqtt})}),this.mqttClient.on("error",s=>{this.store.emitter.emit("error",{type:"mqtt",error:s})}),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.times=0,this.httpTimerList[i]=setInterval(async()=>{this.oldRequestHttp(t),this.store.options.reconnetTimes&&(t.times++,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:n}=this.store.data;t&&(this.httpTimer=setInterval(async()=>{const s=await fetch(t,{headers:n});if(s.ok){const a=await s.text();this.socketCallback(a,{type:"http",url:t})}},i||1e3))}}async oldRequestHttp(e){let t=Zt(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 n=await i.text();this.socketCallback(n,{type:"http",url:t.http})}else 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:n}=this.store.data;i&&(await fetch(i,{method:"post",body:e,headers:n})).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 n=0;this.websockets=[],e.forEach(s=>{s.type==="subscribe"&&(s.protocol==="mqtt"?(s.index=i,s.options.clientId&&!s.options.customClientId&&(s.options.clientId=rs()),s.times=0,this.mqttClients[i]=xse.connect(s.url,s.options),this.mqttClients[i].on("message",(a,o)=>{this.socketCallback(o.toString(),{topic:a,type:"mqtt",url:s.url})}),this.mqttClients[i].on("error",a=>{this.store.emitter.emit("error",{type:"mqtt",error:a})}),this.mqttClients[i].on("close",()=>{var a;this.store.options.reconnetTimes&&(s.times++,s.times>=this.store.options.reconnetTimes&&(s.times=0,this.mqttClients&&((a=this.mqttClients[s.index])==null||a.end())))}),s.topics&&this.mqttClients[i].subscribe(s.topics.split(",")),i+=1):s.protocol==="websocket"?(s.index=n,this.connectNetWebSocket(s),n+=1):s.protocol==="http"&&t.push({url:s.url,interval:s.interval,headers:s.headers||void 0,method:s.method,body:s.body}))})}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)}}randomString(e){e=e||32;let t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",i=t.length,n="";for(let s=0;s{let s=this.mockValue(n);s!==void 0&&e.push({id:n.id,value:s})}),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(n=>{let s=this.mockValue(n);s!==void 0&&(i[n.key]=s)}),Object.keys(i).length){let n=e.onBeforeValue?e.onBeforeValue(e,i):i;this.canvas.updateValue(e,n),(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){function t(s){let a;const o=new RegExp("(^| )"+s+"=([^;]*)(;|$)");return(a=document.cookie.match(o))?decodeURIComponent(a[2]):""}return pse()[e]||localStorage[e]||t(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,this.updateTimerList[i]=setInterval(async()=>{this.requestHttp(t),this.store.options.reconnetTimes&&(t.times++,t.times>=this.store.options.reconnetTimes&&(t.times=0,clearInterval(this.updateTimerList[i]),this.updateTimerList[i]=void 0))},t.interval||1e3)})}}async requestHttp(e){let t=Zt(e);if(t.url){if(typeof t.headers=="object"){for(let n in t.headers)if(typeof t.headers[n]=="string"){let s=t.headers[n].match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));s&&(t.headers[n]=t.headers[n].replace(`\${${s[0]}}`,this.getDynamicParam(s[0])))}}if(typeof t.body=="object"){for(let n in t.body)if(typeof t.body[n]=="string"){let s=t.body[n].match(new RegExp("(?<=\\$\\{).*?(?=\\})","g"));s&&(t.body[n]=t.body[n].replace(`\${${s[0]}}`,this.getDynamicParam(s[0])))}}const i=await fetch(t.url,{headers:t.headers,method:t.method,body:t.method==="GET"?void 0:JSON.stringify(t.body)});if(i.ok){const n=await i.text();this.socketCallback(n,{type:"http",url:t.url})}else this.store.emitter.emit("error",{type:"http",error:i})}}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})}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}),!i))return;i===!0&&(i=e);let n;if(i.constructor===Object||i.constructor===Array)n=i;else if(typeof i=="string")try{n=JSON.parse(i)}catch(s){console.warn("Invalid socket data:",n,s)}else return;n&&(Array.isArray(n)||(n=[n]),n.length&&(n[0].dataId?this.setDatas(n):n.forEach(s=>{this.setValue(s)})))}setDatas(e,{render:t=!0,doEvent:i=!0,history:n}={}){const s=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=s.get(d);if(!d.noOnBinds&&typeof d.onBinds=="function"){if(f)return;s.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},s.set(d,f))}),(u=this.store.bind[l.id])==null||u.forEach(h=>{const d=this.store.pens[h.id];if(!d)return;let f=s.get(d);f?f[h.key]=l.value:(f={id:h.id,[h.key]:l.value},s.set(d,f))})}),this.store.data.locked&&this.doDataEvent(e);let a,o;n&&(a=[]),s.forEach((l,c)=>{this.setValue(l,{render:!1,doEvent:i,history:!1}),n&&(a.push(Zt(c,!0)),o.push(c))}),t&&this.render(),n&&this.pushHistory({type:Vr.Update,initPens:a,pens:o})}setValue(e,{render:t=!0,doEvent:i=!0,history:n}={}){let s=[];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)s=[o];else{let l=this.store.bind[e.id];if(l&&l.length){s=[],this.setDatas([e],{render:t,doEvent:i,history:n});return}}}else if(e.dataId){s=[],this.setDatas([e],{render:t,doEvent:i,history:n});return}else if(e.tag)s=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:n});return}n=n&&!this.store.data.locked;let a;if(n&&(a=Zt(s)),s.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))),Uge(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(),n){let o=Zt(s);this.pushHistory({type:Vr.Update,initPens:a,pens:o})}i&&s.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){this.store.messageEvents[e]&&this.store.messageEvents[e].forEach(t=>{let i=!1;t.event.conditions&&t.event.conditions.length?t.event.conditionType==="and"?i=t.event.conditions.every(n=>this.judgeCondition(t.pen,n.key,n)):t.event.conditionType==="or"&&(i=t.event.conditions.some(n=>this.judgeCondition(t.pen,n.key,n))):i=!0,i&&t.event.actions.forEach(n=>{this.events[n.action](t.pen,n)})})}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:n,target:s,fnJs:a,fn:o,operator:l,valueType:c}=i;let u=!1;if(n==="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=SI(+d,h);break;case"![)":u=!SI(+d,h);break;case"[]":u=EI(d,h);break;case"![]":u=!EI(d,h);break}}return u}judgeCondition(e,t,i){const{type:n,target:s,fnJs:a,fn:o,operator:l,valueType:c}=i;let u=!1;if(n==="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[s][i.value]);let d=AP(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=SI(+d,h);break;case"![)":u=!SI(+d,h);break;case"[]":u=EI(d,h);break;case"![]":u=!EI(d,h);break}}return u}pushChildren(e,t){const i=[Zt(e,!0)],n=[];e.children||(e.children=[]);const s=[];t.forEach(o=>{let l=Zt(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(Zt(u,!0)),u.children.splice(h,1),s.push(Zt(u,!0))}e.children.push(o.id),o.parentId=e.id;const c=XY(o.calculative.worldRect,e.calculative.worldRect);Object.assign(o,c),o.locked=o.lockedOnCombine??Ss.DisableMove,o.locked=o.interaction||X6e.includes(o.name)?0:o.locked,l?(i.push(l),s.push(Zt(o,!0))):n.push(Zt(o,!0))}),s.push(Zt(e,!0));let a=1;n.length&&(a=2,this.pushHistory({type:Vr.Add,pens:n,step:a})),this.pushHistory({type:Vr.Update,initPens:i,pens:s,step:a})}toPng(e,t,i=!1,n){return this.canvas.toPng(e,t,i,n)}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 n;for(const s of this.store.data.pens)(s.calculative.img||["iframe"].includes(s.name))&&((n=s.onRenderPenRaw)==null||n.call(s,s));setTimeout(()=>{const s=document.createElement("a");s.setAttribute("download",(e||this.store.data.name||"le5le.meta2d")+".png"),s.setAttribute("href",this.toPng(t,void 0,!0,i));const a=document.createEvent("MouseEvents");a.initEvent("click",!0,!0),s.dispatchEvent(a)},1e3)}downloadSvg(){if(!window.C2S)throw console.error("请先加载乐吾乐官网下的canvas2svg.js","https://assets.le5lecdn.com/2d/canvas2svg.js"),new Error("请先加载乐吾乐官网下的canvas2svg.js");const e=this.getRect();e.x-=10,e.y-=10;const t=new window.C2S(e.width+20,e.height+20);t.textBaseline="middle";for(const c of this.store.data.pens)c.visible==!1||!nZ(c,this.store)||rZ(t,c,e,!0);let i=t.getSerializedSvg();this.store.data.background?(i=i.replace("{{bk}}",""),i=i.replace("{{bkRect}}",``)):(i=i.replace("{{bk}}",""),i=i.replace("{{bkRect}}","")),i=i.replace(/--le5le--/g,"&#x");const n=window.URL,s=new Blob([i]),a=n.createObjectURL(s),o=document.createElement("a");o.setAttribute("download",`${this.store.data.name||"le5le.meta2d"}.svg`),o.setAttribute("href",a);const l=document.createEvent("MouseEvents");l.initEvent("click",!0,!0),o.dispatchEvent(l)}getRect(e=this.store.data.pens){return u_(e)}hiddenTemplate(){this.canvas.canvasTemplate.hidden()}showTemplate(){this.canvas.canvasTemplate.show()}lockTemplate(e){this.store.data.pens.forEach(t=>{t.canvasLayer===Rs.CanvasTemplate&&(t.locked=e)})}fitView(e=!0,t=10){var h,d;if(!this.hasView())return;const{canvas:i}=this.canvas,{offsetWidth:n,offsetHeight:s}=i;this.resize(n,s);const a=Sv(t),o=this.getRect(),l=(n-a[1]-a[3])/o.width,c=(s-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 n,s;const e=this.getRect(),t=this.canvas.width-e.width,i=this.canvas.height-e.height;if(Math.abs(t)>10){(n=this.store.data.fits)==null||n.forEach(o=>{let l=[];o.children.forEach(u=>{this.store.pens[u].locked=Ss.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){(s=this.store.data.fits)==null||s.forEach(o=>{let l=[];o.children.forEach(u=>{this.store.pens[u].locked=Ss.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.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:n,offsetHeight:s}=i,a=Sv(t),o=this.getRect(),l=(n-a[1]-a[3])/o.width,c=(s-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:n,offsetHeight:s}=i;this.resize(n,s);const a=Sv(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=(n-a[1]-a[3])/o,u=(s-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,n={x:0,y:0,width:t,height:i};Tl(n);const{center:s}=n,{scale:a,origin:o,x:l,y:c}=this.store.data;this.translate((e.x-o.x)/a-s.x-l/a,(e.y-o.y)/a-s.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:n,offsetHeight:s}=i;this.resize(n,s);const a=Sv(e),o=this.getRect(),l=(n-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:n,offsetHeight:s}=i;this.resize(n,s);const a=Sv(e),o=this.getRect();let l=(n-a[1]-a[3])/o.width;t||(l=(s-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(),n=this.getPenRect(t);Tl(n);const{center:s}=n,{scale:a,origin:o,x:l,y:c}=this.store.data;this.translate((i.x-o.x)/a-s.x-l/a,(e-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)}centerView(){if(!this.hasView())return;const e=this.getRect(),t=this.getViewCenter(),i=this.getPenRect(e);Tl(i);const{center:n}=i,{scale:s,origin:a,x:o,y:l}=this.store.data;this.translate((t.x-a.x)/s-n.x-o/s,(t.y-a.y)/s-n.y-l/s);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=Zt(e),n=e[0],{width:s,height:a}=this.getPenRect(n);for(let o=1;o{n[s]=i[s]});for(let s=1;s{n[s]=i[s]});for(let s=0;s0){const i=e[0];RB.forEach(n=>{t[n]=i[n]!==void 0?i[n]:this.store.options.defaultFormat[n]||this.store.options[n]})}else RB.forEach(i=>{this.store.options.defaultFormat[i]||this.store.options[i]});localStorage.setItem("meta2d-formatPainter",JSON.stringify(t))}formatPainter(){const e=this.store.active,t=Zt(e),i=JSON.parse(localStorage.getItem("meta2d-formatPainter"));for(let n=0;n{for(let n=0;n{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 n=Zt(t),s=t.reduce((c,u)=>{const h=this.getPenRect(u);return c+h[e]},0),a=(i-s)/(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:Vr.Update,initPens:n,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 n=this.getPenRect(u_(e));!t&&(t=n.width),e=e.filter(c=>!c.type&&!c.parentId);const s=Zt(e);let a=0;e.forEach(c=>{const u=this.getPenRect(c);u.height>a&&(a=u.height)});let o=n.x,l=n.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-n.x,f=this.getPenRect(e[u+1]);Math.round(t-d)>=Math.round(f.width+i)?o+=h.width+i:(o=n.x,l+=a+i)}),this.initImageCanvas(e),this.initTemplateCanvas(e),this.render(),this.pushHistory({type:Vr.Update,initPens:s,pens:e})}gotoView(e){const t=this.getViewCenter(),i=t.x-e.calculative.worldRect.x-e.calculative.worldRect.width/2,n=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,n-this.store.data.y),this.store.data.x=i,this.store.data.y=n;for(const s of this.store.data.pens)Ev(s);this.canvas.canvasImage.init(),this.canvas.canvasImageBottom.init(),this.render()}showMap(){this.map||(this.map=new Egt(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.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,n=[...j1(t,this.store),t].map(a=>a.id);i.filter(a=>n.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.initImageCanvas(e)}initTemplateCanvas(e){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,n=[...j1(t,this.store),t].map(a=>a.id),s=i.filter(a=>n.includes(a.id));for(let a=s.length-1;a>=0;a--){const o=s[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,...j1(e,this.store)];let n=i.map(l=>this.store.data.pens.findIndex(c=>c.id===l.id));n.includes(-1)&&(console.warn("upByArea: pen children not in canvas"),n=n.filter(l=>l!==-1));const s=Math.min(...n),a=e.calculative.worldRect,o=this.store.data.pens.findIndex((l,c)=>{if(c<=s||l.id===e.id||u0t(l,e))return!1;const u=l.calculative.worldRect;return Jy(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 n=Rs.CanvasImageBottom;t==="top"?n=Rs.CanvasImage:(t==="up"||t==="down")&&(n=Rs.CanvasMain),this.setValue({id:e.id,canvasLayer:n},{render:!1,doEvent:!1,history:!1})}else if(e.externElement||e.name==="gif"){let n=0;t==="top"?(e.calculative.canvas.maxZindex+=1,n=e.calculative.canvas.maxZindex):t==="up"?n=e.calculative.zIndex===void 0?6:e.calculative.zIndex+1:t==="down"&&(n=e.calculative.zIndex===void 0?3:e.calculative.zIndex-1,n<0&&(n=0)),this.setValue({id:e.id,zIndex:n},{render:!1,doEvent:!1,history:!1}),(i=e.calculative.singleton)!=null&&i.div&&Po(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 n=[...j1(t,this.store),t],s=[];for(let l=0;lu.id===c.id)!==-1&&(c.temIndex=l,s.push(c))}let a=-1,o=0;s.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,...s),this.initTemplateCanvas(s),this.initImageCanvas(s)}else{const n=i.findIndex(s=>s.id===t.id);n>-1&&n!==i.length-1&&(i.splice(n+2,0,i[n]),i.splice(n,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 n=[...j1(t,this.store),t],s=[];for(let l=0;lu.id===c.id)!==-1&&(c.temIndex=l,s.push(c))}let a=-1,o=0;s.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,...s),this.initTemplateCanvas(s),this.initImageCanvas(s)}else{const n=i.findIndex(s=>s.id===t.id);n>-1&&n!==0&&(i.splice(n-1,0,i[n]),i.splice(n+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 n=i.findIndex(s=>s.id===e.id);n>-1&&(n>t?(i.splice(t,0,i[n]),i.splice(n+1,1)):n{const a=this.store.pens[s];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":na(a).connectTo===e.id&&i.push(a);break;case"out":Wl(a).connectTo===e.id&&i.push(a);break}}),i}nextNode(e){if(e.type===sa.Line){const t=this.store.pens[na(e).connectTo];return t?[t]:[]}else{const t=this.getLines(e,"out"),i=[];return t.forEach(n=>{const s=this.nextNode(n);for(const a of s)!i.find(l=>l.id===a.id)&&i.push(a)}),i}}previousNode(e){if(e.type===sa.Line){const t=this.store.pens[Wl(e).connectTo];return t?[t]:[]}else{const t=this.getLines(e,"in"),i=[];return t.forEach(n=>{const s=this.previousNode(n);for(const a of s)!i.find(l=>l.id===a.id)&&i.push(a)}),i}}getNext(e){var i;if(e.type===sa.Line){console.warn("非连线节点");return}const t=[];return(i=e.connectedLines)==null||i.forEach(({lineId:n,anchor:s})=>{var l,c;const a=(l=e.anchors)==null?void 0:l.filter(u=>u.id===s)[0],o=this.findOne(n);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===sa.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 n=null,s=null;t.x<=1&&t.x>=0&&t.y<=1&&t.y>=0?(s={id:t.id||rs(),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&&fo(s,e.rotate,e.calculative.worldRect.center),n={id:s.id,penId:e.id,x:t.x,y:t.y}):(s={id:t.id||rs(),penId:e.id,x:t.x,y:t.y},e.calculative.worldRect&&(e.rotate%360&&fo(t,-e.rotate,e.calculative.worldRect.center),n={id:s.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===sa.Line?(e.calculative.worldAnchors.splice(i,0,s),e.anchors.splice(i,0,n),this.canvas.updateLines(e),this.canvas.initLineRect(e),this.render()):(e.calculative.worldAnchors.push(s),e.anchors.push(n))}connectLine(e,t,i,n,s=!0){if(!i){const c=t.calculative.worldRect;i=SP(e,{x:c.x+c.width/2,y:c.y+c.height/2})}if(!n){const c=e.calculative.worldRect;n=SP(t,{x:c.x+c.width/2,y:c.y+c.height/2})}const a=Math.abs(i.x-n.x),l={height:Math.abs(i.y-n.y),lineName:"line",lineWidth:1,name:"line",type:1,width:a,x:Math.min(i.x,n.x),y:Math.min(i.y,n.y),anchors:[{x:i.x>n.x?1:0,y:i.y>n.y?1:0,id:rs()},{x:i.x>n.x?0:1,y:i.x>n.x?0:1,id:rs()}]};return this.addPens([l]),Du(e,i,l,l.calculative.worldAnchors[0]),Du(t,n,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),s&&this.render(),l}toComponent(e=this.store.data.pens,t,i){if(e.length===1){const u=Zt(e[0]);return u.type=sa.Node,u.id=void 0,[u]}const n=Zt(e,!0),s=u_(n);let a={id:rs(),name:"combine",...s,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=n.filter(u=>!u.parentId),l=n.find(u=>u.width===s.width&&u.height===s.height),c=l&&t===void 0;return o.length===1?a=o[0]:c&&(l.children||(l.children=[]),a=l),n.forEach(u=>{if(u===a||u.parentId===a.id||u.parentId)return;a.children.push(u.id),u.parentId=a.id;const h=XY(u.calculative.worldRect,s);Object.assign(u,h),u.locked=u.lockedOnCombine??Ss.DisableMove}),c||o.length===1?Zt(n):Zt([a,...n])}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(n=>{let s=n.plugin,a=n.options;if(s&&$0t(s)&&i)if(s.install(e,a),!this.penPluginMap.has(s))this.penPluginMap.set(s,[{[i]:e[i],option:a}]);else{let o=this.penPluginMap.get(s).find(l=>l[i]===e[i]);o?o.option=a:this.penPluginMap.get(s).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(n=>{let s=n.plugin;s.uninstall(e,n.options);let a=this.penPluginMap.get(s),o=a.findIndex(l=>l[i]===e[i]);o!==-1&&(a.splice(o,1),a.length===0&&this.penPluginMap.delete(s))})}setVisible(e,t,i=!0){if(this.onSizeUpdate(),this.setValue({id:e.id,visible:t},{render:!1,doEvent:!1}),e.children)for(const s of e.children){const a=this.store.pens[s];a&&this.setVisible(a,t,!1)}let n=j1(e,this.store);n.push(e),this.initImageCanvas(n),i&&this.render()}clearHover(){this.canvas.clearHover()}closeSocket(){this.closeWebsocket(),this.closeMqtt(),this.closeHttp()}destroy(e){if(this.clear(!1),this.closeSocket(),this.closeNetwork(),this.store.emitter.all.clear(),this.canvas.destroy(),this.canvas=void 0,un[this.store.id]=void 0,!e){for(const t in un)delete un[t];un.path2dDraws={},un.canvasDraws={},un.anchors={},un.htmlElements={}}}}function Mgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ey:a}=r.calculative.worldRect,o=s/4;if(t.moveTo(i+o,n),t.lineTo(i,n),t.lineTo(i,a),t.lineTo(i+o,a),t instanceof Path2D)return t}function Rgt(r){const e=[{x:.25,y:0},{x:.25,y:1},{x:0,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:n+"",x:t,y:i,penId:r.id}))}function Igt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ex:a,ey:o}=r.calculative.worldRect,l=r.offsetX;let c=s/7;if(l>1?c=l:l>0&&(c=s*l),t.moveTo(i+c,n),t.lineTo(a,n),t.lineTo(i+s-c,o),t.lineTo(i,o),t.closePath(),t instanceof Path2D)return t}function Pgt(r){const e=[{x:.5,y:0},{x:.9285714285714286,y:.5},{x:.5,y:1},{x:.07142857142857142,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function wgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a,ex:o,ey:l}=r.calculative.worldRect,c=s/8;if(t.moveTo(i+c,n),t.lineTo(o-c,n),t.bezierCurveTo(o+c/3,n,o+c/3,l,o-c,l),t.lineTo(i+c,l),t.lineTo(i,n+a/2),t.closePath(),t instanceof Path2D)return t}function Dgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a,ex:o,center:l}=r.calculative.worldRect,c=l.x,u=n+a*6/7,h=a/6;if(t.moveTo(i,n),t.lineTo(o,n),t.lineTo(o,u),t.bezierCurveTo(o-20,u-h,c+s/5,u-h,c,u),t.bezierCurveTo(c-s/5,u+h,i,u+h,i,u),t.closePath(),t instanceof Path2D)return t}function Ogt(r){const e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:.8571428571428571},{x:0,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function Lgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ex:a,ey:o}=r.calculative.worldRect,l=s/10;if(t.moveTo(i+l*2,n),t.bezierCurveTo(i-l*2/3,n,i-l*2/3,o,i+l*2,o),t.lineTo(a,o),t.bezierCurveTo(a-l,o,a-l,n,a,n),t.closePath(),t instanceof Path2D)return t}function Ngt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ex:a,ey:o}=r.calculative.worldRect;t.moveTo(i,n),t.lineTo(a,n),t.lineTo(a,o),t.lineTo(i,o),t.closePath();const l=s/7;if(t.moveTo(i,n+l),t.lineTo(a,n+l),t.moveTo(i+l,n),t.lineTo(i+l,o),t instanceof Path2D)return t}function Fgt(r,e){const t=e||new Path2D,{x:i,y:n,height:s,ex:a,ey:o}=r.calculative.worldRect,l=s/4;if(t.moveTo(i,n+l),t.lineTo(a,n),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t instanceof Path2D)return t}function Bgt(r){const e=[{x:.5,y:.125},{x:1,y:.5},{x:.5,y:1},{x:0,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function kgt(r,e){const t=e||new Path2D,{x:i,y:n,ex:s,ey:a}=r.calculative.worldRect;if(t.moveTo(i,n),t.lineTo(s,n),t.moveTo(i,a),t.lineTo(s,a),t instanceof Path2D)return t}function Ugt(r){const e=[{x:.5,y:0},{x:.5,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:n+"",x:t,y:i,penId:r.id}))}function zgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a,ex:o,ey:l}=r.calculative.worldRect;if(t.ellipse(i+s/2,n+a/2,s/2,a/2,0,0,Math.PI*2),t.moveTo(i+s/2,l),t.lineTo(o,l),t.closePath(),t instanceof Path2D)return t}function Vgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,ex:a,ey:o}=r.calculative.worldRect,l=s/7;if(t.moveTo(i,n),t.lineTo(a,n),t.lineTo(a,o),t.lineTo(i,o),t.closePath(),t.moveTo(i+l,n),t.lineTo(i+l,o),t.moveTo(a-l,n),t.lineTo(a-l,o),t instanceof Path2D)return t}function Ggt(r,e){const t=e||new Path2D,{x:i,y:n,height:s,ex:a,ey:o}=r.calculative.worldRect,l=s/7;if(t.moveTo(i,n+l),t.bezierCurveTo(i,n-l/2|0,a,n-l/2|0,a,n+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 Wgt(){return{flowComment:Mgt,flowData:Igt,flowDb:Ggt,flowDisplay:wgt,flowDocument:Dgt,flowExternStorage:Lgt,flowInternalStorage:Ngt,flowManually:Fgt,flowParallel:kgt,flowQueue:zgt,flowSubprocess:Vgt}}function Kgt(){return{flowDocument:Ogt,flowManually:Bgt,flowParallel:Ugt,flowComment:Rgt,flowData:Pgt}}function Hgt(r,e){const{x:t,y:i,width:n,height:s}=e.calculative.worldRect;r.beginPath(),r.ellipse(t+n/2,i+s/2,n/2,s/2,0,0,Math.PI*2),r.stroke(),r.beginPath(),r.fillStyle=r.strokeStyle,r.ellipse(t+n/2,i+s/2,n/4,s/4,0,0,Math.PI*2),r.fill()}function jgt(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a,ey:o}=r.calculative.worldRect,l=r.calculative.lineLeft||.08;let c=r.calculative.borderRadius||0,u=c;c<1&&(c=s*c,u=a*c);let h=c{const i=e.data.pens.findIndex(n=>n.id===t);i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),r.children=void 0}function Jgt(r,e){r.onDestroy||(r.onDestroy=t1t,r.onAdd=e1t);const t=e||new Path2D,{x:i,y:n,width:s,height:a,ex:o}=r.calculative.worldRect;let l=r.calculative.borderRadius||0,c=l;l<1&&(l=s*l,c=a*c);let u=l{const i=e.data.pens.findIndex(n=>n.id===t);i>-1&&(e.data.pens.splice(i,1),e.pens[t]=void 0)}),r.children=[]}function i1t(){return{interfaceClass:Qgt,simpleClass:Jgt}}function r1t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;if(t.rect(i,n,s,a),t.closePath(),t instanceof Path2D)return t}function n1t(r,e){const t=e.headHeight??50,{x:i,y:n,width:s,height:a,ey:o}=e.calculative.worldRect;let l=e.calculative.borderRadius||0,c=l;e.calculative.borderRadius<1&&(l*=s,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(r.echarts.geoName,l),r.calculative.singleton.echartsReady=!0,r.calculative.singleton.echart.setOption(oZ(r.echarts.option,r.calculative.canvas.store.data.scale),!0),r.calculative.singleton.echart.resize(),setTimeout(()=>{Cse(r)},300)})}))),r.calculative.singleton.echartsReady&&setTimeout(()=>{r.calculative.singleton.echart.setOption(oZ(r.echarts.option,r.calculative.canvas.store.data.scale),!0),setTimeout(()=>Cse(r),300)})}return t}function l1t(r){if(r.calculative.singleton&&r.calculative.singleton.div){r.calculative.singleton.div.remove();let e=globalThis.echarts;e&&e.dispose(r.calculative.singleton.echart),delete r.calculative.singleton.div,delete r.calculative.singleton.echart}}function bse(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function c1t(r){if(!r.calculative.singleton.echart)return;let e=globalThis.echarts;Po(r,r.calculative.singleton.div),!(r.echarts.geoName&&!e.getMap(r.echarts.geoName))&&(r.calculative.singleton.echart.setOption(oZ(r.echarts.option,r.calculative.canvas.store.data.scale),!0),r.calculative.singleton.echart.resize())}function u1t(r){if(r.calculative.singleton.echart&&(Po(r,r.calculative.singleton.div),r.calculative.singleton.echartsReady))if(r.calculative.partialOption){const e=r.calculative.partialOption.echarts.option;r.calculative.singleton.echart.setOption(Zt(e))}else r.calculative.singleton.echart.setOption(oZ(r.echarts.option,r.calculative.canvas.store.data.scale),!0)}function h1t(r,e){if(r.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&&(r.calculative.singleton.echartsReady=!1,fetch(e.echarts.geoUrl).then(g=>{g.text().then(m=>{if(typeof m=="string")try{m=JSON.parse(m)}catch{}if(m.constructor!==Object&&m.constructor!==Array){console.warn("Invalid data:",m);return}return p.registerMap(e.echarts.geoName,m),r.calculative.singleton.echartsReady=!0,r.onValue(r),!1})}))),e}if(r.realTimes&&r.realTimes.length){const{xAxis:p,yAxis:g}=r.echarts.option,{max:m,replaceMode:_,timeFormat:y}=r.echarts;let v=[],x=!1;for(let b in e)if(b.includes("echarts.option")){x=!0;let C=AP(r,b);if(Array.isArray(C)&&_===j9.Add){C.push(e[b]),m&&C.splice(0,C.length-m),e[b]=C;let A="echarts.option.xAxis.data";Array.isArray(p)&&p.length&&(A="echarts.option.xAxis.0.data");let E=AP(r,A),P=c0t(y||"`${hours}:${minutes}:${seconds}`");E.push(P),m&&E.splice(0,E.length-m),e[A]=E}if(b.includes(".data.")){let A=b.substring(0,b.indexOf(".data.")+5);v.includes(A)||v.push(A)}}if(x){const b=Zt(e);r.calculative.partialOption=f1t(b),v.forEach(C=>{let A=AP(r,C);yue(r.calculative.partialOption,C,A)})}return e}if(!e.dataX&&!e.dataY)return e;const t=r.echarts,{max:i,replaceMode:n}=t;let s=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(n)if(n===j9.Replace){if(!d&&!f)a&&(c===1?(!Array.isArray(a)&&(a=[a]),a.forEach((p,g)=>{const m=l[0].data.find(_=>_.name===p.name);m&&(m.value=p.value)})):l.forEach((p,g)=>{Array.isArray(a[g])||(a[g]=[a[g]]),a[g].forEach((m,_)=>{const y=p.data.find(v=>v.name===m.name);y&&(y.value=m.value)})}));else if((d.type==="category"||f.type==="category")&&s&&a){const p=d.type==="category"?d.data:f.data;!Array.isArray(s)&&(s=[s]),!Array.isArray(a)&&(a=[a]),d.type==="category"?o.push("echarts.option.xAxis"):o.push("echarts.option.yAxis"),c===1?a.forEach((g,m)=>{const _=p.indexOf(s[m]);l[0].data[_]=g}):l.forEach((g,m)=>{a[m].forEach((_,y)=>{const v=p.indexOf(s[y]);g.data[v]=_})})}}else n===j9.ReplaceAll&&(s&&(d.data=s,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,g)=>{p.data=a[g],p.data.splice(0,p.data.length-i)})));else{if(s){!Array.isArray(s)&&(s=[s]);const p=d.data;p.push(...s),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,g)=>{Array.isArray(a[g])||(a[g]=[a[g]]);const m=p.data;m.push(...a[g]),m.splice(0,m.length-i)})}return r.calculative.partialOption={},o.forEach(p=>{let g=AP(r,p);yue(r.calculative.partialOption,p,g)}),delete e.dataX,delete e.dataY,Object.assign(e,{echarts:t})}function d1t(r,e,t){if(t.key!=="dataY")return;const i=r.echarts,{xAxis:n,yAxis:s}=i.option;Array.isArray(n)&&n.length>1&&console.warn("echarts 只支持单 x 轴,多 x 轴将被忽略");const a=Array.isArray(n)?n[0]:n,o=Array.isArray(s)?s[0]:s,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:r.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(g=>g.dataId===f);p&&(u.push(d),c.push(p.value))}}),{id:r.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:g}=t.dataIds.find(m=>m.name===d.name);if(g){const m=e.find(_=>_.dataId===g);m&&(p.push([u,m.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:r.id,dataY:c.length===1?c[0]:c}}}function Cse(r){var t,i;const e=new Image;e.src=(i=(t=r.calculative.singleton)==null?void 0:t.echart)==null?void 0:i.getDataURL({pixelRatio:2}),r.calculative.img=e}function oZ(r,e){const t=Zt(r);if(t.dataZoom){let i=["right","top","width","height","left","bottom"];for(let n=0;n{isNaN(s[i[n]])||(s[i[n]]*=e)})}return _ue(t,Mue,e),t}function f1t(r){const e={};return Object.keys(r).forEach(t=>{const i=t.split(".");let n=e;i.forEach((s,a)=>{const o=!isNaN(parseInt(s));if(a===i.length-1)o?(Array.isArray(n)||(n=[]),n[parseInt(s)]=r[t]):n[s]=r[t];else if(o){const l=parseInt(s);if(Array.isArray(n)||n[i[a-1]],n[l]||(n[l]={}),Array.isArray(n))for(let c=0;c{r.calculative.singleton.highchart=e.chart(r.id,r.highcharts.option);const a=r.calculative.singleton.highchart.getSVG(),o=new Image;o.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(a))),r.calculative.img=o}),(n=r.calculative.canvas.externalElements)==null||n.parentElement.appendChild(s),Po(r,s)}return r.calculative.patchFlags&&r.calculative.singleton.div&&Po(r,r.calculative.singleton.div),t}function m1t(r){r.calculative.singleton&&r.calculative.singleton.div&&(r.calculative.singleton.div.remove(),r.calculative.singleton.highchart.destroy(),delete r.calculative.singleton.div,delete r.calculative.singleton.highchart)}function ATe(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function g1t(r){r.calculative.singleton.div&&(Po(r,r.calculative.singleton.div),setTimeout(()=>{r.calculative.singleton.highchart.reflow()},100))}function _1t(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function v1t(r,e){if(e.highcharts)return r.calculative.singleton.highchart.update(e.highcharts.option),e;if(!e.dataX&&!e.dataY)return e;const t=r.highcharts,i=t.max;let n=e.dataX,s=e.dataY;const a=t.option.series.length;if(e.overwrite)n&&(t.option.xAxis.categories=n,t.option.xAxis.categories.splice(0,t.option.xAxis.categories.length-i)),s&&(a===1?(t.option.series[0].data=s,t.option.series[0].data.splice(0,t.option.series[0].data.length-i)):t.option.series.forEach((l,c)=>{l.data=s[c],l.data.splice(0,l.data.length-i)})),r.calculative.singleton.highchart.update(t.option);else{let o=[],l=null,c=!1;if(n){Array.isArray(n)||(n=[n]);const u=t.option.xAxis,h=Array.isArray(u)?u[0].categories:u.categories;h&&(h.push(...n),h.splice(0,h.length-i),c=!0),o=[...n]}s&&(a===1?(Array.isArray(s)||(s=[s]),l=[s]):(l=[],t.option.series.forEach((u,h)=>{Array.isArray(s[h])||(s[h]=[s[h]]),l.push(s[h])}))),l&&r.calculative.singleton.highchart.series.forEach((h,d)=>{l[d].forEach((f,p)=>{let g=!1;i&&h.data.length>=i&&(g=!0);const m=c||o[p]==null?f:[o[p],f];h.addPoint(m,!0,g)})})}return delete e.dataX,delete e.dataY,delete e.overwrite,Object.assign(e,{highcharts:t})}function y1t(r){var i;if(!((i=r.calculative)!=null&&i.singleton))return;const e=r.calculative.singleton.highchart.getSVG(),t=new Image;t.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(e))),r.calculative.img=t}function x1t(r){let e=globalThis.lcjs;if(!r.lightningCharts||!e)return;if(typeof r.lightningCharts=="string")try{r.lightningCharts=JSON.parse(r.lightningCharts)}catch{}if(!r.lightningCharts)return;r.onDestroy||(r.onDestroy=C1t,r.onMove=STe,r.onResize=A1t,r.onRotate=STe,r.onValue=S1t,r.onRenderPenRaw=E1t);const t=new Path2D,i=r.calculative.worldRect;if(r.calculative.singleton||(r.calculative.singleton={}),!r.calculative.singleton.div){const n=document.createElement("div");n.style.position="absolute",n.style.outline="none",n.style.left="-9999px",n.style.top="-9999px",n.style.width=i.width+"px",n.style.height=i.height+"px",n.id=r.id,document.body.appendChild(n),r.calculative.singleton.div=n,setTimeout(()=>{NFe(r)},100),setTimeout(()=>{r.calculative.canvas.externalElements&&r.calculative.canvas.externalElements.parentElement.appendChild(n),Po(r,n);const s=new Image;s.src=r.calculative.singleton.div.children[0].toDataURL(),r.calculative.img=s},400)}return r.calculative.patchFlags&&r.calculative.singleton.div&&Po(r,r.calculative.singleton.div),t}function b1t(r){let e=r.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 n=[],s=1;s<7;s+=2)n.push(parseInt("0x"+e.slice(s,s+2)));return n}else if(e&&i.test(e))return e.match(/\(([^)]*)\)/)[1].split(",").map(l=>parseInt(l));return e}function NFe(r){const{lightningChart:e,PieChartTypes:t,LegendBoxBuilders:i,SliceLabelFormatters:n,Themes:s,GaugeChartTypes:a,SolidLine:o,SolidFill:l,ColorRGBA:c,UIOrigins:u,emptyLine:h,AutoCursorModes:d,AxisScrollStrategies:f,AxisTickStrategies:p,UIElementBuilders:g}=lcjs,m=r.lightningCharts.option.data,_=r.lightningCharts.option.title||"Title",y=s[r.lightningCharts.option.theme||"lightNew"];switch(r.calculative.singleton.lightningChart=e(),r.lightningCharts.option.type){case"line":const v=r.calculative.singleton.lightningChart.ChartXY({container:r.id}).setTitle(_);m.forEach(M=>{v.addLineSeries().setName(M.name).add(M.data)});break;case"bar":const x=r.calculative.singleton.lightningChart;let b;b=M=>{const k=[],z=[],W=x.ChartXY(M).setTitle(_).setAutoCursorMode(d.onHover).setMouseInteractions(!1).setPadding({bottom:30}),K=W.getDefaultAxisX().setMouseInteractions(!1).setScrollStrategy(void 0).setTickStrategy(p.Empty);W.getDefaultAxisY().setMouseInteractions(!1).setTitle(r.lightningCharts.option.yTitle).setInterval(0,70).setScrollStrategy(f.fitting),W.setAutoCursor(Z=>Z.disposePointMarker().disposeTickMarkerX().disposeTickMarkerY().setGridStrokeXStyle(h).setGridStrokeYStyle(h).setResultTable(te=>{te.setOrigin(u.CenterBottom)}));const U=Z=>{const te=W.addRectangleSeries();return te.setCursorResultTableFormatter((le,ce,ue)=>{let N={name:Z.name,value:Z.data[Z.figures.indexOf(ue)]};return le.addRow("Department:",N.name).addRow("# of employees:",String(N.value))}),te},j=W.addLegendBox(i.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.2}),B=()=>{let Z=0;for(let te=0;te{const te=U(Z).setName(Z.name);Z.figures=Z.data.map(le=>te.add({x:0,y:0,width:0,height:0})),j.add(te),z.push(Z),B()},addGroups:Z=>{for(const te of Z)k.push({name:te,tick:K.addCustomTick(g.AxisTick).setGridStrokeLength(0).setTextFormatter(le=>te)})}}};const C=b({theme:y,container:r.id});C.addGroups(r.lightningCharts.option.groups);const A=r.lightningCharts.option.categories;m.forEach((M,R)=>C.addCategory({name:A[R],data:M}));break;case"pie":const E=r.calculative.singleton.lightningChart.Pie({theme:y,container:r.id}).setTitle(_).setAnimationsEnabled(!0).setMultipleSliceExplosion(!0);m.map(M=>E.addSlice(M.name,M.value)),E.setInnerRadius(r.lightningCharts.option.innerRadius||0).setLabelFormatter(n.NamePlusRelativeValue),E.addLegendBox(i.VerticalLegendBox).setAutoDispose({type:"max-width",maxWidth:.3}).add(E);break;case"gauge":const P=r.calculative.singleton.lightningChart.Gauge({theme:y,container:r.id}).setTitle(_).setThickness(20).setAngleInterval(r.lightningCharts.option.startAngle||225,r.lightningCharts.option.endAngle||-45);let w=b1t(r.lightningCharts.option.background);P.getDefaultSlice().setInterval(r.lightningCharts.option.min||0,r.lightningCharts.option.max||100).setValue(m).setFillStyle(new l({color:c(w[0],w[1],w[2])}));break}}function C1t(r){r.calculative.singleton&&r.calculative.singleton.div&&(r.calculative.singleton.div.remove(),delete r.calculative.singleton.div,delete r.calculative.singleton.lightningChart)}function STe(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function A1t(r){r.calculative.singleton.div&&Po(r,r.calculative.singleton.div)}function S1t(r){r.calculative.singleton.div&&(NFe(r),Po(r,r.calculative.singleton.div))}function E1t(r){var t;if(!((t=r.calculative)!=null&&t.singleton))return;const e=new Image;e.src=r.calculative.singleton.div.children[0].toDataURL(),r.calculative.img=e}function T1t(r){Q1({echarts:o1t})}function M1t(r){Q1({highcharts:p1t})}function R1t(r){Q1({lightningCharts:x1t})}var lZ;(function(r){r[r.Add=0]="Add",r[r.Replace=1]="Replace",r[r.ReplaceAll=2]="ReplaceAll"})(lZ||(lZ={}));function FFe(r,e){const t=e.calculative.worldRect.height*14/16,n=(r.match(/[\u4e00-\u9fa5]/g)||"").length;return(r.length-n)*t*.6+n*t}function BFe(r){if(r.direction=="horizontal"){const e=[];let t=0;const i=r.height;r.checkboxHeight=i,r.options.forEach((s,a)=>{e.push(a*(40+i)+t),t+=FFe(s.text,r)}),r.optionPos=e;const n=e.length*(40+i)+t;r.checkboxWidth=n,r.width=n,r.calculative.width=n,r.calculative.worldRect={x:r.x,y:r.y,height:r.height,width:r.width,center:{x:r.x+r.width/2,y:r.y+r.height/2}},Yl(r.calculative.worldRect)}else if(r.direction=="vertical"){r.optionInterval==null&&(r.optionInterval=20),r.optionHeight||(r.optionHeight=20);const e=[];r.options.forEach((i,n)=>{e.push(n*(r.optionInterval+r.optionHeight))}),r.optionPos=e;const t=e[e.length-1]+r.optionHeight;r.checkboxHeight=t,r.width||(r.height=t,r.calculative.height=t,r.calculative.worldRect={x:r.x,y:r.y,height:r.height,width:r.width,center:{x:r.x+r.width/2,y:r.y+r.height/2}},Yl(r.calculative.worldRect))}}function ETe(r,e){e.onAdd||(e.onAdd=kFe,(!e.rowPos||!e.colPos||!e.calculative.maxOffsetY)&&e.onAdd(e),e.onMouseMove=N1t,e.onMouseLeave=F1t,e.onMouseDown=B1t,e.onShowInput=O1t,e.onInput=L1t,e.onValue=z1t,e.onBeforeValue=V1t,e.onMouseEnter=j1t,e.onWheel=G1t,e.onDestroy=K1t),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.data,i=e.calculative.canvas.store.options;if(e.color=e.color||t.color||i.color,e.textColor=e.textColor||e.color||t.textColor||i.textColor,e.activeColor=e.activeColor||i.activeColor,e.hoverColor=e.hoverColor||i.hoverColor,e.activeBackground=e.activeBackground||i.activeBackground,e.hoverBackground=e.hoverBackground||i.hoverBackground,!e.hasHeader){r.save(),r.beginPath();const{x:n,y:s,width:a,height:o}=e.calculative.worldRect;r.fillStyle="#fff0",r.rect(n-1,s-1,a+2,o+2),r.fill(),r.clip()}w1t(r,e),D1t(r,e),I1t(r,e),r.restore(),e.isFirstTime=!1}function I1t(r,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={};s&&s.forEach(f=>{a[f.col]=f.width});for(let f=0;fg.col===f&&g.row===void 0);p&&(i[f]=p[0])}let o=0;const l=r.styles&&r.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;r.beginPath(),r.moveTo(e.calculative.worldRect.x,e.calculative.worldRect.y+f),r.lineTo(e.calculative.worldRect.ex,e.calculative.worldRect.y+f),r.strokeStyle=e.borderColor||"#424B61",r.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;r.beginPath(),r.moveTo(e.calculative.worldRect.x+p,e.calculative.worldRect.y),r.lineTo(e.calculative.worldRect.x+p,e.calculative.worldRect.ey),r.strokeStyle=e.borderColor||"#424B61",r.stroke()})}r.restore()}function D1t(r,e){var i,n,s,a,o;if(!e.colPos)return;e.calculative.texts||(e.calculative.texts=[]);const t=1;for(let l=0;l0){let E=0;d.forEach((P,w)=>{P.wheres&&P.wheres.every(R=>new Function("attr",`return attr ${R.comparison} ${R.value}`)(h))&&(E=w)}),d=d[E]}else d.wheres&&Array.isArray(d.wheres)&&(f=!1,f=d.wheres.every(function(E){return new Function("attr",`return attr ${E.comparison} ${E.value}`)(h)}));let p=e.color,g=e.textColor||e.color,m=null,_=null,y=null,v=null;f&&(p=d.color||c.color||e.color,g=d.textColor||c.textColor||e.textColor,m=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&&(m=m||e.stripeColor||"#407FFF1F"):l%2===0&&(m=m||e.stripeColor||"#407FFF1F")),e.calculative.active&&((i=e.calculative.activeCell)==null?void 0:i.row)===l&&((n=e.calculative.activeCell)==null?void 0:n.col)===u&&(p=e.activeColor,m=e.activeBackground,x=p,g=e.activeTextColor||e.activeColor),e.calculative.hover&&((s=e.calculative.hoverCell)==null?void 0:s.row)===l&&((a=e.calculative.hoverCell)==null?void 0:a.col)===u&&(p=e.hoverColor,m=e.hoverBackground,g=e.hoverTextColor||e.hoverColor,x=p);const b=GFe(e,l,u);if(b.y+b.heighte.calculative.worldRect.height+e.calculative.worldRect.y)continue;m&&(r.save(),r.beginPath(),r.fillStyle=m,r.fillRect(b.x,b.y,b.width+.25*e.calculative.canvas.store.data.scale,b.height),r.restore()),x&&(r.save(),r.beginPath(),r.strokeStyle=x,r.strokeRect(b.x,b.y,b.width,b.height),r.restore()),e.calculative.worldTextRect=b;let C=e.calculative.texts[l];if(e.calculative.texts[l]||(C=[],e.calculative.texts.push(C)),C[u]==null){if(typeof h=="object"){const E=e.styles&&e.styles.filter(P=>P.col===u&&P.row===void 0&&P.pens);if(E.length>0){if(C[u]="",e.isFirstTime){e.maxNum&&e.hasHeader&&l>=e.maxNum&&(h.visible=!1);let P=JSON.parse(JSON.stringify(E[0].pens));P.forEach(w=>{Object.assign(w,{row:l,col:u},h),w.activeBackground=w.background,w.hoverBackground=w.background,w.activeColor=w.color,w.hoverColor=w.color,w.activeTextColor=w.textColor,w.hoverTextColor=w.textColor,w.height*=e.calculative.canvas.store.data.scale,w.width*=e.calculative.canvas.store.data.scale}),U1t(e,b,P),e.calculative.canvas.parent.pushChildren(e,P)}continue}}else h===void 0?C[u]="":C[u]=h.text||h+"";if(!C[u])continue;C[u]=xz(e,C[u])}if(!C[u])continue;r.save(),r.beginPath(),r.fillStyle=g,r.textAlign="center",r.textBaseline="middle",r.font=(v||e.calculative.fontStyle||"")+" normal "+(y||e.calculative.fontWeight||"")+" "+(_||e.calculative.fontSize||12)*t+"px "+e.calculative.fontFamily;let A=e.colStyle&&((o=e.colStyle[u])==null?void 0:o.textAlign);if(A&&(r.textAlign=A),C[u].length===1)A==="left"?r.fillText(C[u][0],b.x,b.y+b.height/2):A==="right"?r.fillText(C[u][0],b.x+b.width,b.y+b.height/2):r.fillText(C[u][0],b.x+b.width/2,b.y+b.height/2);else{const P=(_||e.calculative.fontSize)*e.calculative.lineHeight*t,w=C[u].length*P;let M=(b.height-w)/2;A==="left"?C[u].forEach((R,I)=>{r.fillText(R,b.x,b.y+M+(I+.55)*P)}):A==="right"?C[u].forEach((R,I)=>{r.fillText(R,b.x+b.width,b.y+M+(I+.55)*P)}):C[u].forEach((R,I)=>{r.fillText(R,b.x+b.width/2,b.y+M+(I+.55)*P)})}r.restore()}}}function kFe(r){var e;Gge(r),(e=r.children)!=null&&e.length||(r.isFirstTime=!0),r.offsetY||(r.offsetY=0),P1t(r)}function O1t(r,e){if(!r.calculative.hoverCell)return;const{value:t}=zFe(r,r.calculative.hoverCell.row,r.calculative.hoverCell.col);if(typeof t=="object")return;r.calculative.isHover=!1,r.calculative.isInput=!0,r.calculative.canvas.render(),r.calculative.inputCell=r.calculative.hoverCell;const i=GFe(r,r.calculative.hoverCell.row,r.calculative.hoverCell.col);r.calculative.tempText=t.text||t+"",r.calculative.canvas.showInput(r,i,"#ffffff")}function L1t(r,e){r.calculative.inputCell&&(VFe(r,r.calculative.inputCell.row,r.calculative.inputCell.col,e),r.calculative.isInput=!1,r.calculative.isHover=!0,r.calculative.canvas.render())}function N1t(r,e){r.timer&&(r.calculative.isHover=!1,clearTimeout(r.timer)),r.timer=setTimeout(()=>{r.calculative.isHover=!0,r.calculative.canvas.render()},500),r.calculative.hoverCell=UFe(r,e),r.calculative.canvas.render()}function F1t(r,e){Gge(r),r.calculative.hoverCell=void 0,r.calculative.canvas.render()}function B1t(r,e){r.calculative.activeCell=UFe(r,e),r.calculative.canvas.render()}function UFe(r,e){const t=r.calculative.worldRect.width/r.tableWidth,i=r.calculative.worldRect.height/r.tableHeight,n={row:0,col:0};for(let s=0;sr.calculative.worldRect.x+r.colPos[s]*t&&(n.col=s+1);for(let s=0;sr.calculative.worldRect.y+r.rowPos[s]*i-r.offsetY*r.calculative.canvas.store.data.scale&&(n.row=s+1);return n}function zFe(r,e,t){if(!r.data||!Array.isArray(r.data))return;const i=r.data[e],n=r.styles&&r.styles.filter(s=>s.row===e&&s.col===t);if(Array.isArray(i))return{value:i[t],style:(n==null?void 0:n.length)>0?n.length>1?n:n[0]:{}};if(!i.data||!Array.isArray(i.data))return}function k1t(r,e){if(!r.data||!Array.isArray(r.data))return;const t=r.data[e],i=r.styles&&r.styles.filter(n=>n.row===e&&!n.col);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 VFe(r,e,t,i){if(!r.data||!Array.isArray(r.data))return;r.isFirstTime=!1,r.calculative.texts=void 0;let n=r.data[e];n&&(n[t]instanceof Object||(n[t]=i),r.calculative.canvas.store.emitter.emit("valueUpdate",r))}function GFe(r,e,t){const i=r.calculative.worldRect.width/r.tableWidth,n=r.calculative.worldRect.height/r.tableHeight;let s=0,a=r.colPos[t]*i;t>0&&(s=r.colPos[t-1]*i);let o=0,l=r.rowPos[e]*n;e>0&&(o=r.rowPos[e-1]*n);let c=r.offsetY*r.calculative.canvas.store.data.scale;return e===0&&r.hasHeader&&(c=0),{x:r.calculative.worldRect.x+s,y:r.calculative.worldRect.y+o-c,ex:r.calculative.worldRect.x+a,ey:r.calculative.worldRect.y+l-c,width:a-s,height:l-o}}function U1t(r,e,t){if(!(t&&t.length))return;const i=r.calculative.worldRect.width/r.tableWidth,n=r.calculative.worldRect.height/r.tableHeight;let s=1,a=1;r.initWorldRect&&(r.calculative.worldRect.width!==r.initWorldRect.width&&(s=r.calculative.worldRect.width/r.initWorldRect.width),r.calculative.worldRect.height!==r.initWorldRect.height&&(a=r.calculative.worldRect.height/r.initWorldRect.height));let o=0,l=0,c=0;const u=r.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*s,h.height=h.height*a})}function z1t(r){if(r.calculative.isUpdateData){delete r.calculative.isUpdateData;let e=Zt(r.children);r.children=[],kFe(r),e&&e.forEach(t=>{r.calculative.canvas.delForce(r.calculative.canvas.findOne(t))}),r.calculative.texts=void 0}}function V1t(r,e){if(r.calculative.isUpdateData=!1,r.swiper!==void 0&&(r.swiper?Gge(r):Vge(r)),e.styles&&(r.initWorldRect=void 0),e.table||e.col==null&&e.row==null){if(e.dataY){const i=r.replaceMode;let n=[];return i?i===lZ.Replace?(n=r.data,e.dataX&&e.dataX.forEach((s,a)=>{n[s]=e.dataY[a]})):i===lZ.ReplaceAll&&(e.dataX?n[0]=e.dataX:n[0]=r.data[0],n=n.concat(e.dataY)):n=r.data.concat(e.dataY),delete e.dataX,delete e.dataY,r.calculative.isUpdateData=!0,Object.assign(e,{data:n})}(e.data||e.styles||e.maxNum||e.rowHeight||e.colWidth)&&(r.calculative.isUpdateData=!0,r.initWorldRect=null);for(let i of Object.keys(e))i.includes("data.")&&(r.calculative.isUpdateData=!0);return e}let t=r.data[e.row];return t&&(t[e.col]instanceof Object||(t[e.col]=e.value),VFe(r,e.row,e.col,e.value),r.calculative.canvas.render(),delete e.col,delete e.row),e}function G1t(r,e){if(!r.locked&&!r.calculative.canvas.store.data.locked||!r.maxNum)return;let t=0;e.deltaY>0?t=4:t=-4,Rue(r,t)}function Rue(r,e){var t;r.offsetY||(r.offsetY=0),r.offsetY+=e,r.offsetY>r.calculative.maxOffsetY&&(r.offsetY=r.calculative.maxOffsetY),r.offsetY<0&&(r.offsetY=0),(t=r.children)==null||t.forEach(i=>{const n=r.calculative.canvas.store.pens[i];W1t(r,n)}),r.calculative.canvas.render()}function W1t(r,e){if(!e)return;e.oldY||(e.oldY=e.y),e.calculative.worldRect,r.calculative.worldRect;const t=r.calculative.canvas.store.data.scale;r.calculative.worldRect.height/r.tableHeight;const i=r.rowHeight;e.y=e.oldY-r.offsetY*t/r.calculative.worldRect.height;const n=i*(r.initScale||1)/r.tableHeight*r.maxNum;if(r.calculative.canvas.updatePenRect(e),r.hasHeader)if(e.y1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=n;let s=e.row-r.maxNum;if(!r.data[s])return;let a=Zt(r.data[s][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:s}),Object.assign(e.calculative,a,{row:s})}}else e.visible=!0,e.calculative.visible=!0;else if(e.y<0){if(e.calculative.visible=!1,e.visible=!1,e.y<-i/r.tableHeight/2){e.oldY+=n;let s=e.row+r.maxNum;if(!r.data[s])return;let a=Zt(r.data[s][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:s}),Object.assign(e.calculative,a,{row:s})}}else if(e.y+e.height>1){if(e.calculative.visible=!1,e.visible=!1,e.y+e.height/2>1){e.oldY-=n;let s=e.row-r.maxNum;if(!r.data[s])return;let a=Zt(r.data[s][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:s}),Object.assign(e.calculative,a,{row:s})}}else e.calculative.visible=!0,e.visible=!0}function K1t(r){Vge(r)}function Vge(r){r.interval&&(globalThis.clearInterval(r.interval),r.interval=null)}function Gge(r){if(r.maxNum&&r.swiper){if(r.interval)return;r.interval=globalThis.setInterval(()=>{r.offsetY>=r.calculative.maxOffsetY?(r.offsetY=0,H1t(r)):r.offsetY%r.rowHeight?Rue(r,1):(r.calculative.stap||(r.calculative.stap=0),r.calculative.stap+=1,r.calculative.stap==12&&(r.calculative.stap=0,Rue(r,1)))},50)}}function H1t(r){var e;(e=r.children)==null||e.forEach(t=>{const i=r.rowHeight,n=r.calculative.canvas.store.pens[t];if(!n)return;const s=i*(r.initScale||1)/r.tableHeight*r.maxNum;n.oldY-=s;const a=n.row-r.maxNum;if(!r.data[a])return;let o=Zt(r.data[a][n.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),n.calculative.visible=!0,n.visible=!0,Object.assign(n,o,{row:a}),Object.assign(n.calculative,o,{row:a})}),r.calculative.canvas.render()}function j1t(r){Vge(r)}function $1t(r,e){e.onClick||(e.onClick=X1t);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,n=e.calculative.worldRect.width,s=e.calculative.worldRect.height;n2?s/2-2:1,0,Math.PI*2),r.fill()):(r.fillStyle=e.offColor,(e.disabled||e.disable)&&(r.fillStyle=e.disableOffColor||ph(.6,e.offColor)),e.lineWidth&&(r.strokeStyle=e.offStrokeColor,r.stroke()),r.fill(),r.closePath(),r.beginPath(),r.fillStyle="#ffffff",r.moveTo(t+s,i+s/2),r.arc(t+s/2,i+s/2,s/2>2?s/2-2:1,0,Math.PI*2),r.fill()),r.closePath()}function X1t(r){r.disabled||r.disable||(r.checked=!r.checked,r.calculative.canvas.store.emitter.emit("valueUpdate",r),r.calculative.canvas.render())}function Y1t(r,e){e.onAdd||(e.onAdd=b9,e.onResize=b9,e.onMove=b9,e.onMouseMove=Q1t,e.onMouseDown=WFe,e.onValue=Z1t,e.onBeforeValue=q1t),e.calculative.barRect||b9(e),e.calculative.canvas.store.data;const t=e.calculative.canvas.store.options;let i=e.background;e.disabled&&(i=e.disabledBackground||ph(.6,i)),r.fillStyle=i,r.beginPath();let n=e.calculative.worldRect.x+e.calculative.barRect.x,s=e.calculative.worldRect.y+e.calculative.barRect.y,a=e.calculative.barRect.width,o=e.calculative.barRect.height,l=o/2;r.moveTo(n+l,s),r.arcTo(n+a,s,n+a,s+o,l),r.arcTo(n+a,s+o,n,s+o,l),r.arcTo(n,s+o,e.x,e.y,l),r.arcTo(n,s,n+a,s,l),r.fill();let c=e.activeColor||t.activeColor;e.disabled&&(c=e.disabledColor||ph(.6,c)),r.fillStyle=c,r.beginPath(),a=e.calculative.ballRect.x,r.moveTo(n+l,s),r.arcTo(n+a,s,n+a,s+o,l),r.arcTo(n+a,s+o,n,s+o,l),r.arcTo(n,s+o,e.x,e.y,l),r.arcTo(n,s,n+a,s,l),r.fill(),r.fillStyle=e.btnBackground||"#fff",r.strokeStyle=c,r.lineWidth=2,r.beginPath(),n=e.calculative.worldRect.x+e.calculative.ballRect.x,s=e.calculative.worldRect.y+e.calculative.ballRect.y+e.calculative.ballRect.height/2,r.lineWidth=e.calculative.ballRect.width/10,r.arc(n,s,e.calculative.ballRect.width/2,0,Math.PI*2),r.fill(),r.stroke()}function b9(r){if(r._textWidth||(r._textWidth=r.textWidth||50,r._fontSize=r.fontSize||12),r.textWidth=r.calculative.worldRect.width,r.calculative.textWidth=r.textWidth,r.unit||(r.unit="%"),r.sliderWidth||(r.sliderWidth=r.width),r.sliderHeight||(r.sliderHeight=r.height),!r.calculative.worldRect)return;const e=r.calculative.worldRect.width/r.sliderWidth,t=r.calculative.worldRect.height/r.sliderHeight,i=Math.min(e,t);r.fontSize=r._fontSize*i;const n=r.calculative.worldRect.width-r._textWidth*i;r.textLeft=n+10*i,r.calculative.textLeft=r.textLeft,r.calculative.barRect={x:0,y:(r.calculative.worldRect.height-r.barHeight*t)/2,width:n,height:r.barHeight*t},Yl(r.calculative.barRect),Wge(r)}function Wge(r){const e=r.calculative.barRect.height*3.5,t=r.calculative.barRect.width*r.value/100;r.calculative.ballRect={x:t,y:(r.calculative.worldRect.height-e)/2,width:e,height:e},Yl(r.calculative.ballRect),r.calculative.text=r.value+r.unit,t_(r)}function WFe(r,e){if(r.disabled)return;const t=e.x-r.calculative.worldRect.x;if(t>r.calculative.barRect.width)return;let i=Math.round(t/r.calculative.barRect.width*100);ir.max||i<0||i>100||(r.value=i,Wge(r),r.calculative.text=r.value+r.unit,t_(r),r.calculative.canvas.store.emitter.emit("valueUpdate",r),r.calculative.canvas.render())}function Q1t(r,e){r.calculative.canvas.mouseDown&&WFe(r,e)}function Z1t(r){r.calculative.isUpdateData&&(delete r.calculative.isUpdateData,b9(r)),Wge(r)}function q1t(r,e){return r.calculative.isUpdateData=!1,(e.textWidth||e.barHeight)&&(e.textWidth&&(r._textWidth=0),r.calculative.isUpdateData=!0),e}function J1t(r,e){e.onMouseDown||(e.onMouseDown=e_t),e.options||(e.options=e.data);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,n=e.calculative.worldRect.height;e.calculative.worldRect.width;const{fontStyle:s,fontWeight:a,fontSize:o,fontFamily:l,lineHeight:c}=e.calculative;let u=2;r.beginPath(),r.moveTo(t,i),r.arcTo(t+n,i,t+n,i+n,u),r.arcTo(t+n,i+n,t,i+n,u),r.arcTo(t,i+n,t,i,u),r.arcTo(t,i,t+n,i,u),r.strokeStyle="#d9d9d9",r.fillStyle="#ffffff00",e.checked&&(r.fillStyle=e.background||"#1890ff",r.strokeStyle=e.background||"#1890ff"),(e.isForbidden||e.disabled)&&(r.fillStyle=e.disabledBackground||ph(.6,e.background)||"#ebebeb",r.strokeStyle=e.disabledColor||ph(.6,e.color)||"#d9d9d9"),r.closePath(),r.fill(),r.stroke(),r.save(),e.checked&&(r.beginPath(),r.lineWidth=n/10,r.strokeStyle="#ffffff",r.moveTo(t+102/506*n,i+n/2),r.lineTo(t+220/506*n,i+346/460*n),r.lineTo(t+404/506*n,i+142/460*n),r.stroke()),r.restore(),r.save(),r.fillStyle=e.disabled||e.isForbidden?e.disabledTextColor||ph(.6,e.textColor||e.color)||"#00000040":kx(e,e.calculative.canvas.parent.store)||"#000000d9",r.textAlign="start",r.textBaseline="middle",r.font=wp({fontStyle:s,fontWeight:a,fontFamily:l||e.calculative.canvas.parent.store.options.fontFamily,fontSize:o,lineHeight:c}),r.fillText(e.value+"",t+n+10,i+n/2),r.restore()}function e_t(r,e){r.isForbidden||(r.checked=!r.checked,r.calculative.canvas.store.emitter.emit("valueUpdate",r),r.calculative.canvas.render())}function t_t(r,e){e.options||(e.options=e.data),e.onAdd||(e.onAdd=i_t,e.optionPos||(e.onAdd(e),e.calculative.canvas.parent.active([e])),e.onMouseDown=r_t,e.onValue=n_t);let t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,n=e.calculative.worldRect.height,s=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;hr.calculative.worldRect.x+r.optionPos[t]*r.calculative.worldRect.width/r.checkboxWidth&&e.xr.calculative.worldRect.y+r.optionPos[i]*t&&e.y{const e=a_t(r);r.calculative.canvas.parent.setValue({id:r.id,text:e},{history:!1,doEvent:!1,render:!1}),r.calculative.canvas.render()},r.timeout||1e3)}function l_t(r){r.interval&&(clearInterval(r.interval),r.interval=void 0)}function c_t(){return{radio:t_t,switch:$1t,slider:Y1t,checkbox:J1t,table:ETe,table2:ETe}}function u_t(){return{time:s_t}}const h_t=15;function IA(r,e=h_t){let t=""+r;return t.indexOf(".")>=0&&(t=Number.parseFloat(t).toFixed(e)),Number.parseFloat(t)}function Ase(r){return typeof r=="number"&&Number.isFinite(r)}function d_t(r){r={max:null,min:null,splitNumber:4,symmetrical:!1,deviation:!1,preferZero:!1,...r};const e=[10,15,20,25,30,40,50,60,70,80,90,100,150];let{max:t,min:i,splitNumber:n,symmetrical:s,deviation:a,preferZero:o}=r;if(!Ase(t)||!Ase(i)||t0&&(t<0?t=0:i=0);const l=(t-i)/n;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,g=i;function m(y){if(p=parseInt(""+(t/y+1))*y,g=parseInt(""+(i/y-1))*y,t===0&&(p=0),i===0&&(g=0),s&&p*g<0){const v=Math.max(Math.abs(p),Math.abs(g));p=v,g=-v}}if(m(h),a)return{max:IA(p),min:IA(g),interval:IA(h),splitNumber:Math.round((p-g)/h)};if(!s||p*g>0){let y;e:do{if(y=Math.round((p-g)/h),(f-d)*(y-n)<0){for(;y=e.length-1||f<=0||y===n)break;d=f,y>n?h=e[++f]*c:h=e[--f]*c,m(h)}while(y!==n)}p=IA(p),g=IA(g);const _=IA((p-g)/n);return{max:p,min:g,interval:_,splitNumber:n}}function KFe(r,e){var m,_,y,v,x,b,C,A,E,P,w,M,R,I,D,k,z,W,K,U,j,B,G,Y,Z,te,le,ce;const t=e.calculative.worldRect.x,i=e.calculative.worldRect.y,n=e.calculative.worldRect.width,s=e.calculative.worldRect.height;let a=e.calculative.canvas.store.data.scale,o=[];if(e.echarts)for(let ue=0;ue{p=t+(1+l/2)+(l+1)*b,g=i+n-(f[b]-c.min)/(c.max-c.min)*n;let C=t+(1+l/2)+(l+1)*(b+1),A=i+n-(f[b+1]-c.min)/(c.max-c.min)*n,E=t+(1+l/2)+(l+1)*(b-1),P=i+n-(f[b-1]-c.min)/(c.max-c.min)*n,w=t+(1+l/2)+(l+1)*(b+2),M=i+n-(f[b+2]-c.min)/(c.max-c.min)*n;b===0?(E=t+(1+l/2)+(l+1)*b,P=i+n-(f[b]-c.min)/(c.max-c.min)*n):b===f.length-2&&(w=t+(1+l/2)+(l+1)*(b+1),M=i+n-(f[b+1]-c.min)/(c.max-c.min)*n),h.push({x:p,y:g}),m=p+(C-E)/4,_=g+(A-P)/4,y=C-(w-p)/4,v=A-(M-g)/4,r.bezierCurveTo(m,_,y,v,C,A)})}else for(let m=1;m{r.beginPath(),r.strokeStyle="#fff",r.lineWidth=2*s,r.arc(m.x,m.y,4*s,0,Math.PI*2),r.stroke(),r.fill(),r.closePath()}),r.restore(),h=[]}}function HFe(r,e){if(e.xAxisData||e.data||!e.dataX&&!e.dataY)return e;const t=r.xAxisData,i=r.data,n=r.replaceMode;let s=[],a=[];return n?n===iw.Replace?(e.dataX.forEach((o,l)=>{let c=t.indexOf(o);i.forEach((u,h)=>{u[c]=e.dataY[h][l]})}),s=t,a=i):n===iw.ReplaceAll&&(s=e.dataX,a=e.dataY):(s=[...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:s,data:a})}function m_t(r,e){var u,h;e.onBeforeValue||(e.onBeforeValue=g_t);let t=e.calculative.canvas.store.data.scale;const i=e.calculative.worldRect.x,n=e.calculative.worldRect.y,s=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;dA+E.value,0):_=f.reduce((A,E)=>A+E.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,b=0;r.strokeStyle=o&&((u=f.itemStyle)==null?void 0:u.borderColor)||"#fff",r.lineWidth=(o&&((h=f.itemStyle)==null?void 0:h.borderWidth)||2)*t;const C=o?f.data:f;C.forEach((A,E)=>{var k,z,W,K,U,j,B,G,Y,Z;b+=Math.PI*2*A.value/_,r.beginPath();let P=c+E;P>=e.chartsColor.length&&(P=P%e.chartsColor.length),r.fillStyle=o?e.echarts.option.color[P]:e.chartsColor[P],r.moveTo(g+y*Math.sin(b),m-y*Math.cos(b)),r.arc(g,m,y,-Math.PI/2+b,-Math.PI/2+x,!0),r.lineTo(g+v*Math.sin(x),m-v*Math.cos(x)),r.arc(g,m,v,-Math.PI/2+x,-Math.PI/2+b),r.lineTo(g+y*Math.sin(b),m-y*Math.cos(b)),r.stroke(),r.fill(),r.closePath();let w=(x+b)/2,M=g+(v+10*t)*Math.sin(w),R=m-(v+10*t)*Math.cos(w),I=r.fillStyle;f.label||(f.label={position:"outside",show:!0}),o&&["inner","inside"].includes(f.label.position)?(r.fillStyle="#ffffff",M=g+(v-y)/2*Math.sin(w),R=m-(v-y)/2*Math.cos(w)):o&&f.label.position=="outside",f.labelLine||(f.labelLine={show:!0}),(o&&f.labelLine.show!==!1||!o)&&(r.beginPath(),r.strokeStyle=o?e.echarts.option.color[c+E]:e.chartsColor[c+E],r.moveTo(g+v*Math.sin(w),m-v*Math.cos(w)),r.lineTo(M,R));let D={fontStyle:((k=e.tickLabel)==null?void 0:k.fontStyle)||e.calculative.fontStyle,fontWeight:((z=e.tickLabel)==null?void 0:z.fontWeight)||e.calculative.fontWeight,fontFamily:((W=e.tickLabel)==null?void 0:W.fontFamily)||e.calculative.fontFamily,lineHeight:((K=e.tickLabel)==null?void 0:K.lineHeight)||e.calculative.lineHeight,fontSize:(((U=e.tickLabel)==null?void 0:U.fontSize)||e.calculative.fontSize)*t};r.font=wp(D),r.textBaseline="middle",r.textAlign="center",w>Math.PI?((o&&f.label.position==="outside"||!o)&&(r.textAlign="end"),(o&&f.labelLine.show!==!1||!o&&(((B=(j=e.tickLabel)==null?void 0:j.labelLine)==null?void 0:B.show)??!0))&&r.lineTo(M-5*t,R),(o&&f.label.show!==!1||!o&&(((G=e.tickLabel)==null?void 0:G.show)??!0))&&r.fillText(A.name,M-5*t,R)):((o&&f.label.position==="outside"||!o)&&(r.textAlign="start"),(o&&f.labelLine.show!==!1||!o)&&r.lineTo(M+5*t,R),(o&&f.label.show!==!1||!o&&(((Y=e.tickLabel)==null?void 0:Y.show)??!0))&&r.fillText(A.name,M+5*t,R)),r.stroke(),r.closePath(),r.fillStyle=I,r.strokeStyle=o&&((Z=f.itemStyle)==null?void 0:Z.borderColor)||"#fff",x=b}),c+=C.length}}function g_t(r,e){if(e.data||!e.dataX&&!e.dataY)return e;const t=r.data,i=r.replaceMode;let n=[];return i?i===iw.Replace?(e.dataY.forEach((s,a)=>{s.forEach((o,l)=>{let c=t[a].filter(u=>u.name===o.name);c.length>0&&(c[0].value=o.value)})}),n=t):i===iw.ReplaceAll&&(n=e.dataY):t.forEach((s,a)=>{let o=[...s,...e.dataY[a]];n.push(o)}),delete e.dataX,delete e.dataY,Object.assign(e,{data:n})}function __t(r,e){e.onBeforeValue||(e.onBeforeValue=HFe);let t=e.calculative.canvas.store.data.scale;const i=e.calculative.worldRect.x,n=e.calculative.worldRect.y;e.calculative.worldRect.width;const s=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;hs?s/2*9/10:n/2*9/10,c=t+n/2,u=i+s/2,h=e.echarts?e.echarts.option.series[0].data[0].value:e.value,d,f=e.startAngle-e.endAngle,p=e.background||"#E6EBF8";r.strokeStyle=p;let g=l/10;r.lineWidth=g,r.beginPath(),r.lineCap="round",r.arc(c,u,l,-e.startAngle/180*Math.PI,-e.endAngle/180*Math.PI),r.stroke(),r.closePath();let m=0;if(e.axisLine&&!e.isClock)for(let J=e.axisLine.length-1;J>=0;J--)e.axisLine[J][0]*(e.max-e.min).02?r.textAlign="end":ne<-.02?r.textAlign="start":r.textAlign="center",he>.02?r.textBaseline="top":he<-.02?r.textBaseline="bottom":r.textBaseline="middle",r.fillText(f_t(R*J+e.min),c+D*ne,u-D*he),r.fill()}r.closePath();let k=1,z=["value"];if(e.isClock&&(k=3,z=["hourvalue","minutevalue","secondvalue"]),e.isClock)for(let J=0;J0&&(ae=(e.startAngle-(e[z[J]]-e.min)/(e.max*5-e.min)*f)/180*Math.PI);let ne=4/5*l;z[J]==="hourvalue"&&(ne=3/5*l),z[J]==="minutevalue"&&(ne=3.5/5*l);let he=l*1/40;r.beginPath(),r.setLineDash([]),r.lineWidth=l/(J+1)/20,r.strokeStyle=e.color||"#999999",r.moveTo(c-he*3*Math.cos(ae),u+he*3*Math.sin(ae)),r.lineTo(c+ne*Math.cos(ae),u-ne*Math.sin(ae)),r.stroke()}else{let J=(e.startAngle-(h-e.min)/(e.max-e.min)*f)/180*Math.PI,ae=4/5*l,ne=l*1/40;r.beginPath(),r.setLineDash([]),r.lineWidth=2,r.fillStyle=d,r.moveTo(c-ne*3*Math.cos(J),u+ne*3*Math.sin(J)),r.lineTo(c+ne*Math.cos(J-Math.PI/2),u-ne*Math.sin(J-Math.PI/2)),r.lineTo(c+ae*Math.cos(J),u-ae*Math.sin(J)),r.lineTo(c+ne*Math.cos(J+Math.PI/2),u-ne*Math.sin(J+Math.PI/2)),r.lineTo(c-ne*3*Math.cos(J),u+ne*3*Math.sin(J)),r.fill()}r.beginPath(),r.textAlign="center",r.textBaseline="middle";let W={fontStyle:((te=e.titleLabel)==null?void 0:te.fontStyle)||e.calculative.fontStyle,textDecoration:((le=e.titleLabel)==null?void 0:le.textDecoration)||e.textDecoration,fontWeight:((ce=e.titleLabel)==null?void 0:ce.fontWeight)||e.calculative.fontWeight,fontFamily:((ue=e.titleLabel)==null?void 0:ue.fontFamily)||e.calculative.fontFamily,fontSize:(((N=e.titleLabel)==null?void 0:N.fontSize)||e.calculative.fontSize)*a,lineHeight:((F=e.titleLabel)==null?void 0:F.lineHeight)||e.calculative.lineHeight};r.font=wp(W),r.fillStyle=((X=e.titleLabel)==null?void 0:X.color)||d,e.isClock?r.fillText(("0"+parseInt(e.hourvalue)).slice(-2)+":"+("0"+parseInt(e.minutevalue)).slice(-2)+":"+("0"+parseInt(e.secondvalue)).slice(-2),c,u+l/2):r.fillText(h+" "+(e.unit||""),c,u+l/2),r.fill(),e.isClock&&(r.beginPath(),r.fillStyle=e.color||"#999999",r.strokeStyle="#ffffff",r.arc(c,u,l/20,0,Math.PI*2),r.stroke(),r.fill(),r.closePath())}function y_t(r){if(r.isClock)r.clockInterval=setInterval(()=>{let e=new Date,t=e.getSeconds(),i=e.getMinutes()+t/60,n=e.getHours()%12+i/60;r.calculative.canvas.parent.setValue({id:r.id,hourvalue:n,minutevalue:i,secondvalue:t},{render:!0,doEvent:!1})},1e3);else{const e=r.value;r.value=0,r.frames=[{duration:2e3,value:e}],r.calculative.canvas.parent.startAnimate(r.id),setTimeout(()=>{r.value=e},1e3)}}function x_t(r){r.clockInterval&&(clearInterval(r.clockInterval),r.clockInterval=void 0)}function b_t(r){r.isClock&&(r.onDestroy(r),r.onAdd(r))}function C_t(){return{lineChart:p_t,histogram:__t,pieChart:m_t,gauge:v_t}}function A_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/6,l=s/4;if(t.moveTo(i+l*2,n+0),t.lineTo(i+l*2,n+o),t.moveTo(i,n+o+l*2),t.arc(i+l*2,n+o+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(i+l*4,n+o*5),t.lineTo(i,n+o*5),t.lineTo(i,n+o+l*2),t.moveTo(i+l,n+o*5),t.lineTo(i+l,n+o*6),t.moveTo(i+l*2,n+o*5),t.lineTo(i+l*2,n+o*6),t.moveTo(i+l*3,n+o*5),t.lineTo(i+l*3,n+o*6),t.closePath(),t instanceof Path2D)return t}function TTe(r){const e=[{x:.5,y:0},{x:.25,y:1},{x:.5,y:1},{x:.75,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function S_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a-s,l=.5*s;if(t.moveTo(i+s/2,n),t.lineTo(i+s/2,n+o),t.moveTo(i+s,n+l+o),t.arc(i+s/2,n+l+o,l,0,Math.PI*2,!1),t.closePath(),t instanceof Path2D)return t}function MTe(r){const e=[{x:.5,y:0},{x:.5,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function E_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/2,l=s/5;if(t.moveTo(i,n+o),t.lineTo(i+l,n+o),t.moveTo(i+l*5,n+o),t.ellipse(i+l*3,n+o,2*l,o,0,0,Math.PI*2),t.closePath(),t instanceof Path2D)return t}function T_t(r){const e=[{x:.6,y:0},{x:1,y:.5},{x:.6,y:1},{x:0,y:.5}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function M_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/4,l=.5*s;if(t.moveTo(i+l,n),t.lineTo(i+l,n+o),t.moveTo(i,n+o),t.rect(i,n+o,l*2,o*2),t.moveTo(i+l,n+3*o),t.lineTo(i+l,n+4*o),t.closePath(),t instanceof Path2D)return t}function R_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/8,l=.25*s;if(t.moveTo(i+l*2,n),t.lineTo(i+l*2,n+o*2),t.lineTo(i+l*3,n+o*3),t.lineTo(i+l*3,n+o*5),t.lineTo(i+l*2,n+o*6),t.lineTo(i+l*1,n+o*5),t.lineTo(i+l*1,n+o*3),t.lineTo(i+l*2,n+o*2),t.moveTo(i+l*3,n+o*4),t.lineTo(i+l*4,n+o*4),t.moveTo(i+l*2,n+o*6),t.lineTo(i+l*2,n+o*8),t.closePath(),t instanceof Path2D)return t}function I_t(r){const e=[{x:.5,y:0},{x:1,y:.5},{x:.5,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function P_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=s/2,l=a/10;if(t.moveTo(i+o,n),t.lineTo(i+o,n+l),t.moveTo(i+o,n+l),t.quadraticCurveTo(i+o*2,n+l,i+o*2,n+l*9),t.moveTo(i+o,n+l),t.quadraticCurveTo(i,n+l,i,n+l*9),t.quadraticCurveTo(i+o,n+l*6,i+o*2,n+l*9),t.moveTo(i+o,n+a*3/4),t.lineTo(i+o,n+a),t.moveTo(i+o*2/5,n+a*201/250),t.lineTo(i+o*2/5,n+a),t.moveTo(i+o*8/5,n+a*201/250),t.lineTo(i+o*8/5,n+a),t.closePath(),t instanceof Path2D)return t}function RTe(r){const e=[{x:.5,y:0},{x:.2,y:1},{x:.5,y:1},{x:.8,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function w_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/6,l=s/4;if(t.moveTo(i+l*2,n+0),t.lineTo(i+l*2,n+o),t.moveTo(i,n+o+l*2),t.arc(i+l*2,n+o+l*2,l*2,Math.PI*1,Math.PI*2,!1),t.lineTo(i+l*4,n+o*5),t.lineTo(i,n+o*5),t.lineTo(i,n+o+l*2),t.moveTo(i,n+o*5-o/3),t.lineTo(i+l*4,n+o*5-o/3),t.moveTo(i+l,n+o*5),t.lineTo(i+l,n+o*6),t.moveTo(i+l*2,n+o*5),t.lineTo(i+l*2,n+o*6),t.moveTo(i+l*3,n+o*5),t.lineTo(i+l*3,n+o*6),t.closePath(),t instanceof Path2D)return t}function D_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/4,l=.5*s;if(t.moveTo(i+l,n),t.lineTo(i+l,n+o),t.lineTo(i+l*2,n+o*2),t.lineTo(i+l*2,n+o*4),t.lineTo(i,n+o*4),t.lineTo(i,n+o*2),t.lineTo(i+l,n+o),t.closePath(),t instanceof Path2D)return t}function O_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/4,l=s/2;if(t.moveTo(i+l,n),t.lineTo(i+l,n+o),t.lineTo(i+l*2,n+o*4),t.lineTo(i,n+o*4),t.lineTo(i+l,n+o),t.closePath(),t instanceof Path2D)return t}function L_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect,o=a/3,l=.5*s;if(t.moveTo(i+l,n),t.lineTo(i+l,n+o),t.lineTo(i+s,n+2*o),t.lineTo(i+l,n+a),t.lineTo(i,n+2*o),t.lineTo(i+l,n+o),t.closePath(),t instanceof Path2D)return t}function N_t(r){const e=[{x:.5,y:0},{x:1,y:.6666666666666666},{x:.5,y:1},{x:0,y:.6666666666666666}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function F_t(r,e){const t=e||new Path2D,{x:i,y:n,width:s,height:a}=r.calculative.worldRect;let o=s/2,l=a/10;if(t.moveTo(i+o,n),t.lineTo(i+o,n+l),t.moveTo(i+o,n+l),t.quadraticCurveTo(i+o*2,n+l,i+o*2,n+l*9),t.moveTo(i+o,n+l),t.quadraticCurveTo(i,n+l,i,n+l*9),t.quadraticCurveTo(i+o,n+l*6,i+o*2,n+l*9),t.moveTo(i,n+l*10),t.quadraticCurveTo(i+o,n+l*7,i+o*2,n+l*10),t.moveTo(i+o*2/5,n+a*201/250+l),t.lineTo(i+o*2/5,n+a),t.moveTo(i+o*8/5,n+a*201/250+l),t.lineTo(i+o*8/5,n+a),t.closePath(),t instanceof Path2D)return t}function B_t(r){const e=[{x:.5,y:0},{x:.2,y:1},{x:.8,y:1}];r.anchors=e.map(({x:t,y:i},n)=>({id:`${n}`,penId:r.id,x:t,y:i}))}function k_t(r,e){const{x:t,y:i,width:n,height:s}=e.calculative.worldRect,a=n/2,o=s/10;r.beginPath(),r.moveTo(t+a,i),r.lineTo(t+a,i+o),r.moveTo(t+a,i+o),r.quadraticCurveTo(t+a*2,i+o,t+a*2,i+o*9),r.moveTo(t+a,i+o),r.quadraticCurveTo(t,i+o,t,i+o*9),r.quadraticCurveTo(t+a,i+o*6,t+a*2,i+o*9),r.moveTo(t+a,i+s*3/4),r.lineTo(t+a,i+s*9/10),r.moveTo(t+a*2/5,i+s*201/250),r.lineTo(t+a*2/5,i+s*9/10),r.moveTo(t+a*8/5,i+s*201/250),r.lineTo(t+a*8/5,i+s*9/10),r.stroke(),r.closePath(),r.beginPath();const l=a*2>o*10?o:a/5;r.fillStyle="#333333",r.font=l+"px Arial",r.textBaseline="bottom",r.textAlign="center",r.fillText("o",t+a,i+s),r.fillText("m",t+a*2/5,i+s),r.fillText("o",t+a*8/5,i+s),r.closePath()}function U_t(){return{andGate:A_t,basicEvent:S_t,conditionalEvent:E_t,event:M_t,forbiddenGate:R_t,orGate:P_t,priorityAndGate:w_t,switchEvent:D_t,transferSymbol:O_t,unexpandedEvent:L_t,xorGate:F_t}}function z_t(){return{votingGate:k_t}}function V_t(){return{andGate:TTe,orGate:RTe,priorityAndGate:TTe,votingGate:RTe,xorGate:B_t,forbiddenGate:I_t,basicEvent:MTe,unexpandedEvent:N_t,conditionalEvent:T_t,transferSymbol:MTe}}var jFe={exports:{}},Sse={exports:{}};const G_t={},W_t=Object.freeze(Object.defineProperty({__proto__:null,default:G_t},Symbol.toStringTag,{value:"Module"})),$Fe=LNe(W_t);var ITe;function Ws(){return ITe||(ITe=1,function(r,e){(function(t,i){r.exports=i()})(Ri,function(){var t=t||function(i,n){var s;if(typeof window<"u"&&window.crypto&&(s=window.crypto),typeof self<"u"&&self.crypto&&(s=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(s=globalThis.crypto),!s&&typeof window<"u"&&window.msCrypto&&(s=window.msCrypto),!s&&typeof Ri<"u"&&Ri.crypto&&(s=Ri.crypto),!s&&typeof h_=="function")try{s=$Fe}catch{}var a=function(){if(s){if(typeof s.getRandomValues=="function")try{return s.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof s.randomBytes=="function")try{return s.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!=n?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,b=this.sigBytes,C=y.sigBytes;if(this.clamp(),b%4)for(var A=0;A>>2]>>>24-A%4*8&255;v[b+A>>>2]|=E<<24-(b+A)%4*8}else for(var P=0;P>>2]=x[P>>>2];return this.sigBytes+=C,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-C%4*8&255;b.push((A>>>4).toString(16)),b.push((A&15).toString(16))}return b.join("")},parse:function(y){for(var v=y.length,x=[],b=0;b>>3]|=parseInt(y.substr(b,2),16)<<24-b%8*4;return new h.init(x,v/2)}},p=d.Latin1={stringify:function(y){for(var v=y.words,x=y.sigBytes,b=[],C=0;C>>2]>>>24-C%4*8&255;b.push(String.fromCharCode(A))}return b.join("")},parse:function(y){for(var v=y.length,x=[],b=0;b>>2]|=(y.charCodeAt(b)&255)<<24-b%4*8;return new h.init(x,v)}},g=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)))}},m=c.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(y){typeof y=="string"&&(y=g.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes},_process:function(y){var v,x=this._data,b=x.words,C=x.sigBytes,A=this.blockSize,E=A*4,P=C/E;y?P=i.ceil(P):P=i.max((P|0)-this._minBufferSize,0);var w=P*A,M=i.min(w*4,C);if(w){for(var R=0;R>>2]|=l[h]<<24-h%4*8;a.call(this,u,c)}else a.apply(this,arguments)};o.prototype=s}}(),t.lib.WordArray})}(Tse)),Tse.exports}var Mse={exports:{}},DTe;function H_t(){return DTe||(DTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.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 s.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 s.create(u,c*2)}};function o(l){return l<<8&4278255360|l>>>8&16711935}}(),t.enc.Utf16})}(Mse)),Mse.exports}var Rse={exports:{}},OTe;function eT(){return OTe||(OTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.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,g=c[f+1>>>2]>>>24-(f+1)%4*8&255,m=c[f+2>>>2]>>>24-(f+2)%4*8&255,_=p<<16|g<<8|m,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,m=p|g;h[d>>>2]|=m<<24-d%4*8,d++}return s.create(h,d)}}(),t.enc.Base64})}(Rse)),Rse.exports}var Ise={exports:{}},LTe;function j_t(){return LTe||(LTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.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,m=u[p+1>>>2]>>>24-(p+1)%4*8&255,_=u[p+2>>>2]>>>24-(p+2)%4*8&255,y=g<<16|m<<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,m=p|g;h[d>>>2]|=m<<24-d%4*8,d++}return s.create(h,d)}}(),t.enc.Base64url})}(Ise)),Ise.exports}var Pse={exports:{}},NTe;function tT(){return NTe||(NTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(i){var n=t,s=n.lib,a=s.WordArray,o=s.Hasher,l=n.algo,c=[];(function(){for(var g=0;g<64;g++)c[g]=i.abs(i.sin(g+1))*4294967296|0})();var u=l.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(g,m){for(var _=0;_<16;_++){var y=m+_,v=g[y];g[y]=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360}var x=this._hash.words,b=g[m+0],C=g[m+1],A=g[m+2],E=g[m+3],P=g[m+4],w=g[m+5],M=g[m+6],R=g[m+7],I=g[m+8],D=g[m+9],k=g[m+10],z=g[m+11],W=g[m+12],K=g[m+13],U=g[m+14],j=g[m+15],B=x[0],G=x[1],Y=x[2],Z=x[3];B=h(B,G,Y,Z,b,7,c[0]),Z=h(Z,B,G,Y,C,12,c[1]),Y=h(Y,Z,B,G,A,17,c[2]),G=h(G,Y,Z,B,E,22,c[3]),B=h(B,G,Y,Z,P,7,c[4]),Z=h(Z,B,G,Y,w,12,c[5]),Y=h(Y,Z,B,G,M,17,c[6]),G=h(G,Y,Z,B,R,22,c[7]),B=h(B,G,Y,Z,I,7,c[8]),Z=h(Z,B,G,Y,D,12,c[9]),Y=h(Y,Z,B,G,k,17,c[10]),G=h(G,Y,Z,B,z,22,c[11]),B=h(B,G,Y,Z,W,7,c[12]),Z=h(Z,B,G,Y,K,12,c[13]),Y=h(Y,Z,B,G,U,17,c[14]),G=h(G,Y,Z,B,j,22,c[15]),B=d(B,G,Y,Z,C,5,c[16]),Z=d(Z,B,G,Y,M,9,c[17]),Y=d(Y,Z,B,G,z,14,c[18]),G=d(G,Y,Z,B,b,20,c[19]),B=d(B,G,Y,Z,w,5,c[20]),Z=d(Z,B,G,Y,k,9,c[21]),Y=d(Y,Z,B,G,j,14,c[22]),G=d(G,Y,Z,B,P,20,c[23]),B=d(B,G,Y,Z,D,5,c[24]),Z=d(Z,B,G,Y,U,9,c[25]),Y=d(Y,Z,B,G,E,14,c[26]),G=d(G,Y,Z,B,I,20,c[27]),B=d(B,G,Y,Z,K,5,c[28]),Z=d(Z,B,G,Y,A,9,c[29]),Y=d(Y,Z,B,G,R,14,c[30]),G=d(G,Y,Z,B,W,20,c[31]),B=f(B,G,Y,Z,w,4,c[32]),Z=f(Z,B,G,Y,I,11,c[33]),Y=f(Y,Z,B,G,z,16,c[34]),G=f(G,Y,Z,B,U,23,c[35]),B=f(B,G,Y,Z,C,4,c[36]),Z=f(Z,B,G,Y,P,11,c[37]),Y=f(Y,Z,B,G,R,16,c[38]),G=f(G,Y,Z,B,k,23,c[39]),B=f(B,G,Y,Z,K,4,c[40]),Z=f(Z,B,G,Y,b,11,c[41]),Y=f(Y,Z,B,G,E,16,c[42]),G=f(G,Y,Z,B,M,23,c[43]),B=f(B,G,Y,Z,D,4,c[44]),Z=f(Z,B,G,Y,W,11,c[45]),Y=f(Y,Z,B,G,j,16,c[46]),G=f(G,Y,Z,B,A,23,c[47]),B=p(B,G,Y,Z,b,6,c[48]),Z=p(Z,B,G,Y,R,10,c[49]),Y=p(Y,Z,B,G,U,15,c[50]),G=p(G,Y,Z,B,w,21,c[51]),B=p(B,G,Y,Z,W,6,c[52]),Z=p(Z,B,G,Y,E,10,c[53]),Y=p(Y,Z,B,G,k,15,c[54]),G=p(G,Y,Z,B,C,21,c[55]),B=p(B,G,Y,Z,I,6,c[56]),Z=p(Z,B,G,Y,j,10,c[57]),Y=p(Y,Z,B,G,M,15,c[58]),G=p(G,Y,Z,B,K,21,c[59]),B=p(B,G,Y,Z,P,6,c[60]),Z=p(Z,B,G,Y,z,10,c[61]),Y=p(Y,Z,B,G,A,15,c[62]),G=p(G,Y,Z,B,D,21,c[63]),x[0]=x[0]+B|0,x[1]=x[1]+G|0,x[2]=x[2]+Y|0,x[3]=x[3]+Z|0},_doFinalize:function(){var g=this._data,m=g.words,_=this._nDataBytes*8,y=g.sigBytes*8;m[y>>>5]|=128<<24-y%32;var v=i.floor(_/4294967296),x=_;m[(y+64>>>9<<4)+15]=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,m[(y+64>>>9<<4)+14]=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,g.sigBytes=(m.length+1)*4,this._process();for(var b=this._hash,C=b.words,A=0;A<4;A++){var E=C[A];C[A]=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360}return b},clone:function(){var g=o.clone.call(this);return g._hash=this._hash.clone(),g}});function h(g,m,_,y,v,x,b){var C=g+(m&_|~m&y)+v+b;return(C<>>32-x)+m}function d(g,m,_,y,v,x,b){var C=g+(m&y|_&~y)+v+b;return(C<>>32-x)+m}function f(g,m,_,y,v,x,b){var C=g+(m^_^y)+v+b;return(C<>>32-x)+m}function p(g,m,_,y,v,x,b){var C=g+(_^(m|~y))+v+b;return(C<>>32-x)+m}n.MD5=o._createHelper(u),n.HmacMD5=o._createHmacHelper(u)}(Math),t.MD5})}(Pse)),Pse.exports}var wse={exports:{}},FTe;function XFe(){return FTe||(FTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.WordArray,a=n.Hasher,o=i.algo,l=[],c=o.SHA1=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(u,h){for(var d=this._hash.words,f=d[0],p=d[1],g=d[2],m=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&g|~p&m)+1518500249:y<40?x+=(p^g^m)+1859775393:y<60?x+=(p&g|p&m|g&m)-1894007588:x+=(p^g^m)-899497514,_=m,m=g,g=p<<30|p>>>2,p=f,f=x}d[0]=d[0]+f|0,d[1]=d[1]+p|0,d[2]=d[2]+g|0,d[3]=d[3]+m|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})}(wse)),wse.exports}var Dse={exports:{}},BTe;function Kge(){return BTe||(BTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){return function(i){var n=t,s=n.lib,a=s.WordArray,o=s.Hasher,l=n.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 g=2,m=0;m<64;)f(g)&&(m<8&&(c[m]=p(i.pow(g,1/2))),u[m]=p(i.pow(g,1/3)),m++),g++})();var h=[],d=l.SHA256=o.extend({_doReset:function(){this._hash=new a.init(c.slice(0))},_doProcessBlock:function(f,p){for(var g=this._hash.words,m=g[0],_=g[1],y=g[2],v=g[3],x=g[4],b=g[5],C=g[6],A=g[7],E=0;E<64;E++){if(E<16)h[E]=f[p+E]|0;else{var P=h[E-15],w=(P<<25|P>>>7)^(P<<14|P>>>18)^P>>>3,M=h[E-2],R=(M<<15|M>>>17)^(M<<13|M>>>19)^M>>>10;h[E]=w+h[E-7]+R+h[E-16]}var I=x&b^~x&C,D=m&_^m&y^_&y,k=(m<<30|m>>>2)^(m<<19|m>>>13)^(m<<10|m>>>22),z=(x<<26|x>>>6)^(x<<21|x>>>11)^(x<<7|x>>>25),W=A+z+I+u[E]+h[E],K=k+D;A=C,C=b,b=x,x=v+W|0,v=y,y=_,_=m,m=W+K|0}g[0]=g[0]+m|0,g[1]=g[1]+_|0,g[2]=g[2]+y|0,g[3]=g[3]+v|0,g[4]=g[4]+x|0,g[5]=g[5]+b|0,g[6]=g[6]+C|0,g[7]=g[7]+A|0},_doFinalize:function(){var f=this._data,p=f.words,g=this._nDataBytes*8,m=f.sigBytes*8;return p[m>>>5]|=128<<24-m%32,p[(m+64>>>9<<4)+14]=i.floor(g/4294967296),p[(m+64>>>9<<4)+15]=g,f.sigBytes=p.length*4,this._process(),this._hash},clone:function(){var f=o.clone.call(this);return f._hash=this._hash.clone(),f}});n.SHA256=o._createHelper(d),n.HmacSHA256=o._createHmacHelper(d)}(Math),t.SHA256})}(Dse)),Dse.exports}var Ose={exports:{}},kTe;function $_t(){return kTe||(kTe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),Kge())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.WordArray,a=i.algo,o=a.SHA256,l=a.SHA224=o.extend({_doReset:function(){this._hash=new s.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})}(Ose)),Ose.exports}var Lse={exports:{}},UTe;function YFe(){return UTe||(UTe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),wJ())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.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=s.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,g){for(var m=this._hash.words,_=m[0],y=m[1],v=m[2],x=m[3],b=m[4],C=m[5],A=m[6],E=m[7],P=_.high,w=_.low,M=y.high,R=y.low,I=v.high,D=v.low,k=x.high,z=x.low,W=b.high,K=b.low,U=C.high,j=C.low,B=A.high,G=A.low,Y=E.high,Z=E.low,te=P,le=w,ce=M,ue=R,N=I,F=D,X=k,J=z,ae=W,ne=K,he=U,fe=j,ye=B,Se=G,De=Y,ze=Z,Le=0;Le<80;Le++){var Je,ke,We=d[Le];if(Le<16)ke=We.high=p[g+Le*2]|0,Je=We.low=p[g+Le*2+1]|0;else{var it=d[Le-15],_t=it.high,Dt=it.low,Qt=(_t>>>1|Dt<<31)^(_t>>>8|Dt<<24)^_t>>>7,qt=(Dt>>>1|_t<<31)^(Dt>>>8|_t<<24)^(Dt>>>7|_t<<25),wt=d[Le-2],zt=wt.high,Ot=wt.low,St=(zt>>>19|Ot<<13)^(zt<<3|Ot>>>29)^zt>>>6,Lt=(Ot>>>19|zt<<13)^(Ot<<3|zt>>>29)^(Ot>>>6|zt<<26),Bt=d[Le-7],Kt=Bt.high,ai=Bt.low,fi=d[Le-16],kt=fi.high,Ft=fi.low;Je=qt+ai,ke=Qt+Kt+(Je>>>0>>0?1:0),Je=Je+Lt,ke=ke+St+(Je>>>0>>0?1:0),Je=Je+Ft,ke=ke+kt+(Je>>>0>>0?1:0),We.high=ke,We.low=Je}var Ht=ae&he^~ae&ye,ni=ne&fe^~ne&Se,Di=te&ce^te&N^ce&N,mi=le&ue^le&F^ue&F,Ai=(te>>>28|le<<4)^(te<<30|le>>>2)^(te<<25|le>>>7),Ni=(le>>>28|te<<4)^(le<<30|te>>>2)^(le<<25|te>>>7),gi=(ae>>>14|ne<<18)^(ae>>>18|ne<<14)^(ae<<23|ne>>>9),rt=(ne>>>14|ae<<18)^(ne>>>18|ae<<14)^(ne<<23|ae>>>9),Ei=h[Le],Wi=Ei.high,Gt=Ei.low,At=ze+rt,Ze=De+gi+(At>>>0>>0?1:0),At=At+ni,Ze=Ze+Ht+(At>>>0>>0?1:0),At=At+Gt,Ze=Ze+Wi+(At>>>0>>0?1:0),At=At+Je,Ze=Ze+ke+(At>>>0>>0?1:0),Et=Ni+mi,Mt=Ai+Di+(Et>>>0>>0?1:0);De=ye,ze=Se,ye=he,Se=fe,he=ae,fe=ne,ne=J+At|0,ae=X+Ze+(ne>>>0>>0?1:0)|0,X=N,J=F,N=ce,F=ue,ce=te,ue=le,le=At+Et|0,te=Ze+Mt+(le>>>0>>0?1:0)|0}w=_.low=w+le,_.high=P+te+(w>>>0>>0?1:0),R=y.low=R+ue,y.high=M+ce+(R>>>0>>0?1:0),D=v.low=D+F,v.high=I+N+(D>>>0>>0?1:0),z=x.low=z+J,x.high=k+X+(z>>>0>>0?1:0),K=b.low=K+ne,b.high=W+ae+(K>>>0>>0?1:0),j=C.low=j+fe,C.high=U+he+(j>>>0>>0?1:0),G=A.low=G+Se,A.high=B+ye+(G>>>0>>0?1:0),Z=E.low=Z+ze,E.high=Y+De+(Z>>>0>>0?1:0)},_doFinalize:function(){var p=this._data,g=p.words,m=this._nDataBytes*8,_=p.sigBytes*8;g[_>>>5]|=128<<24-_%32,g[(_+128>>>10<<5)+30]=Math.floor(m/4294967296),g[(_+128>>>10<<5)+31]=m,p.sigBytes=g.length*4,this._process();var y=this._hash.toX32();return y},clone:function(){var p=s.clone.call(this);return p._hash=this._hash.clone(),p},blockSize:1024/32});i.SHA512=s._createHelper(f),i.HmacSHA512=s._createHmacHelper(f)}(),t.SHA512})}(Lse)),Lse.exports}var Nse={exports:{}},zTe;function X_t(){return zTe||(zTe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),wJ(),YFe())})(Ri,function(t){return function(){var i=t,n=i.x64,s=n.Word,a=n.WordArray,o=i.algo,l=o.SHA512,c=o.SHA384=l.extend({_doReset:function(){this._hash=new a.init([new s.init(3418070365,3238371032),new s.init(1654270250,914150663),new s.init(2438529370,812702999),new s.init(355462360,4144912697),new s.init(1731405415,4290775857),new s.init(2394180231,1750603025),new s.init(3675008525,1694076839),new s.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})}(Nse)),Nse.exports}var Fse={exports:{}},VTe;function Y_t(){return VTe||(VTe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),wJ())})(Ri,function(t){return function(i){var n=t,s=n.lib,a=s.WordArray,o=s.Hasher,l=n.x64,c=l.Word,u=n.algo,h=[],d=[],f=[];(function(){for(var m=1,_=0,y=0;y<24;y++){h[m+5*_]=(y+1)*(y+2)/2%64;var v=_%5,x=(2*m+3*_)%5;m=v,_=x}for(var m=0;m<5;m++)for(var _=0;_<5;_++)d[m+5*_]=_+(2*m+3*_)%5*5;for(var b=1,C=0;C<24;C++){for(var A=0,E=0,P=0;P<7;P++){if(b&1){var w=(1<>>24)&16711935|(b<<24|b>>>8)&4278255360,C=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360;var A=y[x];A.high^=C,A.low^=b}for(var E=0;E<24;E++){for(var P=0;P<5;P++){for(var w=0,M=0,R=0;R<5;R++){var A=y[P+5*R];w^=A.high,M^=A.low}var I=p[P];I.high=w,I.low=M}for(var P=0;P<5;P++)for(var D=p[(P+4)%5],k=p[(P+1)%5],z=k.high,W=k.low,w=D.high^(z<<1|W>>>31),M=D.low^(W<<1|z>>>31),R=0;R<5;R++){var A=y[P+5*R];A.high^=w,A.low^=M}for(var K=1;K<25;K++){var w,M,A=y[K],U=A.high,j=A.low,B=h[K];B<32?(w=U<>>32-B,M=j<>>32-B):(w=j<>>64-B,M=U<>>64-B);var G=p[d[K]];G.high=w,G.low=M}var Y=p[0],Z=y[0];Y.high=Z.high,Y.low=Z.low;for(var P=0;P<5;P++)for(var R=0;R<5;R++){var K=P+5*R,A=y[K],te=p[K],le=p[(P+1)%5+5*R],ce=p[(P+2)%5+5*R];A.high=te.high^~le.high&ce.high,A.low=te.low^~le.low&ce.low}var A=y[0],ue=f[E];A.high^=ue.high,A.low^=ue.low}},_doFinalize:function(){var m=this._data,_=m.words;this._nDataBytes*8;var y=m.sigBytes*8,v=this.blockSize*32;_[y>>>5]|=1<<24-y%32,_[(i.ceil((y+1)/v)*v>>>5)-1]|=128,m.sigBytes=_.length*4,this._process();for(var x=this._state,b=this.cfg.outputLength/8,C=b/8,A=[],E=0;E>>24)&16711935|(w<<24|w>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,A.push(M),A.push(w)}return new a.init(A,b)},clone:function(){for(var m=o.clone.call(this),_=m._state=this._state.slice(0),y=0;y<25;y++)_[y]=_[y].clone();return m}});n.SHA3=o._createHelper(g),n.HmacSHA3=o._createHmacHelper(g)}(Math),t.SHA3})}(Fse)),Fse.exports}var Bse={exports:{}},GTe;function Q_t(){return GTe||(GTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,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 n=t,s=n.lib,a=s.WordArray,o=s.Hasher,l=n.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]),g=l.RIPEMD160=o.extend({_doReset:function(){this._hash=a.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(C,A){for(var E=0;E<16;E++){var P=A+E,w=C[P];C[P]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var M=this._hash.words,R=f.words,I=p.words,D=c.words,k=u.words,z=h.words,W=d.words,K,U,j,B,G,Y,Z,te,le,ce;Y=K=M[0],Z=U=M[1],te=j=M[2],le=B=M[3],ce=G=M[4];for(var ue,E=0;E<80;E+=1)ue=K+C[A+D[E]]|0,E<16?ue+=m(U,j,B)+R[0]:E<32?ue+=_(U,j,B)+R[1]:E<48?ue+=y(U,j,B)+R[2]:E<64?ue+=v(U,j,B)+R[3]:ue+=x(U,j,B)+R[4],ue=ue|0,ue=b(ue,z[E]),ue=ue+G|0,K=G,G=B,B=b(j,10),j=U,U=ue,ue=Y+C[A+k[E]]|0,E<16?ue+=x(Z,te,le)+I[0]:E<32?ue+=v(Z,te,le)+I[1]:E<48?ue+=y(Z,te,le)+I[2]:E<64?ue+=_(Z,te,le)+I[3]:ue+=m(Z,te,le)+I[4],ue=ue|0,ue=b(ue,W[E]),ue=ue+ce|0,Y=ce,ce=le,le=b(te,10),te=Z,Z=ue;ue=M[1]+j+le|0,M[1]=M[2]+B+ce|0,M[2]=M[3]+G+Y|0,M[3]=M[4]+K+Z|0,M[4]=M[0]+U+te|0,M[0]=ue},_doFinalize:function(){var C=this._data,A=C.words,E=this._nDataBytes*8,P=C.sigBytes*8;A[P>>>5]|=128<<24-P%32,A[(P+64>>>9<<4)+14]=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360,C.sigBytes=(A.length+1)*4,this._process();for(var w=this._hash,M=w.words,R=0;R<5;R++){var I=M[R];M[R]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return w},clone:function(){var C=o.clone.call(this);return C._hash=this._hash.clone(),C}});function m(C,A,E){return C^A^E}function _(C,A,E){return C&A|~C&E}function y(C,A,E){return(C|~A)^E}function v(C,A,E){return C&E|A&~E}function x(C,A,E){return C^(A|~E)}function b(C,A){return C<>>32-A}n.RIPEMD160=o._createHelper(g),n.HmacRIPEMD160=o._createHmacHelper(g)}(),t.RIPEMD160})}(Bse)),Bse.exports}var kse={exports:{}},WTe;function Hge(){return WTe||(WTe=1,function(r,e){(function(t,i){r.exports=i(Ws())})(Ri,function(t){(function(){var i=t,n=i.lib,s=n.Base,a=i.enc,o=a.Utf8,l=i.algo;l.HMAC=s.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(),g=f.words,m=p.words,_=0;_>>2]&255;w.sigBytes-=M}};s.BlockCipher=f.extend({cfg:f.cfg.extend({mode:m,padding:y}),reset:function(){var w;f.reset.call(this);var M=this.cfg,R=M.iv,I=M.mode;this._xformMode==this._ENC_XFORM_MODE?w=I.createEncryptor:(w=I.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==w?this._mode.init(this,R&&R.words):(this._mode=w.call(I,this,R&&R.words),this._mode.__creator=w)},_doProcessBlock:function(w,M){this._mode.processBlock(w,M)},_doFinalize:function(){var w,M=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(M.pad(this._data,this.blockSize),w=this._process(!0)):(w=this._process(!0),M.unpad(w)),w},blockSize:128/32});var v=s.CipherParams=a.extend({init:function(w){this.mixIn(w)},toString:function(w){return(w||this.formatter).stringify(this)}}),x=n.format={},b=x.OpenSSL={stringify:function(w){var M,R=w.ciphertext,I=w.salt;return I?M=o.create([1398893684,1701076831]).concat(I).concat(R):M=R,M.toString(u)},parse:function(w){var M,R=u.parse(w),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})}},C=s.SerializableCipher=a.extend({cfg:a.extend({format:b}),encrypt:function(w,M,R,I){I=this.cfg.extend(I);var D=w.createEncryptor(R,I),k=D.finalize(M),z=D.cfg;return v.create({ciphertext:k,key:R,iv:z.iv,algorithm:w,mode:z.mode,padding:z.padding,blockSize:w.blockSize,formatter:I.format})},decrypt:function(w,M,R,I){I=this.cfg.extend(I),M=this._parse(M,I.format);var D=w.createDecryptor(R,I).finalize(M.ciphertext);return D},_parse:function(w,M){return typeof w=="string"?M.parse(w,this):w}}),A=n.kdf={},E=A.OpenSSL={execute:function(w,M,R,I,D){if(I||(I=o.random(64/8)),D)var k=d.create({keySize:M+R,hasher:D}).compute(w,I);else var k=d.create({keySize:M+R}).compute(w,I);var z=o.create(k.words.slice(M),R*4);return k.sigBytes=M*4,v.create({key:k,iv:z,salt:I})}},P=s.PasswordBasedCipher=C.extend({cfg:C.cfg.extend({kdf:E}),encrypt:function(w,M,R,I){I=this.cfg.extend(I);var D=I.kdf.execute(R,w.keySize,w.ivSize,I.salt,I.hasher);I.iv=D.iv;var k=C.encrypt.call(this,w,M,D.key,I);return k.mixIn(D),k},decrypt:function(w,M,R,I){I=this.cfg.extend(I),M=this._parse(M,I.format);var D=I.kdf.execute(R,w.keySize,w.ivSize,M.salt,I.hasher);I.iv=D.iv;var k=C.decrypt.call(this,w,M,D.key,I);return k}})}()})}(Vse)),Vse.exports}var Gse={exports:{}},$Te;function q_t(){return $Te||($Te=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return t.mode.CFB=function(){var i=t.lib.BlockCipherMode.extend();i.Encryptor=i.extend({processBlock:function(s,a){var o=this._cipher,l=o.blockSize;n.call(this,s,a,l,o),this._prevBlock=s.slice(a,a+l)}}),i.Decryptor=i.extend({processBlock:function(s,a){var o=this._cipher,l=o.blockSize,c=s.slice(a,a+l);n.call(this,s,a,l,o),this._prevBlock=c}});function n(s,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 s(o){return(o[0]=n(o[0]))===0&&(o[1]=n(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),s(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 n=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=n}},t.pad.Ansix923})}($se)),$se.exports}var Xse={exports:{}},JTe;function n2t(){return JTe||(JTe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return t.pad.Iso10126={pad:function(i,n){var s=n*4,a=s-i.sigBytes%s;i.concat(t.lib.WordArray.random(a-1)).concat(t.lib.WordArray.create([a<<24],1))},unpad:function(i){var n=i.words[i.sigBytes-1>>>2]&255;i.sigBytes-=n}},t.pad.Iso10126})}(Xse)),Xse.exports}var Yse={exports:{}},eMe;function s2t(){return eMe||(eMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return t.pad.Iso97971={pad:function(i,n){i.concat(t.lib.WordArray.create([2147483648],1)),t.pad.ZeroPadding.pad(i,n)},unpad:function(i){t.pad.ZeroPadding.unpad(i),i.sigBytes--}},t.pad.Iso97971})}(Yse)),Yse.exports}var Qse={exports:{}},tMe;function a2t(){return tMe||(tMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return t.pad.ZeroPadding={pad:function(i,n){var s=n*4;i.clamp(),i.sigBytes+=s-(i.sigBytes%s||s)},unpad:function(i){for(var n=i.words,s=i.sigBytes-1,s=i.sigBytes-1;s>=0;s--)if(n[s>>>2]>>>24-s%4*8&255){i.sigBytes=s+1;break}}},t.pad.ZeroPadding})}(Qse)),Qse.exports}var Zse={exports:{}},iMe;function o2t(){return iMe||(iMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return t.pad.NoPadding={pad:function(){},unpad:function(){}},t.pad.NoPadding})}(Zse)),Zse.exports}var qse={exports:{}},rMe;function l2t(){return rMe||(rMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),ju())})(Ri,function(t){return function(i){var n=t,s=n.lib,a=s.CipherParams,o=n.enc,l=o.Hex,c=n.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})}(qse)),qse.exports}var Jse={exports:{}},nMe;function c2t(){return nMe||(nMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.BlockCipher,a=i.algo,o=[],l=[],c=[],u=[],h=[],d=[],f=[],p=[],g=[],m=[];(function(){for(var v=[],x=0;x<256;x++)x<128?v[x]=x<<1:v[x]=x<<1^283;for(var b=0,C=0,x=0;x<256;x++){var A=C^C<<1^C<<2^C<<3^C<<4;A=A>>>8^A&255^99,o[b]=A,l[A]=b;var E=v[b],P=v[E],w=v[P],M=v[A]*257^A*16843008;c[b]=M<<24|M>>>8,u[b]=M<<16|M>>>16,h[b]=M<<8|M>>>24,d[b]=M;var M=w*16843009^P*65537^E*257^b*16843008;f[A]=M<<24|M>>>8,p[A]=M<<16|M>>>16,g[A]=M<<8|M>>>24,m[A]=M,b?(b=E^v[v[v[w^E]]],C^=v[v[C]]):b=C=1}})();var _=[0,1,2,4,8,16,32,64,128,27,54],y=a.AES=s.extend({_doReset:function(){var v;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var x=this._keyPriorReset=this._key,b=x.words,C=x.sigBytes/4,A=this._nRounds=C+6,E=(A+1)*4,P=this._keySchedule=[],w=0;w6&&w%C==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^=_[w/C|0]<<24),P[w]=P[w-C]^v);for(var M=this._invKeySchedule=[],R=0;R>>24]]^p[o[v>>>16&255]]^g[o[v>>>8&255]]^m[o[v&255]]}}},encryptBlock:function(v,x){this._doCryptBlock(v,x,this._keySchedule,c,u,h,d,o)},decryptBlock:function(v,x){var b=v[x+1];v[x+1]=v[x+3],v[x+3]=b,this._doCryptBlock(v,x,this._invKeySchedule,f,p,g,m,l);var b=v[x+1];v[x+1]=v[x+3],v[x+3]=b},_doCryptBlock:function(v,x,b,C,A,E,P,w){for(var M=this._nRounds,R=v[x]^b[0],I=v[x+1]^b[1],D=v[x+2]^b[2],k=v[x+3]^b[3],z=4,W=1;W>>24]^A[I>>>16&255]^E[D>>>8&255]^P[k&255]^b[z++],U=C[I>>>24]^A[D>>>16&255]^E[k>>>8&255]^P[R&255]^b[z++],j=C[D>>>24]^A[k>>>16&255]^E[R>>>8&255]^P[I&255]^b[z++],B=C[k>>>24]^A[R>>>16&255]^E[I>>>8&255]^P[D&255]^b[z++];R=K,I=U,D=j,k=B}var K=(w[R>>>24]<<24|w[I>>>16&255]<<16|w[D>>>8&255]<<8|w[k&255])^b[z++],U=(w[I>>>24]<<24|w[D>>>16&255]<<16|w[k>>>8&255]<<8|w[R&255])^b[z++],j=(w[D>>>24]<<24|w[k>>>16&255]<<16|w[R>>>8&255]<<8|w[I&255])^b[z++],B=(w[k>>>24]<<24|w[R>>>16&255]<<16|w[I>>>8&255]<<8|w[D&255])^b[z++];v[x]=K,v[x+1]=U,v[x+2]=j,v[x+3]=B},keySize:256/32});i.AES=s._createHelper(y)}(),t.AES})}(Jse)),Jse.exports}var eae={exports:{}},sMe;function u2t(){return sMe||(sMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.WordArray,a=n.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 b=l[x]-1;v[x]=y[b>>>5]>>>31-b%32&1}for(var C=this._subKeys=[],A=0;A<16;A++){for(var E=C[A]=[],P=u[A],x=0;x<24;x++)E[x/6|0]|=v[(c[x]-1+P)%28]<<31-x%6,E[4+(x/6|0)]|=v[28+(c[x+24]-1+P)%28]<<31-x%6;E[0]=E[0]<<1|E[0]>>>31;for(var x=1;x<7;x++)E[x]=E[x]>>>(x-1)*4+3;E[7]=E[7]<<5|E[7]>>>27}for(var w=this._invSubKeys=[],x=0;x<16;x++)w[x]=C[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),g.call(this,2,858993459),g.call(this,8,16711935),p.call(this,1,1431655765);for(var x=0;x<16;x++){for(var b=v[x],C=this._lBlock,A=this._rBlock,E=0,P=0;P<8;P++)E|=h[P][((A^b[P])&d[P])>>>0];this._lBlock=A,this._rBlock=C^E}var w=this._lBlock;this._lBlock=this._rBlock,this._rBlock=w,p.call(this,1,1431655765),g.call(this,8,16711935),g.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 g(_,y){var v=(this._rBlock>>>_^this._lBlock)&y;this._lBlock^=v,this._rBlock^=v<<_}i.DES=a._createHelper(f);var m=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),b=y.length<6?y.slice(0,2):y.slice(4,6);this._des1=f.createEncryptor(s.create(v)),this._des2=f.createEncryptor(s.create(x)),this._des3=f.createEncryptor(s.create(b))},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(m)}(),t.TripleDES})}(eae)),eae.exports}var tae={exports:{}},aMe;function h2t(){return aMe||(aMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.StreamCipher,a=i.algo,o=a.RC4=s.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,g=0;p<256;p++){var m=p%d,_=h[m>>>2]>>>24-m%4*8&255;g=(g+f[p]+_)%256;var y=f[p];f[p]=f[g],f[g]=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 g=u[h];u[h]=u[d],u[d]=g,f|=u[(u[h]+u[d])%256]<<24-p*8}return this._i=h,this._j=d,f}i.RC4=s._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=s._createHelper(c)}(),t.RC4})}(tae)),tae.exports}var iae={exports:{}},oMe;function d2t(){return oMe||(oMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.StreamCipher,a=i.algo,o=[],l=[],c=[],u=a.Rabbit=s.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 g=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 p=0;p<4;p++)h.call(this);for(var p=0;p<8;p++)m[p]^=g[p+4&7];if(f){var _=f.words,y=_[0],v=_[1],x=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,b=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,C=x>>>16|b&4294901760,A=b<<16|x&65535;m[0]^=x,m[1]^=C,m[2]^=b,m[3]^=A,m[4]^=x,m[5]^=C,m[6]^=b,m[7]^=A;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 g=0;g<4;g++)o[g]=(o[g]<<8|o[g]>>>24)&16711935|(o[g]<<24|o[g]>>>8)&4278255360,d[f+g]^=o[g]},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 g=d[p]+f[p],m=g&65535,_=g>>>16,y=((m*m>>>17)+m*_>>>15)+_*_,v=((g&4294901760)*g|0)+((g&65535)*g|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=s._createHelper(u)}(),t.Rabbit})}(iae)),iae.exports}var rae={exports:{}},lMe;function f2t(){return lMe||(lMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.StreamCipher,a=i.algo,o=[],l=[],c=[],u=a.RabbitLegacy=s.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],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 m=0;m<4;m++)h.call(this);for(var m=0;m<8;m++)g[m]^=p[m+4&7];if(f){var _=f.words,y=_[0],v=_[1],x=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,b=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,C=x>>>16|b&4294901760,A=b<<16|x&65535;g[0]^=x,g[1]^=C,g[2]^=b,g[3]^=A,g[4]^=x,g[5]^=C,g[6]^=b,g[7]^=A;for(var m=0;m<4;m++)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 g=0;g<4;g++)o[g]=(o[g]<<8|o[g]>>>24)&16711935|(o[g]<<24|o[g]>>>8)&4278255360,d[f+g]^=o[g]},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 g=d[p]+f[p],m=g&65535,_=g>>>16,y=((m*m>>>17)+m*_>>>15)+_*_,v=((g&4294901760)*g|0)+((g&65535)*g|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=s._createHelper(u)}(),t.RabbitLegacy})}(rae)),rae.exports}var nae={exports:{}},cMe;function p2t(){return cMe||(cMe=1,function(r,e){(function(t,i,n){r.exports=i(Ws(),eT(),tT(),Jx(),ju())})(Ri,function(t){return function(){var i=t,n=i.lib,s=n.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(m,_){let y=_>>24&255,v=_>>16&255,x=_>>8&255,b=_&255,C=m.sbox[0][y]+m.sbox[1][v];return C=C^m.sbox[2][x],C=C+m.sbox[3][b],C}function d(m,_,y){let v=_,x=y,b;for(let C=0;C1;--C)v=v^m.pbox[C],x=h(m,v)^x,b=v,v=x,x=b;return b=v,v=x,x=b,x=x^m.pbox[1],v=v^m.pbox[0],{left:v,right:x}}function p(m,_,y){for(let A=0;A<4;A++){m.sbox[A]=[];for(let E=0;E<256;E++)m.sbox[A][E]=c[A][E]}let v=0;for(let A=0;A=y&&(v=0);let x=0,b=0,C=0;for(let A=0;A{window.meta2d&&window.meta2d.render()}),document.head.appendChild(i)}var hMe=performance.now();function PA(r){let e="/view/";e==="/"&&(e=""),location.host.indexOf(".le5le.")===-1&&(e=".",location.pathname.indexOf("/view")!==-1&&(e="/view"));const i=document.createElement("script");i.type="text/javascript",i.defer=!0,i.src=e+r+"?r="+new Date().getTime(),i.addEventListener("load",()=>{const n=performance.now();(n>hMe+500||n>33)&&(window.meta2d&&window.meta2d.render(),hMe=n)}),document.body.appendChild(i)}function _2t(r){const e="blrtP0ilBMMMYtAt",t=MI.enc.Utf8.parse(e);return MI.AES.decrypt(r,MI.enc.Utf8.parse(e),{iv:t,mode:MI.mode.CBC,padding:MI.pad.Pkcs7}).toString(MI.enc.Utf8)}function D0(r,e){return e=e||window.location.search,new URLSearchParams(e).get(r)}function v2t(){let r="/view/";r==="/"&&(r=""),location.host.indexOf(".le5le.")===-1&&(r=".",location.pathname.indexOf("/view")!==-1&&(r="/view"));try{fetch(r+"/theme/dark.json").then(t=>t.json()).then(t=>{echarts.registerTheme("le-dark",t)}),fetch(r+"/theme/light.json").then(t=>t.json()).then(t=>{echarts.registerTheme("le-light",t)})}catch(t){console.warn(t)}}function y2t(r){const e=D0("token")||QFe("token")||"";e&&r.pens.forEach(t=>{t.name=="iframe"&&t.iframe.includes("le5le.com")&&(t.iframe+="&token="+e)})}function ZFe(r,e){const t=new Tgt("app");x2t(),uMe("/css/t/font_2395018_nng9x1qhat.css"),uMe("/css/t/font_2073009_teagntehxt.css"),PA("/js/r.js"),setTimeout(()=>{if(location.host.indexOf(".le5le.com")===-1)PA("/js/1.js"),setTimeout(async()=>{let o=".";location.pathname.indexOf("/view")!==-1&&(o="/view"),window.registerIot(window.enterpriseId||window.userId,`${o}/js/2d-components.js`),window.meta2dTools&®isterToolsNew&®isterToolsNew(),t.render()},1e3);else{for(let o=1;o<10;o++)PA("/js/"+o+".js");for(let o=97;o<110;o++)PA("/js/"+String.fromCharCode(o)+".js");PA("/js/2d-components.js")}const a=["/js/marked.min.js","/js/echarts.min.js","/js/highcharts.js","/js/lcjs.iife.js"];for(let o=0;o{PA("/js/highcharts-more.js")},1e3);const i=setInterval(()=>{!window.meta2dTools||window.meta2dTools.length<1450||registerToolsNew&&(registerToolsNew(),clearInterval(i))},200),n=setInterval(()=>{globalThis.echarts&&(v2t(),clearInterval(n))},200);r.locked=1,window.userId=r.userId,setTimeout(()=>{var l,c,u;y2t(r),t.open(r);const s=document.getElementById("lock");let a=null,o=null;if(s){a=s.querySelector(".locked"),o=s.querySelector(".unlock");let h=D0("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=D0("showLock");d&&d.endsWith("#")&&(d=d.slice(0,-1)),d==1&&(s.style.display="block",s.addEventListener("click",()=>{a.style.display==="block"?(t.setOptions({disableScale:!1,disableTranslate:!1}),a.style.display="none",o.style.display="block",cp("已解锁,可以拖动和缩放画布",2e3,"success")):(t.setOptions({disableScale:!0,disableTranslate:!0}),a.style.display="block",o.style.display="none",cp("已锁定,无法拖动和缩放画布",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,0)},1e3),setTimeout(()=>{t.fitView(!0,0)},5e3)}function x2t(){Q1(Wgt()),gue(Kgt()),Q1(Xgt()),mP(Ygt()),Q1(i1t()),Q1(s1t()),mP(a1t()),T1t(),M1t(),R1t(),mP(c_t()),Q1(u_t()),mP(C_t()),Q1(U_t()),mP(z_t()),gue(V_t())}const cZ={};function xe(r,e){cZ[r]=e}function Sa(r){return cZ[r]}function b2t(r){for(const e in cZ)if(r instanceof cZ[e]&&!e.includes("Abstract"))return e;return"Unknown"}class vo{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,n){for(const s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,n)}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}}vo._BabylonFileParsers={};vo._IndividualBabylonFileParsers={};xe("BABYLON.AbstractScene",vo);class Rd{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in Rd.Triggers)if(Object.prototype.hasOwnProperty.call(Rd.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Rd.Triggers)if(Object.prototype.hasOwnProperty.call(Rd.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Rd.Triggers)if(Object.prototype.hasOwnProperty.call(Rd.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Rd.Triggers={};class jge{constructor(e,t=!1,i,n){this.initialize(e,t,i,n)}initialize(e,t=!1,i,n){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=n,this}}class qFe{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 Ce{static FromPromise(e,t){const i=new Ce;return e.then(n=>{i.notifyObservers(n)}).catch(n=>{if(t)t.notifyObservers(n);else throw n}),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 jge(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,n=null,s=!1){if(!e)return null;const a=new qFe(e,t,n);return a.unregisterOnNextCall=s,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,n,s){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=n,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s;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 n=this._eventState;n.mask=i,n.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,n)}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 Ce;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 e5=1/2.2,$9=2.2,cl=(1+Math.sqrt(5))/2,Ki=.001;function Qh(r,e){const t=[];for(let i=0;i{const s=n.previous;if(!s)return;const a=n.next;a?(s.next=a,a.previous=s):(s.next=void 0,r[e]=s),n.next=void 0,n.previous=void 0}}const A2t=["push","splice","pop","shift","unshift"];function JFe(r,e){const t=A2t.map(i=>C2t(r,i,e));return()=>{t.forEach(i=>{i==null||i()})}}class jl{static SetMatrixPrecision(e){if(jl.MatrixTrackPrecisionChange=!1,e&&!jl.MatrixUse64Bits&&jl.MatrixTrackedMatrices)for(let t=0;tparseInt(r.toString().replace(/\W/g,""));class Ne{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=Pd(this.x),t=Pd(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 Ne.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 Ne(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 Ne(this.x+e.x,this.y+e.y)}subtract(e){return new Ne(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 Ne(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 Ne(this.x*e,this.y*t)}divide(e){return new Ne(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 Ne(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 Ne(-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 Ne(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=Ki){return e&&mu(this.x,e.x,t)&&mu(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new Ne(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 Ne(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),n=Math.sin(e),s=i*this.x-n*this.y,a=n*this.x+i*this.y;return t.x=s,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 Ne;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 Ne(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new Ne(0,0)}static One(){return new Ne(1,1)}static Random(e=0,t=1){return new Ne(Qn(e,t),Qn(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Qn(e,t),Qn(e,t))}static get ZeroReadOnly(){return Ne._ZeroReadOnly}static FromArray(e,t=0){return new Ne(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,n,s){const a=s*s,o=s*a,l=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-n.x)*a+(-e.x+3*t.x-3*i.x+n.x)*o),c=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-n.y)*a+(-e.y+3*t.y-3*i.y+n.y)*o);return new Ne(l,c)}static ClampToRef(e,t,i,n){return n.x=za(e.x,t.x,i.x),n.y=za(e.y,t.y,i.y),n}static Clamp(e,t,i){const n=za(e.x,t.x,i.x),s=za(e.y,t.y,i.y);return new Ne(n,s)}static Hermite(e,t,i,n,s){const a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+s,h=o-a,d=e.x*l+i.x*c+t.x*u+n.x*h,f=e.y*l+i.y*c+t.y*u+n.y*h;return new Ne(d,f)}static Hermite1stDerivative(e,t,i,n,s){return this.Hermite1stDerivativeToRef(e,t,i,n,s,new Ne)}static Hermite1stDerivativeToRef(e,t,i,n,s,a){const o=s*s;return a.x=(o-s)*6*e.x+(3*o-4*s+1)*t.x+(-o+s)*6*i.x+(3*o-2*s)*n.x,a.y=(o-s)*6*e.y+(3*o-4*s+1)*t.y+(-o+s)*6*i.y+(3*o-2*s)*n.y,a}static Lerp(e,t,i){return Ne.LerpToRef(e,t,i,new Ne)}static LerpToRef(e,t,i,n){return n.x=e.x+(t.x-e.x)*i,n.y=e.y+(t.y-e.y)*i,n}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return Ne.NormalizeToRef(e,new Ne)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,n=e.y>t.y?e.y:t.y;return new Ne(i,n)}static Transform(e,t){return Ne.TransformToRef(e,t,new Ne)}static TransformToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+n[12],a=e.x*n[1]+e.y*n[5]+n[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,n){const s=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),a=s<0?-1:1,o=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.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*s*a}static Distance(e,t){return Math.sqrt(Ne.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y;return i*i+n*n}static Center(e,t){return Ne.CenterToRef(e,t,new Ne)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const n=Ne.DistanceSquared(t,i);if(n===0)return Ne.Distance(e,t);const s=i.subtract(t),a=Math.max(0,Math.min(1,Ne.Dot(e.subtract(t),s)/n)),o=t.add(s.multiplyByFloats(a,a));return Ne.Distance(e,o)}}Ne._ZeroReadOnly=Ne.Zero();Object.defineProperties(Ne.prototype,{dimension:{value:[2]},rank:{value:1}});class O{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=Pd(this._x),t=Pd(this._y),i=Pd(this._z);let n=e;return n=n*397^t,n=n*397^i,n}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 O.FromArrayToRef(e,t,this),this}toQuaternion(){return Oe.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 O(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 O(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 O(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._isDirty=!0,n}negate(){return new O(-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 O(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 n=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(n),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(n);return e.set(s,a,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,n=this._y,s=this._z,a=e._x,o=e._y,l=e._z,c=e._w,u=2*(o*s-l*n),h=2*(l*i-a*s),d=2*(a*n-o*i);return t._x=i+c*u+o*d-l*h,t._y=n+c*h+l*u-a*d,t._z=s+c*d+a*h-o*u,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new O)}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 O)}projectOnPlaneToRef(e,t,i){const n=e.normal,s=e.d,a=wi.Vector3[0];this.subtractToRef(t,a),a.normalize();const o=O.Dot(a,n);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const l=-(O.Dot(t,n)+s)/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=Ki){return e&&mu(this._x,e._x,t)&&mu(this._y,e._y,t)&&mu(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 O(this._x*e,this._y*t,this._z*i)}divide(e){return new O(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(!mu(t,i,e))return!0;const n=Math.abs(this._z);return!mu(t,n,e)||!mu(i,n,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 O(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 O(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=wi.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(wi.Matrix[0]),O.TransformCoordinatesToRef(this,wi.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,wi.Vector3[0]),wi.Vector3[0].rotateByQuaternionToRef(e,wi.Vector3[0]),t.addToRef(wi.Vector3[0],i),i}cross(e){return O.CrossToRef(this,e,new O)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new O)}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 O(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,n){const s=O.Dot(e,i),a=O.Dot(t,i);return(s-n)/(s-a)}static GetAngleBetweenVectors(e,t,i){const n=e.normalizeToRef(wi.Vector3[1]),s=t.normalizeToRef(wi.Vector3[2]);let a=O.Dot(n,s);a=za(a,-1,1);const o=Math.acos(a),l=wi.Vector3[3];return O.CrossToRef(n,s,l),O.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){wi.Vector3[0].copyFrom(e);const n=wi.Vector3[0];wi.Vector3[1].copyFrom(t);const s=wi.Vector3[1];wi.Vector3[2].copyFrom(i);const a=wi.Vector3[2],o=wi.Vector3[3],l=wi.Vector3[4];n.normalize(),s.normalize(),a.normalize(),O.CrossToRef(a,n,o),O.CrossToRef(o,a,l);const c=Math.atan2(O.Dot(s,o),O.Dot(s,l));return eBe(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const n=oe.Vector3[0];return t.subtractToRef(e,n),i._y=Math.atan2(n.x,n.z)||0,i._x=Math.atan2(Math.sqrt(n.x**2+n.z**2),n.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=O.Zero();return O.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,n){i=za(i,0,1);const s=wi.Vector3[0],a=wi.Vector3[1];s.copyFrom(e);const o=s.length();s.normalizeFromLength(o),a.copyFrom(t);const l=a.length();a.normalizeFromLength(l);const c=O.Dot(s,a);let u,h;if(c<1-Ki){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 s.scaleInPlace(u),a.scaleInPlace(h),n.copyFrom(s).addInPlace(a),n.scaleInPlace(ef(o,l,i)),n}static SmoothToRef(e,t,i,n,s){return O.SlerpToRef(e,t,n===0?1:i/n,s),s}static FromArray(e,t=0){return new O(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return O.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 O.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,n){return n.copyFromFloats(e,t,i),n}static Zero(){return new O(0,0,0)}static One(){return new O(1,1,1)}static Up(){return new O(0,1,0)}static get UpReadOnly(){return O._UpReadOnly}static get DownReadOnly(){return O._DownReadOnly}static get RightReadOnly(){return O._RightReadOnly}static get LeftReadOnly(){return O._LeftReadOnly}static get LeftHandedForwardReadOnly(){return O._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return O._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return O._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return O._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return O._ZeroReadOnly}static get OneReadOnly(){return O._OneReadOnly}static Down(){return new O(0,-1,0)}static Forward(e=!1){return new O(0,0,e?-1:1)}static Backward(e=!1){return new O(0,0,e?1:-1)}static Right(){return new O(1,0,0)}static Left(){return new O(-1,0,0)}static Random(e=0,t=1){return new O(Qn(e,t),Qn(e,t),Qn(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Qn(e,t),Qn(e,t),Qn(e,t))}static TransformCoordinates(e,t){const i=O.Zero();return O.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return O.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const a=n.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 s._x=o*u,s._y=l*u,s._z=c*u,s._isDirty=!0,s}static TransformNormal(e,t){const i=O.Zero();return O.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,n,s){const a=n.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,n,s){const a=s*s,o=s*a,l=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-n._x)*a+(-e._x+3*t._x-3*i._x+n._x)*o),c=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-n._y)*a+(-e._y+3*t._y-3*i._y+n._y)*o),u=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-n._z)*a+(-e._z+3*t._z-3*i._z+n._z)*o);return new O(l,c,u)}static Clamp(e,t,i){const n=new O;return O.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:a,a=ai._z?i._z:o,o=o0&&w<0?(R.copyFrom(a),I=t,D=i):w>0&&M<0?(R.copyFrom(l),I=i,D=n):(R.copyFrom(o).scaleInPlace(-1),I=n,D=t);const k=wi.Vector3[9],z=wi.Vector3[4];if(I.subtractToRef(y,C),D.subtractToRef(y,k),O.CrossToRef(C,k,z),!(O.Dot(z,c)<0))return s.copyFrom(y),Math.abs(g*m);const K=wi.Vector3[5];O.CrossToRef(R,z,K),K.normalize();const U=wi.Vector3[9];U.copyFrom(I).subtractInPlace(y);const j=U.length();if(jthis.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,n){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(n,this.w),this}maximizeInPlaceFromFloats(e,t,i,n){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(n,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 It(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 It(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 It)}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 O(this.x,this.y,this.z)}clone(){return new It(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,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}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 It(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 It.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,n,s){return s.x=e,s.y=t,s.z=i,s.w=n,s}static Zero(){return new It(0,0,0,0)}static One(){return new It(1,1,1,1)}static Random(e=0,t=1){return new It(Qn(e,t),Qn(e,t),Qn(e,t),Qn(e,t))}static RandomToRef(e=0,t=1,i){return i.x=Qn(e,t),i.y=Qn(e,t),i.z=Qn(e,t),i.w=Qn(e,t),i}static Clamp(e,t,i){return It.ClampToRef(e,t,i,new It)}static ClampToRef(e,t,i,n){return n.x=za(e.x,t.x,i.x),n.y=za(e.y,t.y,i.y),n.z=za(e.z,t.z,i.z),n.w=za(e.w,t.w,i.w),n}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return It._ZeroReadOnly}static Normalize(e){return It.NormalizeToRef(e,new It)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new It;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new It;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(It.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+n*n+s*s+a*a}static Center(e,t){return It.CenterToRef(e,t,new It)}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 It.TransformCoordinatesToRef(e,t,new It)}static TransformCoordinatesToRef(e,t,i){return It.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,n,s){const a=n.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 s.x=o,s.y=l,s.z=c,s.w=u,s}static TransformNormal(e,t){return It.TransformNormalToRef(e,t,new It)}static TransformNormalToRef(e,t,i){const n=t.m,s=e.x*n[0]+e.y*n[4]+e.z*n[8],a=e.x*n[1]+e.y*n[5]+e.z*n[9],o=e.x*n[2]+e.y*n[6]+e.z*n[10];return i.x=s,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,n,s,a){const o=s.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=n,a}static FromVector3(e,t=0){return new It(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}}It._ZeroReadOnly=It.Zero();Object.defineProperties(It.prototype,{dimension:{value:[4]},rank:{value:1}});class Oe{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,n=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=n}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=Pd(this._x),t=Pd(this._y),i=Pd(this._z),n=Pd(this._w);let s=e;return s=s*397^t,s=s*397^i,s=s*397^n,s}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 Oe.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=Ki){return e&&mu(this._x,e._x,t)&&mu(this._y,e._y,t)&&mu(this._z,e._z,t)&&mu(this._w,e._w,t)}clone(){return new Oe(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,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._isDirty=!0,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new Oe(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,n){return this._x+=e,this._y+=t,this._z+=i,this._w+=n,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,n){return this.subtractFromFloatsToRef(e,t,i,n,new Oe)}subtractFromFloatsToRef(e,t,i,n,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-n,s._isDirty=!0,s}subtract(e){return new Oe(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 Oe(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 Oe(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,n=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=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,n,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,n){return this._x*=e,this._y*=t,this._z*=i,this._w*=n,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 Oe)}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,n){return this._x===e&&this._y===t&&this._z===i&&this._w===n}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 Oe(-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 Oe(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=O.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,n=this._y,s=this._w,a=n*t-i*s,o=.4999999;if(a<-o)e._y=2*Math.atan2(n,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(n,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=s*s,c=t*t,u=i*i,h=n*n;e._z=Math.atan2(2*(i*n+t*s),-c-u+h+l),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+n*s),c-u-h+l),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,n=this._y,s=this._w,a=Math.sqrt(i*i+n*n),o=Math.sqrt(t*t+s*s),l=2*Math.atan2(a,o),c=2*Math.atan2(t,s),u=2*Math.atan2(n,i),h=(c+u)/2,d=(c-u)/2;return e.set(d,l,h),e}toRotationMatrix(e){return pe.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return Oe.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 Oe;return Oe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,n=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],u=i[2],h=i[6],d=i[10],f=n+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-s)*p,t._isDirty=!0):n>l&&n>d?(p=2*Math.sqrt(1+n-l-d),t._w=(h-c)/p,t._x=.25*p,t._y=(s+o)/p,t._z=(a+u)/p,t._isDirty=!0):l>d?(p=2*Math.sqrt(1+l-n-d),t._w=(a-u)/p,t._x=(s+o)/p,t._y=.25*p,t._z=(c+h)/p,t._isDirty=!0):(p=2*Math.sqrt(1+d-n-l),t._w=(o-s)/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 n=Oe.Dot(e,t);return 1-n*n<=i}static SmoothToRef(e,t,i,n,s){let a=n===0?1:i/n;return a=za(a,0,1),Oe.SlerpToRef(e,t,a,s),s}static Zero(){return new Oe(0,0,0,0)}static Inverse(e){return new Oe(-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 Oe(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 Oe.RotationAxisToRef(e,t,new Oe)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const n=Math.sin(t/2)/e.length();return i._x=e._x*n,i._y=e._y*n,i._z=e._z*n,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new Oe(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,n,s){return s.copyFromFloats(e,t,i,n),s}static FromEulerAngles(e,t,i){const n=new Oe;return Oe.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerAnglesToRef(e,t,i,n){return Oe.RotationYawPitchRollToRef(t,e,i,n),n}static FromEulerVector(e){const t=new Oe;return Oe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return Oe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,n=Ki){const s=O.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(O.CrossToRef(e,t,oe.Vector3[0]),i.set(oe.Vector3[0].x,oe.Vector3[0].y,oe.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){const n=new Oe;return Oe.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){const s=i*.5,a=t*.5,o=e*.5,l=Math.sin(s),c=Math.cos(s),u=Math.sin(a),h=Math.cos(a),d=Math.sin(o),f=Math.cos(o);return n._x=f*u*c+d*h*l,n._y=d*h*c-f*u*l,n._z=f*h*l-d*u*c,n._w=f*h*c+d*u*l,n._isDirty=!0,n}static RotationAlphaBetaGamma(e,t,i){const n=new Oe;return Oe.RotationAlphaBetaGammaToRef(e,t,i,n),n}static RotationAlphaBetaGammaToRef(e,t,i,n){const s=(i+e)*.5,a=(i-e)*.5,o=t*.5;return n._x=Math.cos(a)*Math.sin(o),n._y=Math.sin(a)*Math.sin(o),n._z=Math.sin(s)*Math.cos(o),n._w=Math.cos(s)*Math.cos(o),n._isDirty=!0,n}static RotationQuaternionFromAxis(e,t,i){const n=new Oe(0,0,0,0);return Oe.RotationQuaternionFromAxisToRef(e,t,i,n),n}static RotationQuaternionFromAxisToRef(e,t,i,n){const s=wi.Matrix[0];return e=e.normalizeToRef(wi.Vector3[0]),t=t.normalizeToRef(wi.Vector3[1]),i=i.normalizeToRef(wi.Vector3[2]),pe.FromXYZAxesToRef(e,t,i,s),Oe.FromRotationMatrixToRef(s,n),n}static FromLookDirectionLH(e,t){const i=new Oe;return Oe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const n=wi.Matrix[0];return pe.LookDirectionLHToRef(e,t,n),Oe.FromRotationMatrixToRef(n,i),i}static FromLookDirectionRH(e,t){const i=new Oe;return Oe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const n=wi.Matrix[0];return pe.LookDirectionRHToRef(e,t,n),Oe.FromRotationMatrixToRef(n,i)}static Slerp(e,t,i){const n=Oe.Identity();return Oe.SlerpToRef(e,t,i,n),n}static SlerpToRef(e,t,i,n){let s,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,s=l?-i:i;else{const c=Math.acos(o),u=1/Math.sin(c);a=Math.sin((1-i)*c)*u,s=l?-Math.sin(i*c)*u:Math.sin(i*c)*u}return n._x=a*e._x+s*t._x,n._y=a*e._y+s*t._y,n._z=a*e._z+s*t._z,n._w=a*e._w+s*t._w,n._isDirty=!0,n}static Hermite(e,t,i,n,s){const a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+s,h=o-a,d=e._x*l+i._x*c+t._x*u+n._x*h,f=e._y*l+i._y*c+t._y*u+n._y*h,p=e._z*l+i._z*c+t._z*u+n._z*h,g=e._w*l+i._w*c+t._w*u+n._w*h;return new Oe(d,f,p,g)}static Hermite1stDerivative(e,t,i,n,s){const a=new Oe;return this.Hermite1stDerivativeToRef(e,t,i,n,s,a),a}static Hermite1stDerivativeToRef(e,t,i,n,s,a){const o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*n._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*n._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*n._z,a._w=(o-s)*6*e._w+(3*o-4*s+1)*t._w+(-o+s)*6*i._w+(3*o-2*s)*n._w,a._isDirty=!0,a}static Normalize(e){const t=Oe.Zero();return Oe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const n=new Oe;return Oe.ClampToRef(e,t,i,n),n}static ClampToRef(e,t,i,n){return n.copyFromFloats(za(e.x,t.x,i.x),za(e.y,t.y,i.y),za(e.z,t.z,i.z),za(e.w,t.w,i.w))}static Random(e=0,t=1){return new Oe(Qn(e,t),Qn(e,t),Qn(e,t),Qn(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(Qn(e,t),Qn(e,t),Qn(e,t),Qn(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(Oe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,n=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+n*n+s*s+a*a}static Center(e,t){return Oe.CenterToRef(e,t,Oe.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(Oe.prototype,{dimension:{value:[4]},rank:{value:1}});class pe{static get Use64Bits(){return jl.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=pe._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,n=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:n}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,jl.MatrixTrackPrecisionChange&&jl.MatrixTrackedMatrices.push(this),this._m=new jl.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],n=e[2],s=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],g=e[13],m=e[14],_=e[15],y=d*_-m*f,v=h*_-g*f,x=h*m-g*d,b=u*_-p*f,C=u*m-d*p,A=u*g-p*h,E=+(o*y-l*v+c*x),P=-(a*y-l*b+c*C),w=+(a*v-o*b+c*A),M=-(a*x-o*C+l*A);return t*E+i*P+n*w+s*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 n=0;n<16;n++)e[t+n]=i[n];return this}asArray(){return this._m}fromArray(e,t=0){return pe.FromArrayToRef(e,t,this)}copyFromFloats(...e){return pe.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 pe.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 pe;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,n=t._m,s=e.m;for(let a=0;a<16;a++)n[a]=i[a]+s[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 n=0;n<16;n++)t[n]+=i[n];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 n=0;n<16;n++)t[n]-=i[n];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,n=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]-n[a];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let n=0;n<16;n++)t[n]-=i[n];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new pe)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,n=t._m,s=e;for(let a=0;a<16;a++)n[a]=i[a]-s[a];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return pe.IdentityToRef(e),e;const t=this._m,i=t[0],n=t[1],s=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],g=t[12],m=t[13],_=t[14],y=t[15],v=f*y-_*p,x=d*y-m*p,b=d*_-m*f,C=h*y-g*p,A=h*_-f*g,E=h*m-g*d,P=+(l*v-c*x+u*b),w=-(o*v-c*C+u*A),M=+(o*x-l*C+u*E),R=-(o*b-l*A+c*E),I=i*P+n*w+s*M+a*R;if(I===0)return e.copyFrom(this),e;const D=1/I,k=c*y-_*u,z=l*y-m*u,W=l*_-m*c,K=o*y-g*u,U=o*_-g*c,j=o*m-g*l,B=c*p-f*u,G=l*p-d*u,Y=l*f-d*c,Z=o*p-h*u,te=o*f-h*c,le=o*d-h*l,ce=-(n*v-s*x+a*b),ue=+(i*v-s*C+a*A),N=-(i*x-n*C+a*E),F=+(i*b-n*A+s*E),X=+(n*k-s*z+a*W),J=-(i*k-s*K+a*U),ae=+(i*z-n*K+a*j),ne=-(i*W-n*U+s*j),he=-(n*B-s*G+a*Y),fe=+(i*B-s*Z+a*te),ye=-(i*G-n*Z+a*le),Se=+(i*Y-n*te+s*le);return pe.FromValuesToRef(P*D,ce*D,X*D,he*D,w*D,ue*D,J*D,fe*D,M*D,N*D,ae*D,ye*D,R*D,F*D,ne*D,Se*D,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 O(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 pe.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 pe;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let n=0;n<16;n++)t[n]*=i[n];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,n=t._m,s=e;for(let a=0;a<16;a++)n[a]=i[a]*s[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 n=this._m,s=e.m,a=n[0],o=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],f=n[7],p=n[8],g=n[9],m=n[10],_=n[11],y=n[12],v=n[13],x=n[14],b=n[15],C=s[0],A=s[1],E=s[2],P=s[3],w=s[4],M=s[5],R=s[6],I=s[7],D=s[8],k=s[9],z=s[10],W=s[11],K=s[12],U=s[13],j=s[14],B=s[15];return t[i]=a*C+o*w+l*D+c*K,t[i+1]=a*A+o*M+l*k+c*U,t[i+2]=a*E+o*R+l*z+c*j,t[i+3]=a*P+o*I+l*W+c*B,t[i+4]=u*C+h*w+d*D+f*K,t[i+5]=u*A+h*M+d*k+f*U,t[i+6]=u*E+h*R+d*z+f*j,t[i+7]=u*P+h*I+d*W+f*B,t[i+8]=p*C+g*w+m*D+_*K,t[i+9]=p*A+g*M+m*k+_*U,t[i+10]=p*E+g*R+m*z+_*j,t[i+11]=p*P+g*I+m*W+_*B,t[i+12]=y*C+v*w+x*D+b*K,t[i+13]=y*A+v*M+x*k+b*U,t[i+14]=y*E+v*R+x*z+b*j,t[i+15]=y*P+v*I+x*W+b*B,this}divide(e){return this.divideToRef(e,new pe)}divideToRef(e,t){const i=this._m,n=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]/n[a];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let n=0;n<16;n++)t[n]/=i[n];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let n=0;n<16;n++)t[n]=Math.min(t[n],i[n]);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 n=0;n<16;n++)t[n]=Math.min(t[n],i[n]);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 pe)}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 n=0;n<16;n++)i[n]=-t[n];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,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]}equalsWithEpsilon(e,t=0){const i=this._m,n=e.m;for(let s=0;s<16;s++)if(!mu(i[s],n[s],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 pe)}floorToRef(e){const t=this._m,i=e._m;for(let n=0;n<16;n++)i[n]=Math.floor(t[n]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new pe)}fractToRef(e){const t=this._m,i=e._m;for(let n=0;n<16;n++)i[n]=t[n]-Math.floor(t[n]);return e.markAsUpdated(),e}clone(){const e=new pe;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Pd(this._m[0]);for(let t=1;t<16;t++)e=e*397^Pd(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Oe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,n,s=!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||wi.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]),n){const o=(s?n.absoluteScaling.x:n.scaling.x)<0?-1:1,l=(s?n.absoluteScaling.y:n.scaling.y)<0?-1:1,c=(s?n.absoluteScaling.z:n.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;pe.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,wi.Matrix[0]),Oe.FromRotationMatrixToRef(wi.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new It(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 pe;return pe.TransposeToRef(this,e),e}transposeToRef(e){return pe.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,n,s){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]=n,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){const t=new pe;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=wi.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return pe.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 pe;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=wi.Vector3[0];if(!this.decompose(t))return pe.IdentityToRef(e),e;const i=this._m,n=1/t._x,s=1/t._y,a=1/t._z;return pe.FromValuesToRef(i[0]*n,i[1]*n,i[2]*n,0,i[4]*s,i[5]*s,i[6]*s,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 pe;return pe.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let n=0;n<16;n++)i._m[n]=e[n+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,n){return n._m[0]=e[0+t]*i,n._m[1]=e[1+t]*i,n._m[2]=e[2+t]*i,n._m[3]=e[3+t]*i,n._m[4]=e[4+t]*i,n._m[5]=e[5+t]*i,n._m[6]=e[6+t]*i,n._m[7]=e[7+t]*i,n._m[8]=e[8+t]*i,n._m[9]=e[9+t]*i,n._m[10]=e[10+t]*i,n._m[11]=e[11+t]*i,n._m[12]=e[12+t]*i,n._m[13]=e[13+t]*i,n._m[14]=e[14+t]*i,n._m[15]=e[15+t]*i,n.markAsUpdated(),n}static get IdentityReadOnly(){return pe._IdentityReadOnly}static FromValuesToRef(e,t,i,n,s,a,o,l,c,u,h,d,f,p,g,m,_){const y=_._m;y[0]=e,y[1]=t,y[2]=i,y[3]=n,y[4]=s,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]=g,y[15]=m,_.markAsUpdated()}static FromValues(e,t,i,n,s,a,o,l,c,u,h,d,f,p,g,m){const _=new pe,y=_._m;return y[0]=e,y[1]=t,y[2]=i,y[3]=n,y[4]=s,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]=g,y[15]=m,_.markAsUpdated(),_}static Compose(e,t,i){const n=new pe;return pe.ComposeToRef(e,t,i,n),n}static ComposeToRef(e,t,i,n){const s=n._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,g=a*d,m=o*h,_=o*d,y=l*d,v=c*u,x=c*h,b=c*d,C=e._x,A=e._y,E=e._z;return s[0]=(1-(m+y))*C,s[1]=(p+b)*C,s[2]=(g-x)*C,s[3]=0,s[4]=(p-b)*A,s[5]=(1-(f+y))*A,s[6]=(_+v)*A,s[7]=0,s[8]=(g+x)*E,s[9]=(_-v)*E,s[10]=(1-(f+m))*E,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,n.markAsUpdated(),n}static Identity(){const e=pe.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 pe.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=pe.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 pe;return pe.RotationXToRef(e,t),t}static Invert(e){const t=new pe;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return pe.FromValuesToRef(1,0,0,0,0,n,i,0,0,-i,n,0,0,0,0,1,t),t._updateIdentityStatus(n===1&&i===0),t}static RotationY(e){const t=new pe;return pe.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return pe.FromValuesToRef(n,0,-i,0,0,1,0,0,i,0,n,0,0,0,0,1,t),t._updateIdentityStatus(n===1&&i===0),t}static RotationZ(e){const t=new pe;return pe.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),n=Math.cos(e);return pe.FromValuesToRef(n,i,0,0,-i,n,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(n===1&&i===0),t}static RotationAxis(e,t){const i=new pe;return pe.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const n=Math.sin(-t),s=Math.cos(-t),a=1-s;e=e.normalizeToRef(wi.Vector3[0]);const o=i._m;return o[0]=e._x*e._x*a+s,o[1]=e._x*e._y*a-e._z*n,o[2]=e._x*e._z*a+e._y*n,o[3]=0,o[4]=e._y*e._x*a+e._z*n,o[5]=e._y*e._y*a+s,o[6]=e._y*e._z*a-e._x*n,o[7]=0,o[8]=e._z*e._x*a-e._y*n,o[9]=e._z*e._y*a+e._x*n,o[10]=e._z*e._z*a+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,n=!1){const s=O.Dot(t,e),a=i._m;if(s<-1+Ki)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=n?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=n?-1:1,a[11]=0;else{const o=O.Cross(t,e),l=1/(1+s);a[0]=o._x*o._x*l+s,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+s,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+s,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 n=new pe;return pe.RotationYawPitchRollToRef(e,t,i,n),n}static RotationYawPitchRollToRef(e,t,i,n){return Oe.RotationYawPitchRollToRef(e,t,i,wi.Quaternion[0]),wi.Quaternion[0].toRotationMatrix(n),n}static Scaling(e,t,i){const n=new pe;return pe.ScalingToRef(e,t,i,n),n}static ScalingToRef(e,t,i,n){return pe.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,n),n._updateIdentityStatus(e===1&&t===1&&i===1),n}static Translation(e,t,i){const n=new pe;return pe.TranslationToRef(e,t,i,n),n}static TranslationToRef(e,t,i,n){return pe.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,n),n._updateIdentityStatus(e===0&&t===0&&i===0),n}static Lerp(e,t,i){const n=new pe;return pe.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){const s=n._m,a=e.m,o=t.m;for(let l=0;l<16;l++)s[l]=a[l]*(1-i)+o[l]*i;return n.markAsUpdated(),n}static DecomposeLerp(e,t,i){const n=new pe;return pe.DecomposeLerpToRef(e,t,i,n),n}static DecomposeLerpToRef(e,t,i,n){const s=wi.Vector3[0],a=wi.Quaternion[0],o=wi.Vector3[1];e.decompose(s,a,o);const l=wi.Vector3[2],c=wi.Quaternion[1],u=wi.Vector3[3];t.decompose(l,c,u);const h=wi.Vector3[4];O.LerpToRef(s,l,i,h);const d=wi.Quaternion[2];Oe.SlerpToRef(a,c,i,d);const f=wi.Vector3[5];return O.LerpToRef(o,u,i,f),pe.ComposeToRef(h,d,f,n),n}static LookAtLH(e,t,i){const n=new pe;return pe.LookAtLHToRef(e,t,i,n),n}static LookAtLHToRef(e,t,i,n){const s=wi.Vector3[0],a=wi.Vector3[1],o=wi.Vector3[2];t.subtractToRef(e,o),o.normalize(),O.CrossToRef(i,o,s);const l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),O.CrossToRef(o,s,a),a.normalize();const c=-O.Dot(s,e),u=-O.Dot(a,e),h=-O.Dot(o,e);return pe.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,u,h,1,n),n}static LookAtRH(e,t,i){const n=new pe;return pe.LookAtRHToRef(e,t,i,n),n}static LookAtRHToRef(e,t,i,n){const s=wi.Vector3[0],a=wi.Vector3[1],o=wi.Vector3[2];e.subtractToRef(t,o),o.normalize(),O.CrossToRef(i,o,s);const l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),O.CrossToRef(o,s,a),a.normalize();const c=-O.Dot(s,e),u=-O.Dot(a,e),h=-O.Dot(o,e);return pe.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,u,h,1,n),n}static LookDirectionLH(e,t){const i=new pe;return pe.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const n=wi.Vector3[0];n.copyFrom(e),n.scaleInPlace(-1);const s=wi.Vector3[1];return O.CrossToRef(t,n,s),pe.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,n._x,n._y,n._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new pe;return pe.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const n=wi.Vector3[2];return O.CrossToRef(t,e,n),pe.FromValuesToRef(n._x,n._y,n._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,n,s){const a=new pe;return pe.OrthoLHToRef(e,t,i,n,a,s),a}static OrthoLHToRef(e,t,i,n,s,a){const o=i,l=n,c=2/e,u=2/t,h=2/(l-o),d=-(l+o)/(l-o);return pe.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,h,0,0,0,d,1,s),a&&s.multiplyToRef(wA,s),s._updateIdentityStatus(c===1&&u===1&&h===1&&d===0),s}static OrthoOffCenterLH(e,t,i,n,s,a,o){const l=new pe;return pe.OrthoOffCenterLHToRef(e,t,i,n,s,a,l,o),l}static OrthoOffCenterLHToRef(e,t,i,n,s,a,o,l){const c=s,u=a,h=2/(t-e),d=2/(n-i),f=2/(u-c),p=-(u+c)/(u-c),g=(e+t)/(e-t),m=(n+i)/(i-n);return pe.FromValuesToRef(h,0,0,0,0,d,0,0,0,0,f,0,g,m,p,1,o),l&&o.multiplyToRef(wA,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,n,s,a,o,l,c,u,h){const d=-o*Math.cos(l),f=-o*Math.sin(l);return pe.TranslationToRef(0,0,-c,wi.Matrix[1]),pe.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,wi.Matrix[0]),wi.Matrix[1].multiplyToRef(wi.Matrix[0],wi.Matrix[0]),pe.TranslationToRef(0,0,c,wi.Matrix[1]),wi.Matrix[0].multiplyToRef(wi.Matrix[1],wi.Matrix[0]),pe.OrthoOffCenterLHToRef(e,t,i,n,s,a,u,h),wi.Matrix[0].multiplyToRef(u,u),u}static OrthoOffCenterRH(e,t,i,n,s,a,o){const l=new pe;return pe.OrthoOffCenterRHToRef(e,t,i,n,s,a,l,o),l}static OrthoOffCenterRHToRef(e,t,i,n,s,a,o,l){return pe.OrthoOffCenterLHToRef(e,t,i,n,s,a,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,n,s,a,o,l,c,u,h){const d=o*Math.cos(l),f=o*Math.sin(l);return pe.TranslationToRef(0,0,c,wi.Matrix[1]),pe.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,wi.Matrix[0]),wi.Matrix[1].multiplyToRef(wi.Matrix[0],wi.Matrix[0]),pe.TranslationToRef(0,0,-c,wi.Matrix[1]),wi.Matrix[0].multiplyToRef(wi.Matrix[1],wi.Matrix[0]),pe.OrthoOffCenterRHToRef(e,t,i,n,s,a,u,h),wi.Matrix[0].multiplyToRef(u,u),u}static PerspectiveLH(e,t,i,n,s,a=0){const o=new pe,l=i,c=n,u=2*l/e,h=2*l/t,d=(c+l)/(c-l),f=-2*c*l/(c-l),p=Math.tan(a);return pe.FromValuesToRef(u,0,0,0,0,h,0,p,0,0,d,1,0,0,f,0,o),s&&o.multiplyToRef(wA,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,n,s,a=0,o=!1){const l=new pe;return pe.PerspectiveFovLHToRef(e,t,i,n,l,!0,s,a,o),l}static PerspectiveFovLHToRef(e,t,i,n,s,a=!0,o,l=0,c=!1){const u=i,h=n,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,g=c&&u===0?-1:h!==0?(h+u)/(h-u):1,m=c&&u===0?2*h:h!==0?-2*h*u/(h-u):-2*u,_=Math.tan(l);return pe.FromValuesToRef(f,0,0,0,0,p,0,_,0,0,g,1,0,0,m,0,s),o&&s.multiplyToRef(wA,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,n,s,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 pe.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(wA,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,n,s,a=0,o=!1){const l=new pe;return pe.PerspectiveFovRHToRef(e,t,i,n,l,!0,s,a,o),l}static PerspectiveFovRHToRef(e,t,i,n,s,a=!0,o,l=0,c=!1){const u=i,h=n,d=1/Math.tan(e*.5),f=a?d/t:d,p=a?d:d*t,g=c&&u===0?1:h!==0?-(h+u)/(h-u):-1,m=c&&u===0?2*h:h!==0?-2*h*u/(h-u):-2*u,_=Math.tan(l);return pe.FromValuesToRef(f,0,0,0,0,p,0,_,0,0,g,-1,0,0,m,0,s),o&&s.multiplyToRef(wA,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,n,s,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 pe.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(wA,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,n,s,a){const o=e.width,l=e.height,c=e.x,u=e.y,h=pe.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,a-s,0,c+o/2,l/2+u,s,1),d=new pe;return t.multiplyToRef(i,d),d.multiplyToRef(n,d),d.multiplyToRef(h,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return jl.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 jl.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new pe;return pe.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,n=i[0],s=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],g=i[14],m=i[3],_=i[7],y=i[11],v=i[15],x=t._m;return x[0]=n,x[1]=s,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]=g,x[12]=m,x[13]=_,x[14]=y,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new pe;return pe.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,n=e.normal.y,s=e.normal.z,a=-2*i,o=-2*n,l=-2*s;return pe.FromValuesToRef(a*i+1,o*i,l*i,0,a*n,o*n+1,l*n,0,a*s,o*s,l*s+1,0,a*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,n){return pe.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,n),n}static FromQuaternionToRef(e,t){const i=e._x*e._x,n=e._y*e._y,s=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*(n+s),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*(s+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*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}pe._UpdateFlagSeed=0;pe._IdentityReadOnly=pe.Identity();Object.defineProperties(pe.prototype,{dimension:{value:[4,4]},rank:{value:2}});class wi{}wi.Vector3=eb(11,O.Zero);wi.Matrix=eb(2,pe.Identity);wi.Quaternion=eb(3,Oe.Zero);class oe{}oe.Vector2=eb(3,Ne.Zero);oe.Vector3=eb(13,O.Zero);oe.Vector4=eb(3,It.Zero);oe.Quaternion=eb(3,Oe.Zero);oe.Matrix=eb(8,pe.Identity);xe("BABYLON.Vector2",Ne);xe("BABYLON.Vector3",O);xe("BABYLON.Vector4",It);xe("BABYLON.Matrix",pe);const wA=pe.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class Xt{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=Xt.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Xt.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let n=Xt.Clamp(i);return n=-2*n*n*n+3*n*n,t*n+e*(1-n)}static MoveTowards(e,t,i){let n=0;return Math.abs(t-e)<=i?n=t:n=e+Xt.Sign(t-e)*i,n}static MoveTowardsAngle(e,t,i){const n=Xt.DeltaAngle(e,t);let s=0;return-i180&&(n-=360),e+n*za(i)}static InverseLerp(e,t,i){let n=0;return e!=t?n=za((i-e)/(t-e)):n=0,n}static Hermite(e,t,i,n,s){const a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+s,h=o-a;return e*l+i*c+t*u+n*h}static Hermite1stDerivative(e,t,i,n,s){const a=s*s;return(a-s)*6*e+(3*a-4*s+1)*t+(-a+s)*6*i+(3*a-2*s)*n}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:Xt.HCF(t,i)}}Xt.TwoPi=Math.PI*2;Xt.WithinEpsilon=mu;Xt.ToHex=Ym;Xt.Clamp=za;Xt.Lerp=ef;Xt.RandomRange=Qn;Xt.NormalizeRadians=eBe;function t5(r){return Math.pow(r,$9)}function i5(r){return r<=.04045?.0773993808*r:Math.pow(.947867299*(r+.055),2.4)}function r5(r){return Math.pow(r,e5)}function n5(r){return r<=.0031308?12.92*r:1.055*Math.pow(r,.41666)-.055}class Pe{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 Pe.FromArrayToRef(e,t,this),this}toColor4(e=1){return new at(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 Pe(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 Pe(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=Ki){return Xt.WithinEpsilon(this.r,e.r,t)&&Xt.WithinEpsilon(this.g,e.g,t)&&Xt.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 Pe(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=za(this.r,e,t),i.g=za(this.g,e,t),i.b=za(this.b,e,t),i}add(e){return new Pe(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 Pe(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 Pe(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n}clone(){return new Pe(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"#"+Ym(e)+Ym(t)+Ym(i)}toHSV(){return this.toHSVToRef(new Pe)}toHSVToRef(e){const t=this.r,i=this.g,n=this.b,s=Math.max(t,i,n),a=Math.min(t,i,n);let o=0,l=0;const c=s,u=s-a;return s!==0&&(l=u/s),s!=a&&(s==t?(o=(i-n)/u,i=0&&a<=1?(l=s,c=o):a>=1&&a<=2?(l=o,c=s):a>=2&&a<=3?(c=s,u=o):a>=3&&a<=4?(c=o,u=s):a>=4&&a<=5?(l=o,u=s):a>=5&&a<=6&&(l=s,u=o);const h=i-s;return n.r=l+h,n.g=c+h,n.b=u+h,n}static FromHSV(e,t,i){const n=new Pe(0,0,0);return Pe.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new Pe(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16);return Pe.FromInts(t,i,n)}static FromArray(e,t=0){return new Pe(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 Pe(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new Pe(0,0,0);return Pe.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,s){const a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*u+n.r*h,f=e.g*l+i.g*c+t.g*u+n.g*h,p=e.b*l+i.b*c+t.b*u+n.b*h;return new Pe(d,f,p)}static Hermite1stDerivative(e,t,i,n,s){const a=Pe.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,s,a),a}static Hermite1stDerivativeToRef(e,t,i,n,s,a){const o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*n.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*n.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*n.b}static Red(){return new Pe(1,0,0)}static Green(){return new Pe(0,1,0)}static Blue(){return new Pe(0,0,1)}static Black(){return new Pe(0,0,0)}static get BlackReadOnly(){return Pe._BlackReadOnly}static White(){return new Pe(1,1,1)}static Purple(){return new Pe(.5,0,.5)}static Magenta(){return new Pe(1,0,1)}static Yellow(){return new Pe(1,1,0)}static Gray(){return new Pe(.5,.5,.5)}static Teal(){return new Pe(0,1,1)}static Random(){return new Pe(Math.random(),Math.random(),Math.random())}}Pe._BlackReadOnly=Pe.Black();Object.defineProperties(Pe.prototype,{dimension:{value:[3]},rank:{value:1}});class at{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}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 at(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,n){return this.r+=e,this.g+=t,this.b+=i,this.a+=n,this}subtract(e){return new at(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,n){return new at(this.r-e,this.g-t,this.b-i,this.a-n)}subtractFromFloatsToRef(e,t,i,n,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-n,s}scale(e){return new at(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=za(this.r,e,t),i.g=za(this.g,e,t),i.b=za(this.b,e,t),i.a=za(this.a,e,t),i}multiply(e){return new at(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,n){return new at(this.r*e,this.g*t,this.b*i,this.a*n)}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,n){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(n,this.a),this}maximizeInPlaceFromFloats(e,t,i,n){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(n,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=Ki){return Xt.WithinEpsilon(this.r,e.r,t)&&Xt.WithinEpsilon(this.g,e.g,t)&&Xt.WithinEpsilon(this.b,e.b,t)&&Xt.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,n){return this.r===e&&this.g===t&&this.b===i&&this.a===n}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 at().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,n){return this.r=e,this.g=t,this.b=i,this.a=n,this}set(e,t,i,n){return this.copyFromFloats(e,t,i,n)}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),n=Math.round(this.b*255);if(e)return"#"+Ym(t)+Ym(i)+Ym(n);const s=Math.round(this.a*255);return"#"+Ym(t)+Ym(i)+Ym(n)+Ym(s)}toLinearSpace(e=!1){const t=new at;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=i5(this.r),e.g=i5(this.g),e.b=i5(this.b)):(e.r=t5(this.r),e.g=t5(this.g),e.b=t5(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new at;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=n5(this.r),e.g=n5(this.g),e.b=n5(this.b)):(e.r=r5(this.r),e.g=r5(this.g),e.b=r5(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new at(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),s=e.length===9?parseInt(e.substring(7,9),16):255;return at.FromInts(t,i,n,s)}static Lerp(e,t,i){return at.LerpToRef(e,t,i,new at)}static LerpToRef(e,t,i,n){return n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i,n}static Hermite(e,t,i,n,s){const a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,u=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*u+n.r*h,f=e.g*l+i.g*c+t.g*u+n.g*h,p=e.b*l+i.b*c+t.b*u+n.b*h,g=e.a*l+i.a*c+t.a*u+n.a*h;return new at(d,f,p,g)}static Hermite1stDerivative(e,t,i,n,s){const a=new at;return this.Hermite1stDerivativeToRef(e,t,i,n,s,a),a}static Hermite1stDerivativeToRef(e,t,i,n,s,a){const o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*n.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*n.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*n.b,a.a=(o-s)*6*e.a+(3*o-4*s+1)*t.a+(-o+s)*6*i.a+(3*o-2*s)*n.a}static FromColor3(e,t=1){return new at(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new at(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,n){return new at(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let n=0;nnew at(0,0,0,0));xe("BABYLON.Color3",Pe);xe("BABYLON.Color4",at);class ws{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new Ce,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 n=this._condition.serialize();return n.children.push(i),t&&t.children.push(n),n}return t&&t.children.push(i),i}}ws._SerializeValueAsString=r=>typeof r=="number"?r.toString():typeof r=="boolean"?r?"true":"false":r instanceof Ne?r.x+", "+r.y:r instanceof O?r.x+", "+r.y+", "+r.z:r instanceof Pe?r.r+", "+r.g+", "+r.b:r instanceof at?r.r+", "+r.g+", "+r.b+", "+r.a:r;ws._GetTargetProperty=r=>({name:"target",targetType:r._isMesh?"MeshProperties":r._isLight?"LightProperties":r._isCamera?"CameraProperties":r._isMaterial?"MaterialProperties":"SceneProperties",value:r._isScene?"Scene":r.name});xe("BABYLON.Action",ws);class Ca{constructor(e,t,i,n,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){const n=e.getScene();return new Ca(e,n.pointerX,n.pointerY,n.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,n){return new Ca(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,n)}static CreateNewFromScene(e,t){return new Ca(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,n){return new Ca(e,t.x,t.y,null,i,n)}}class rw{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 Gl extends rw{static get IsEqual(){return Gl._IsEqual}static get IsDifferent(){return Gl._IsDifferent}static get IsGreater(){return Gl._IsGreater}static get IsLesser(){return Gl._IsLesser}constructor(e,t,i,n,s=Gl.IsEqual){super(e),this.propertyPath=i,this.value=n,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Gl.IsGreater:return this._effectiveTarget[this._property]>this.value;case Gl.IsLesser:return this._effectiveTarget[this._property]n<10?"0"+n:""+n,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 n=Array.isArray(t)?t[0]:t;if(i!==void 0&&!ge._CheckLimit(n,i))return;const s=ge._FormatMessage(n),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+s,...o);const l=`
${s}

`;ge._AddLogEntry(l),ge._GenerateLimitMessage(n,e)}static get LogCache(){return ge._LogCache}static ClearLogCache(){ge._LogCache="",ge._LogLimitOutputs={},ge.errorsCount=0}static set LogLevels(e){ge.Log=ge._LogDisabled,ge.Warn=ge._LogDisabled,ge.Error=ge._LogDisabled,[ge.MessageLogLevel,ge.WarningLogLevel,ge.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];ge[i.name]=ge._LogEnabled.bind(ge,t)}})}}ge.NoneLogLevel=0;ge.MessageLogLevel=1;ge.WarningLogLevel=2;ge.ErrorLogLevel=4;ge.AllLogLevel=7;ge.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";ge._LogCache="";ge._LogLimitOutputs={};ge._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];ge.errorsCount=0;ge.Log=ge._LogEnabled.bind(ge,ge.MessageLogLevel);ge.Warn=ge._LogEnabled.bind(ge,ge.WarningLogLevel);ge.Error=ge._LogEnabled.bind(ge,ge.ErrorLogLevel);class rBe extends ws{constructor(e,t,i,n){super(e,n),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:[ws._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class nBe extends ws{constructor(e,t,i,n){super(e,n),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[ws._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class sBe extends ws{constructor(e,t,i,n,s){super(e,s),this.propertyPath=i,this.value=n,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:[ws._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ws._SerializeValueAsString(this.value)}]},e)}}class aBe extends ws{constructor(e,t,i,n,s){super(e,s),this.propertyPath=i,this.value=n,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"&&ge.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:[ws._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ws._SerializeValueAsString(this.value)}]},e)}}class oBe extends ws{constructor(e,t,i,n,s,a){super(e,a),this.from=i,this.to=n,this.loop=s,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:[ws._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:ws._SerializeValueAsString(this.loop)||!1}]},e)}}class lBe extends ws{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:[ws._GetTargetProperty(this._target)]},e)}}class $ge extends ws{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class cBe extends ws{constructor(e,t,i,n=!0){super(e,i),this.children=t,this.enableChildrenConditions=n}_prepare(){for(let e=0;e!r||r.getClassName&&r.getClassName()==="Mesh"?null:r.getClassName&&(r.getClassName()==="SubMesh"||r.getClassName()==="PhysicsBody")?r.clone(e):r.clone?r.clone():Array.isArray(r)?r.slice():t&&typeof r=="object"?{...r}:null;function S2t(r){const e=[];do Object.getOwnPropertyNames(r).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(r=Object.getPrototypeOf(r));return e}class bc{static DeepCopy(e,t,i,n,s=!1){const a=S2t(e);for(const o of a){if(o[0]==="_"&&(!n||n.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=Fn.OnPickTrigger&&t.trigger<=Fn.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Fn.OnPickTrigger&&t.trigger<=Fn.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Fn.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(ge.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Fn.Triggers[e.trigger]?Fn.Triggers[e.trigger]++:Fn.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),Fn.Triggers[e.trigger]-=1,Fn.Triggers[e.trigger]===0&&delete Fn.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const u=Sa("BABYLON."+l);return u&&new u(...c)},a=(l,c,u,h)=>{if(h===null){const g=parseFloat(c);return c==="true"||c==="false"?c==="true":isNaN(g)?c:g}const d=h.split("."),f=c.split(",");for(let g=0;g{if(l.detached)return;const f=[];let p=null,g=null;const m=l.combine&&l.combine.length>0;if(l.type===2?f.push(n):f.push(c),m){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:Fn[u.name],parameter:d}}else c=Fn[u.name];for(let h=0;h=0;o--)(a=r[o])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}const dX={},ZY={};function E2t(r){const e=r.getClassName();return ZY[e]||(ZY[e]={}),ZY[e]}function Iue(r){const e=r.getClassName();if(dX[e])return dX[e];dX[e]={};const t=dX[e];let i=r,n=e;for(;n;){const s=ZY[n];for(const l in s)t[l]=s[l];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==n)break;i=a}while(a);if(o)break;n=a.getClassName(),i=a}return t}function Lp(r,e){return(t,i)=>{const n=E2t(t);n[i]||(n[i]={type:r,sourceName:e})}}function T2t(r,e=null){return(t,i)=>{const n=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[n]},set:function(s){typeof this.equals=="function"&&this.equals(s)||this[n]!==s&&(this[n]=s,t[r].apply(this))},enumerable:!0,configurable:!0})}}function Ke(r,e=null){return T2t(r,e)}function Q(r){return Lp(0,r)}function ki(r){return Lp(1,r)}function qr(r){return Lp(2,r)}function Yw(r){return Lp(3,r)}function Cz(r){return Lp(4,r)}function ta(r){return Lp(5,r)}function Qw(r){return Lp(6,r)}function fBe(r){return Lp(7,r)}function Zw(r){return Lp(8,r)}function Yge(r){return Lp(9,r)}function pBe(r){return Lp(10,r)}function DJ(r){return Lp(12,r)}function mBe(r){return Lp(11,r)}function M_(r,e,t,i){const n=t.value;t.value=(...s)=>{let a=n;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?a=(...l)=>i(...l)?o(...l):n(...l):a=o}return r[e]=a,a(...s)}}M_.filter=function(r){return(e,t,i)=>M_(e,t,i,r)};const fMe={};function Ji(r,e=!1){if(!(e&&fMe[r]))return fMe[r]=!0,`${r} needs to be imported before as it contains a side-effect required by your code.`}class Yy{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),Yy._HandleParenthesisContent(i,t))):e=Yy._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Yy.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(s=>s==="true");let i;const n=e.split("||");for(const s in n)if(Object.prototype.hasOwnProperty.call(n,s)){let a=Yy._SimplifyNegation(n[s].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 fn{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>fn.HasTags(e),e.addTags=t=>fn.AddTagsTo(e,t),e.removeTags=t=>fn.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>fn.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 n in e._tags)Object.prototype.hasOwnProperty.call(e._tags,n)&&e._tags[n]===!0&&i.push(n);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(n){fn._AddTagTo(e,n)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(fn.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!fn.HasTags(e))return;const i=t.split(" ");for(const n in i)fn._RemoveTagFrom(e,i[n])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?fn.HasTags(e):Yy.Eval(t,i=>fn.HasTags(e)&&e._tags[i])}}const pMe=function(r,e,t,i={}){const n=r();fn&&fn.HasTags(e)&&fn.AddTagsTo(n,fn.GetTags(e,!0));const s=Iue(n),a={};for(const o in s){const l=s[o],c=e[o],u=l.type;if(c!=null&&(o!=="uniqueId"||ot.AllowLoadingUniqueId))switch(u){case 0:case 6:case 11:n[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&a[c.uniqueId]?n[o]=a[c.uniqueId]:(n[o]=t||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=n[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[o]=t?c:c.clone();break}}return n};class ot{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw Ji("ImageProcessingConfiguration")};ot._FresnelParametersParser=r=>{throw Ji("FresnelParameters")};ot._ColorCurvesParser=r=>{throw Ji("ColorCurves")};ot._TextureParser=(r,e,t)=>{throw Ji("Texture")};class M2t{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new Ce,this._onClonedObservable=new Ce}}let Dn=class Pue{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const s=this._NodeConstructors[e];return s?s(t,i,n):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 M2t,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new Ce,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=pe.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new Ce,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||ei.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 n=0;n(!t||t(n))&&n.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 Pue(e,this.getScene()),this);if(t&&(n.parent=t),!i){const s=this.getDescendants(!0);for(let a=0;a{throw Ji("AnimationRange")};Dn._NodeConstructors={};V([Q()],Dn.prototype,"name",void 0);V([Q()],Dn.prototype,"id",void 0);V([Q()],Dn.prototype,"uniqueId",void 0);V([Q()],Dn.prototype,"state",void 0);V([Q()],Dn.prototype,"metadata",void 0);class Fu{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 Fu(this.width*e,this.height*t)}clone(){return new Fu(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 Fu(0,0)}add(e){return new Fu(this.width+e.width,this.height+e.height)}subtract(e){return new Fu(this.width-e.width,this.height-e.height)}scale(e){return new Fu(this.width*e,this.height*e)}static Lerp(e,t,i){const n=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new Fu(n,s)}}function R2t(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class oa{constructor(){this._xhr=R2t(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(oa.CustomRequestHeaders).length>0||oa.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in oa.CustomRequestHeaders){const t=oa.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return oa.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){oa.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of oa.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)}}oa.CustomRequestHeaders={};oa.CustomRequestModifiers=new Array;oa.SkipRequestModificationForBabylonCDN=!0;const Qge=Object.freeze(new Oe(0,0,0,0)),Zge=Object.freeze(O.Zero()),qge=Object.freeze(Ne.Zero()),Jge=Object.freeze(Fu.Zero()),e1e=Object.freeze(Pe.Black()),t1e=Object.freeze(new at(0,0,0,0)),Nm={key:0,repeatCount:0,loopMode:2};let dt=class zi{static _PrepareAnimation(e,t,i,n,s,a,o,l){let c;if(!isNaN(parseFloat(s))&&isFinite(s)?c=zi.ANIMATIONTYPE_FLOAT:s instanceof Oe?c=zi.ANIMATIONTYPE_QUATERNION:s instanceof O?c=zi.ANIMATIONTYPE_VECTOR3:s instanceof Ne?c=zi.ANIMATIONTYPE_VECTOR2:s instanceof Pe?c=zi.ANIMATIONTYPE_COLOR3:s instanceof at?c=zi.ANIMATIONTYPE_COLOR4:s instanceof Fu&&(c=zi.ANIMATIONTYPE_SIZE),c==null)return null;const u=new zi(e,t,i,c,o),h=[{frame:0,value:s},{frame:n,value:a}];return u.setKeys(h),l!==void 0&&u.setEasingFunction(l),u}static CreateAnimation(e,t,i,n){const s=new zi(e+"Animation",e,i,t,zi.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(n),s}static CreateAndStartAnimation(e,t,i,n,s,a,o,l,c,u,h){const d=zi._PrepareAnimation(e,i,n,s,a,o,l,c);return!d||(t.getScene&&(h=t.getScene()),!h)?null:h.beginDirectAnimation(t,[d],0,s,d.loopMode===1,1,u)}static CreateAndStartHierarchyAnimation(e,t,i,n,s,a,o,l,c,u,h){const d=zi._PrepareAnimation(e,n,s,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,n,s,a,o,l,c,u){const h=zi._PrepareAnimation(e,i,n,s,a,o,l,c);return h?(t.animations.push(h),t.getScene().beginAnimation(t,0,s,h.loopMode===1,1,u)):null}static MakeAnimationAdditive(e,t,i,n=!1,s){let a;typeof t=="object"?a=t:a={referenceFrame:t??0,range:i,cloneOriginalAnimation:n,clonedAnimationName:s};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:oe.Vector3[0],referenceQuaternion:oe.Quaternion[0],referenceScaling:oe.Vector3[1],keyPosition:oe.Vector3[2],keyQuaternion:oe.Quaternion[1],keyScaling:oe.Vector3[3]};let p=u.frame,g=d.frame;if(a.range){const y=o.getRange(a.range);y&&(p=y.from,g=y.to)}else p=a.fromFrame??p,g=a.toFrame??g;if(p!==u.frame&&(c=o.createKeyForFrame(p)),g!==d.frame&&(h=o.createKeyForFrame(g)),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{Nm.key=0;const y=o._interpolate(l,Nm);f.referenceValue=y.clone?y.clone():y}o.dataType===zi.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():o.dataType===zi.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let m=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},_&&(m===Number.MAX_VALUE&&(m=v.frame),v.frame-=m,_.push(v))),!(y&&o.dataType!==zi.ANIMATIONTYPE_FLOAT&&v.value===u.value))switch(o.dataType){case zi.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),pe.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,v.value);break;case zi.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(v.value,v.value);break;case zi.ANIMATIONTYPE_VECTOR2:case zi.ANIMATIONTYPE_VECTOR3:case zi.ANIMATIONTYPE_COLOR3:case zi.ANIMATIONTYPE_COLOR4:v.value.subtractToRef(f.referenceValue,v.value);break;case zi.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,n,s,a,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const c=s*(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=n.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,n,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=s,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=n,this.loopMode=s===void 0?zi.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=zi._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 n in this._ranges)i&&(t+=", ",i=!1),t+=n;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>=n&&this._keys[a].frame<=s&&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 n=this._keys,s=n.length;let a=t.key;for(;a>=0&&e=n[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(n[0].value);if(a+1>s-1)return i?void 0:this._getKeyValue(n[s-1].value);const o=n[a],l=n[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 zi.ANIMATIONTYPE_FLOAT:{const g=h?this.floatInterpolateFunctionWithTangents(c,o.outTangent*d,u,l.inTangent*d,f):this.floatInterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+g}break}case zi.ANIMATIONTYPE_QUATERNION:{const g=h?this.quaternionInterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.quaternionInterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((t.offsetValue||Qge).scale(t.repeatCount))}return g}case zi.ANIMATIONTYPE_VECTOR3:{const g=h?this.vector3InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.vector3InterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||Zge).scale(t.repeatCount))}break}case zi.ANIMATIONTYPE_VECTOR2:{const g=h?this.vector2InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.vector2InterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||qge).scale(t.repeatCount))}break}case zi.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(c,u,f);case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(c,u,f).add((t.offsetValue||Jge).scale(t.repeatCount))}break}case zi.ANIMATIONTYPE_COLOR3:{const g=h?this.color3InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.color3InterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||e1e).scale(t.repeatCount))}break}case zi.ANIMATIONTYPE_COLOR4:{const g=h?this.color4InterpolateFunctionWithTangents(c,o.outTangent.scale(d),u,l.inTangent.scale(d),f):this.color4InterpolateFunction(c,u,f);switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return g;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.add((t.offsetValue||t1e).scale(t.repeatCount))}break}case zi.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case zi.ANIMATIONLOOPMODE_CYCLE:case zi.ANIMATIONLOOPMODE_CONSTANT:case zi.ANIMATIONLOOPMODE_YOYO:return zi.AllowMatricesInterpolation?this.matrixInterpolateFunction(c,u,f,t.workValue):c;case zi.ANIMATIONLOOPMODE_RELATIVE:case zi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return c}break}}return 0}matrixInterpolateFunction(e,t,i,n){return zi.AllowMatrixDecomposeForInterpolation?n?(pe.DecomposeLerpToRef(e,t,i,n),n):pe.DecomposeLerp(e,t,i):n?(pe.LerpToRef(e,t,i,n),n):pe.Lerp(e,t,i)}clone(){const e=new zi(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){Nm.key=0;const t=this._interpolate(e,Nm,!0);if(!t)return this._keys[Nm.key].frame===e?Nm.key:Nm.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Nm.key+1,0,i),Nm.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 n=0;n=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(u=o.values[3]);break;case zi.ANIMATIONTYPE_QUATERNION:if(s=Oe.FromArray(o.values),o.values.length>=8){const d=Oe.FromArray(o.values.slice(4,8));d.equals(Oe.Zero())||(l=d)}if(o.values.length>=12){const d=Oe.FromArray(o.values.slice(8,12));d.equals(Oe.Zero())||(c=d)}o.values.length>=13&&(u=o.values[12]);break;case zi.ANIMATIONTYPE_MATRIX:s=pe.FromArray(o.values),o.values.length>=17&&(u=o.values[16]);break;case zi.ANIMATIONTYPE_COLOR3:s=Pe.FromArray(o.values),o.values[3]&&(l=Pe.FromArray(o.values[3])),o.values[4]&&(c=Pe.FromArray(o.values[4])),o.values[5]&&(u=o.values[5]);break;case zi.ANIMATIONTYPE_COLOR4:s=at.FromArray(o.values),o.values[4]&&(l=at.FromArray(o.values[4])),o.values[5]&&(c=at.FromArray(o.values[5])),o.values[6]&&(u=at.FromArray(o.values[6]));break;case zi.ANIMATIONTYPE_VECTOR3:default:s=O.FromArray(o.values),o.values[3]&&(l=O.FromArray(o.values[3])),o.values[4]&&(c=O.FromArray(o.values[4])),o.values[5]&&(u=o.values[5]);break}const h={};h.frame=o.frame,h.value=s,l!=null&&(h.inTangent=l),c!=null&&(h.outTangent=c),u!=null&&(h.interpolation=u),n.push(h)}if(t.setKeys(n),e.ranges)for(a=0;a{const s=new oa;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a=JSON.parse(s.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 n("Unable to load the animation")}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const n=new oa;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const s=JSON.parse(JSON.parse(n.responseText).jsonPayload);if(s.animations){const a=JSON.parse(s.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(s.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};dt._UniqueIdGenerator=0;dt.AllowMatricesInterpolation=!1;dt.AllowMatrixDecomposeForInterpolation=!0;dt.SnippetUrl="https://snippet.babylonjs.com";dt.ANIMATIONTYPE_FLOAT=0;dt.ANIMATIONTYPE_VECTOR3=1;dt.ANIMATIONTYPE_QUATERNION=2;dt.ANIMATIONTYPE_MATRIX=3;dt.ANIMATIONTYPE_COLOR3=4;dt.ANIMATIONTYPE_COLOR4=7;dt.ANIMATIONTYPE_VECTOR2=5;dt.ANIMATIONTYPE_SIZE=6;dt.ANIMATIONLOOPMODE_RELATIVE=0;dt.ANIMATIONLOOPMODE_CYCLE=1;dt.ANIMATIONLOOPMODE_CONSTANT=2;dt.ANIMATIONLOOPMODE_YOYO=4;dt.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;dt.CreateFromSnippetAsync=dt.ParseFromSnippetAsync;xe("BABYLON.Animation",dt);Dn._AnimationRangeFactory=(r,e,t)=>new QS(r,e,t);class gBe extends ws{constructor(e,t,i,n,s=1e3,a,o,l){super(e,a),this.duration=1e3,this.onInterpolationDoneObservable=new Ce,this.propertyPath=i,this.value=n,this.duration=s,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=dt.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Pe)i=dt.ANIMATIONTYPE_COLOR3;else if(this.value instanceof O)i=dt.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof pe)i=dt.ANIMATIONTYPE_MATRIX;else if(this.value instanceof Oe)i=dt.ANIMATIONTYPE_QUATERNION;else{ge.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const n=new dt("InterpolateValueAction",this._property,100*(1e3/this.duration),i,dt.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const s=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,s)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[ws._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ws._SerializeValueAsString(this.value)},{name:"duration",value:ws._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:ws._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}xe("BABYLON.InterpolateValueAction",gBe);class _Be{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,n){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=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===dt.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=pe.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 s=t.getEvents();s&&s.length>0&&s.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 n=e;for(let s=0;s-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 n=this._events;if(n.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*s)/1e3+this._absoluteFrameOffset,f=0,p=!1;const g=n&&this._animationState.loopMode===dt.ANIMATIONLOOPMODE_YOYO;if(g){const v=(d-t)/u,x=Math.sin(v*Math.PI);d=Math.abs(x)*u+t;const C=x>=0?1:-1;this._yoyoDirection!==C&&(p=!0),this._yoyoDirection=C}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!n&&i>=t&&(d>=u&&s>0||d<=0&&s<0))c=!1,f=o._getKeyValue(this._maxValue);else if(!n&&t>=i&&(d<=u&&s<0||d>=0&&s>0))c=!1,f=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==dt.ANIMATIONLOOPMODE_CYCLE){const v=i.toString()+t.toString();if(!this._offsetsCache[v]){this._animationState.repeatCount=0,this._animationState.loopMode=dt.ANIMATIONLOOPMODE_CYCLE;const x=o._interpolate(t,this._animationState),b=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case dt.ANIMATIONTYPE_FLOAT:this._offsetsCache[v]=b-x;break;case dt.ANIMATIONTYPE_QUATERNION:this._offsetsCache[v]=b.subtract(x);break;case dt.ANIMATIONTYPE_VECTOR3:this._offsetsCache[v]=b.subtract(x);break;case dt.ANIMATIONTYPE_VECTOR2:this._offsetsCache[v]=b.subtract(x);break;case dt.ANIMATIONTYPE_SIZE:this._offsetsCache[v]=b.subtract(x);break;case dt.ANIMATIONTYPE_COLOR3:this._offsetsCache[v]=b.subtract(x);break}this._highLimitsCache[v]=b}f=this._highLimitsCache[v],h=this._offsetsCache[v]}if(h===void 0)switch(o.dataType){case dt.ANIMATIONTYPE_FLOAT:h=0;break;case dt.ANIMATIONTYPE_QUATERNION:h=Qge;break;case dt.ANIMATIONTYPE_VECTOR3:h=Zge;break;case dt.ANIMATIONTYPE_VECTOR2:h=qge;break;case dt.ANIMATIONTYPE_SIZE:h=Jge;break;case dt.ANIMATIONTYPE_COLOR3:h=e1e;break;case dt.ANIMATIONTYPE_COLOR4:h=t1e;break}let m;if(this._host&&this._host.syncRoot){const v=this._host.syncRoot,x=(v.masterFrame-v.fromFrame)/(v.toFrame-v.fromFrame);m=t+u*x}else d>0&&t>i||d<0&&t0&&this.currentFrame>m||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=m,this._animationState.repeatCount=u===0?0:d/u>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=h;const y=o._interpolate(m,this._animationState);if(this.setValue(y,a),_.length){for(let v=0;v<_.length;v++)if(u>=0&&m>=_[v].frame&&_[v].frame>=t||u<0&&m<=_[v].frame&&_[v].frame<=t){const x=_[v];x.isDone||(x.onlyOnce&&(_.splice(v,1),v--),x.isDone=!0,x.action(m))}}return c||(this._stopped=!0),c}}function dl(){return typeof window<"u"}function ex(){return typeof navigator<"u"}function OS(){return typeof document<"u"}function Az(r){let e="",t=r.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}const I2t={IsWindowObjectExist:dl,IsNavigatorAvailable:ex,IsDocumentAvailable:OS,GetDOMTextContent:Az};class hn{static get Now(){return dl()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class LS{}LS.FilesToLoad={};class vBe{static ExponentialBackoff(e=3,t=500){return(i,n,s)=>n.status!==0||s>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,s)*t}}class ZS extends Error{}ZS._setPrototypeOf=Object.setPrototypeOf||((r,e)=>(r.__proto__=e,r));const B_={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Q0 extends ZS{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",ZS._setPrototypeOf(this,Q0.prototype)}}const yBe=(r,e)=>r.endsWith(e),xBe=(r,e)=>r?r.startsWith(e):!1,i1e=r=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(r);let e="";for(let t=0;t{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,n,s,a,o,l,c,u=0;const h=ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);for(;u>2,o=(i&3)<<4|n>>4,l=(n&15)<<2|s>>6,c=s&63,isNaN(n)?l=c=64:isNaN(s)&&(c=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t},OJ=r=>atob(r),Ez=r=>{const e=OJ(r),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let n=0;n{let t=String(r);for(;t.length{i+=u.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class O2t{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const s=t.split(";");for(let a=0;a{u=u.trim(),u!==""&&(i.push(u),u="")},a=h=>{nRo._Stack[n],l=()=>n===-1?"!!INVALID EXPRESSION!!":Ro._Stack[n--];let c=0,u="";for(;c1){for(s();n!==-1&&Ro._OperatorPriority[o()]>=Ro._OperatorPriority[d];)i.push(l());a(d),c++}else u+=h;c++}for(s();n!==-1;)o()==="("?l():i.push(l());return Ro._InfixToPostfixCache.size>=Ro.InfixToPostfixCacheLimitSize&&Ro.ClearCache(),Ro._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(Ro._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=n>s;break;case"<":i=n=":i=n>=s;break;case"==":i=n===s;break;case"!=":i=n!==s;break}return i}}const hZ={};function CBe(r,e,t=""){return t+(e?e+` `:"")+r}function ABe(r,e,t,i,n,s,a){const o=a||hZ.loadFile;if(o)return o(r,e,t,i,n,s);throw Ji("FileTools")}function SBe(r,e,t,i){if(r){e?r.IS_NDC_HALF_ZRANGE="":delete r.IS_NDC_HALF_ZRANGE,t?r.USE_REVERSE_DEPTHBUFFER="":delete r.USE_REVERSE_DEPTHBUFFER,i?r.USE_EXACT_SRGB_CONVERSIONS="":delete r.USE_EXACT_SRGB_CONVERSIONS;return}else{let n="";return e&&(n+="#define IS_NDC_HALF_ZRANGE"),t&&(n&&(n+=` `),n+="#define USE_REVERSE_DEPTHBUFFER"),i&&(n&&(n+=` `),n+="#define USE_EXACT_SRGB_CONVERSIONS"),n}}const k2t=/defined\s*?\((.+?)\)/g,aae=/defined\s*?\[(.+?)\]/g,U2t=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,z2t=/__decl__/,mMe=/light\{X\}.(\w*)/g,gMe=/\{X\}/g,fX=[],V2t=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function r1e(r){r.processor&&r.processor.initializeShaders&&r.processor.initializeShaders(r.processingContext)}function dZ(r,e,t,i){var n;(n=e.processor)!=null&&n.preProcessShaderCode&&(r=e.processor.preProcessShaderCode(r,e.isFragment)),Hk(r,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));const a=H2t(s,e,i);t(a,s)})}function G2t(r,e,t,i){var n;(n=e.processor)!=null&&n.preProcessShaderCode&&(r=e.processor.preProcessShaderCode(r,e.isFragment)),Hk(r,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));const a=j2t(s,e,i);t(a,s)})}function n1e(r,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:r,fragmentCode:e}:t.processor.finalizeShaders(r,e,t.processingContext)}function W2t(r,e){var i;if((i=e.processor)!=null&&i.noPrecision)return r;const t=e.shouldUseHighPrecisionShader;return r.indexOf("precision highp float")===-1?t?r=`precision highp float; `+r:r=`precision mediump float; `+r:t||(r=r.replace("precision highp float","precision mediump float")),r}function oae(r){const t=/defined\((.+)\)/.exec(r);if(t&&t.length)return new uZ(t[1].trim(),r[0]==="!");const i=["==","!=",">=","<=","<",">"];let n="",s=0;for(n of i)if(s=r.indexOf(n),s>-1)break;if(s===-1)return new uZ(r);const a=r.substring(0,s).trim(),o=r.substring(s+n.length).trim();return new B2t(a,n,o)}function K2t(r){r=r.replace(k2t,"defined[$1]");const e=Ro.infixToPostfix(r),t=[];for(const n of e)if(n!=="||"&&n!=="&&")t.push(n);else if(t.length>=2){let s=t[t.length-1],a=t[t.length-2];t.length-=2;const o=n=="&&"?new F2t:new N2t;typeof s=="string"&&(s=s.replace(aae,"defined($1)")),typeof a=="string"&&(a=a.replace(aae,"defined($1)")),o.leftOperand=typeof a=="string"?oae(a):a,o.rightOperand=typeof s=="string"?oae(s):s,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(aae,"defined($1)")),typeof i=="string"?oae(i):i}function qY(r,e){const t=new L2t,i=r.substring(0,e);let n=r.substring(e);return n=n.substring(0,(n.indexOf("//")+1||n.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new uZ(n):i==="#ifndef"?t.testExpression=new uZ(n,!0):t.testExpression=K2t(n),t}function lae(r,e,t){let i=r.currentLine;for(;wue(r,t);){i=r.currentLine;const n=i.substring(0,5).toLowerCase();if(n==="#else"){const s=new Tz;e.children.push(s),wue(r,s);return}else if(n==="#elif"){const s=qY(i,5);e.children.push(s),t=s}}}function wue(r,e){for(;r.canRead;){r.lineIndex++;const t=r.currentLine;if(t.indexOf("#")>=0){const n=V2t.exec(t);if(n&&n.length){switch(n[0]){case"#ifdef":{const a=new sae;e.children.push(a);const o=qY(t,6);a.children.push(o),lae(r,a,o);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const a=new sae;e.children.push(a);const o=qY(t,7);a.children.push(o),lae(r,a,o);break}case"#if":{const a=new sae,o=qY(t,3);e.children.push(a),a.children.push(o),lae(r,a,o);break}}continue}}const i=new Tz;if(i.line=t,e.children.push(i),t[0]==="#"&&t[1]==="d"){const n=t.replace(";","").split(" ");i.additionalDefineKey=n[1],n.length===3&&(i.additionalDefineValue=n[2])}}return!1}function EBe(r,e,t){const i=new Tz,n=new O2t;return n.lineIndex=-1,n.lines=r.split(` `),wue(n,i),i.process(e,t)}function TBe(r,e){var n;const t=r.defines,i={};for(const s of t){const o=s.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((n=r.processor)==null?void 0:n.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=r.version,i[r.platformName]="true",SBe(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function H2t(r,e,t){let i=W2t(r,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 n=e.defines,s=TBe(e,t);return e.processor.preProcessor&&(i=e.processor.preProcessor(i,n,s,e.isFragment,e.processingContext)),i=EBe(i,s,e),e.processor.postProcessor&&(i=e.processor.postProcessor(i,n,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function j2t(r,e,t){var a,o;let i=r;const n=e.defines,s=TBe(e,t);return(a=e.processor)!=null&&a.preProcessor&&(i=e.processor.preProcessor(i,n,s,e.isFragment,e.processingContext)),i=EBe(i,s,e),(o=e.processor)!=null&&o.postProcessor&&(i=e.processor.postProcessor(i,n,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Hk(r,e,t){fX.length=0;let i;for(;(i=U2t.exec(r))!==null;)fX.push(i);let n=String(r),s=[r],a=!1;for(const o of fX){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(z2t,""),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+=g.replace(gMe,m.toString())+` `}else e.supportsUniformBuffers||(c=c.replace(mMe,(d,f)=>f+"{X}")),c=c.replace(gMe,h)}const u=[];for(const h of s){const d=h.split(o[0]);for(let f=0;f=0||c.indexOf("#include <")>=0}else{const c=e.shadersRepository+"ShadersInclude/"+l+".fx";MBe.loadFile(c,u=>{e.includesShadersStore[l]=u,Hk(s.join(""),e,t)});return}}fX.length=0,n=s.join(""),a?Hk(n.toString(),e,t):t(n)}const MBe={loadFile:(r,e,t,i,n,s)=>{throw Ji("FileTools")}};class nw{static SetImmediate(e){dl()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class me{static GetShadersRepository(e=0){return e===0?me.ShadersRepository:me.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?me.ShadersStore:me.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?me.IncludesShadersStore:me.IncludesShadersStoreWGSL}}me.ShadersRepository="src/Shaders/";me.ShadersStore={};me.IncludesShadersStore={};me.ShadersRepositoryWGSL="src/ShadersWGSL/";me.ShadersStoreWGSL={};me.IncludesShadersStoreWGSL={};class RBe{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,n,s,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)=>{n[i[f]]=d}),this._uniforms=n;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],n=t.updateFlag;return i!==void 0&&i===n?!1:(this._valueCache[e]=n,!0)}_cacheFloat2(e,t,i){let n=this._valueCache[e];if(!n||n.length!==2)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s||s.length!==3)return s=[t,i,n],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==n&&(s[2]=n,a=!0),a}_cacheFloat4(e,t,i,n,s){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,n,s],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]!==n&&(a[2]=n,o=!0),a[3]!==s&&(a[3]=s,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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setInt4(this._uniforms[e],t,i,n,s)||(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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setUInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setUInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,n,s)||(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,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setFloat3(this._uniforms[e],t,i,n)||(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,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,n,s)||(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 Due=new WeakMap,$2t={_webGLVersion:2,cachedPipelines:{}};function up(r){let e=Due.get(r);if(!e){if(!r)return $2t;e={_webGLVersion:r.TEXTURE_BINDING_3D?2:1,_context:r,cachedPipelines:{}},Due.set(r,e)}return e}function X2t(r){Due.delete(r)}function IBe(r,e,t,i,n,s){const a=up(i);s||(s=a._createShaderProgramInjection??s1e);const o=Oue(e,"vertex",i,a._contextWasLost),l=Oue(t,"fragment",i,a._contextWasLost);return s(r,o,l,i,n,a.validateShaderPrograms)}function PBe(r,e,t,i,n,s=null,a){const o=up(n);a||(a=o._createShaderProgramInjection??s1e);const l=o._webGLVersion>1?`#version 300 es #define WEBGL2 `:"",c=_Me(e,"vertex",i,l,n,o._contextWasLost),u=_Me(t,"fragment",i,l,n,o._contextWasLost);return a(r,c,u,n,s,o.validateShaderPrograms)}function Y2t(r,e){const t=new RBe,i=up(r);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function s1e(r,e,t,i,n=null,s){const a=i.createProgram();if(r.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,e),i.attachShader(a,t),i.linkProgram(a),r.context=i,r.vertexShader=e,r.fragmentShader=t,r.isParallelCompiled||wBe(r,i,s),a}function wBe(r,e,t){const i=r.context,n=r.vertexShader,s=r.fragmentShader,a=r.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const c=e.getShaderInfoLog(n);if(c)throw r.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!e.getShaderParameter(s,e.COMPILE_STATUS)){const c=e.getShaderInfoLog(s);if(c)throw r.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}const l=i.getProgramInfoLog(a);if(l)throw r.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(a),!i.getProgramParameter(a,i.VALIDATE_STATUS))){const c=i.getProgramInfoLog(a);if(c)throw r.programValidationError=c,new Error(c)}i.deleteShader(n),i.deleteShader(s),r.vertexShader=void 0,r.fragmentShader=void 0,r.onCompiled&&(r.onCompiled(),r.onCompiled=void 0)}function Q2t(r,e,t,i,n,s,a,o,l,c="",u,h,d){const f=up(r.context);h||(h=f.createRawShaderProgramInjection??IBe),d||(d=f.createShaderProgramInjection??PBe);const p=r;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 _Me(r,e,t,i,n,s){return Oue(CBe(r,t,i),e,n,s)}function Oue(r,e,t,i){const n=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!n){let s=t.NO_ERROR,a=t.NO_ERROR;for(;(a=t.getError())!==t.NO_ERROR;)s=a;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${s}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(n,r),t.compileShader(n),n}function Z2t(r,e){e.useProgram(r)}function q2t(r,e){const t=r;if(!t.isParallelCompiled){e(r);return}const i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(r)}}function J2t(r,e){return up(e).cachedPipelines[r]}function a1e(r){const e=r._name,t=r.context;if(e&&t){const i=up(t),n=i.cachedPipelines[e];n==null||n.dispose(),delete i.cachedPipelines[e]}}function evt(r,e,t,i,n,s,a){let o,l;const c=dl()?s==null?void 0:s.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]){r.isFragment=!0;const[d,f]=u;dZ(f,r,(p,g)=>{a&&(a._fragmentSourceCodeBeforeMigration=g),t&&(p=t("fragment",p));const m=n1e(d,p,r);r=null;const _=tvt(m.vertexCode,m.fragmentCode,e,n);i==null||i(_.vertexSourceCode,_.fragmentSourceCode)},s)}};vMe(o,"Vertex","",d=>{r1e(r),dZ(d,r,(f,p)=>{a&&(a._rawVertexSourceCode=d,a._vertexSourceCodeBeforeMigration=p),t&&(f=t("vertex",f)),u[0]=f,h()},s)},n),vMe(l,"Fragment","Pixel",d=>{a&&(a._rawFragmentSourceCode=d),u[1]=d,h()},n)}function vMe(r,e,t,i,n,s){if(typeof HTMLElement<"u"&&r instanceof HTMLElement){const l=Az(r);i(l);return}if(r.substr(0,7)==="source:"){i(r.substr(7));return}if(r.substr(0,7)==="base64:"){const l=window.atob(r.substr(7));i(l);return}const a=me.GetShadersStore(n);if(a[r+e+"Shader"]){i(a[r+e+"Shader"]);return}if(t&&a[r+t+"Shader"]){i(a[r+t+"Shader"]);return}let o;if(r[0]==="."||r[0]==="/"||r.indexOf("http")>-1?o=r:o=me.GetShadersRepository(n)+r,s=s||ABe,!s)throw new Error("loadFileInjection is not defined");s(o+"."+e.toLowerCase()+".fx",i)}function tvt(r,e,t,i){if(t){const n=t.vertexElement||t.vertex||t.spectorName||t,s=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+n+` `+r,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+s+` `+e}}else return{vertexSourceCode:r,fragmentSourceCode:e}}const ivt=(r,e,t,i)=>{try{const n=r.existingPipelineContext||e(r.shaderProcessingContext);if(n._name=r.name,r.name&&r.context){const s=up(r.context);s.cachedPipelines[r.name]=n}return t(n,r.vertex,r.fragment,!!r.createAsRaw,"","",r.rebuildRebind,r.defines,r.transformFeedbackVaryings,"",()=>{i(n,()=>{var s;(s=r.onRenderingStateCompiled)==null||s.call(r,n)})}),n}catch(n){throw ge.Error("Error compiling effect"),n}};class Sr{static get ShadersRepository(){return me.ShadersRepository}static set ShadersRepository(e){me.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new Ce),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,n=null,s,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 Ce,this.onErrorObservable=new Ce,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 g;if(t.attributes){const m=t;if(this._engine=i,this._attributesNames=m.attributes,this._uniformsNames=m.uniformsNames.concat(m.samplers),this._samplerList=m.samplers.slice(),this.defines=m.defines,this.onError=m.onError,this.onCompiled=m.onCompiled,this._fallbacks=m.fallbacks,this._indexParameters=m.indexParameters,this._transformFeedbackVaryings=m.transformFeedbackVaryings||null,this._multiTarget=!!m.multiTarget,this._shaderLanguage=m.shaderLanguage??0,m.uniformBuffersNames){this._uniformBuffersNamesList=m.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,n){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(s,a)=>{n&&n(a)},this.onCompiled=()=>{var a,o;const s=this.getEngine().scenes;if(s)for(let l=0;lthis._rebuildProgram(l,c,u,h),defines:n,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 n=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let s=null;if(t&&e){const a=t.match(n);if(a&&a.length===2){const o=parseInt(a[1]),l=e.split(` `,-1);l.length>=o&&(s=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var a,o,l;this._compilationError=e.message;const i=this._attributesNames,n=this._fallbacks;if(ge.Error("Unable to compile effect:"),ge.Error("Uniforms: "+this._uniformsNames.map(function(c){return" "+c})),ge.Error("Attributes: "+i.map(function(c){return" "+c})),ge.Error(`Defines: `+this.defines),Sr.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&&(ge.Error("Vertex code:"),ge.Error(h))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([h,u]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),h&&(ge.Error("Fragment code:"),ge.Error(h))),c&&ge.Error(c),u&&ge.Error(u)}ge.Error("Error: "+this._compilationError);const s=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,s()),n?(this._pipelineContext=null,n.hasMoreFallbacks?(this._allFallbacksProcessed=!1,ge.Error("Trying next fallback."),this.defines=n.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,s(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||s())}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 n=this._samplerList.indexOf(e);for(let a=1;a0)&&(this._pipelineContext&&a1e(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0)}static RegisterShader(e,t,i,n=0){t&&(me.GetShadersStore(n)[`${e}PixelShader`]=t),i&&(me.GetShadersStore(n)[`${e}VertexShader`]=i)}static ResetCache(){Sr._BaseCache={}}}Sr.LogShaderCodeOnCompilationError=!0;Sr._UniqueIdSeed=0;Sr._BaseCache={};Sr.ShadersStore=me.ShadersStore;Sr.IncludesShadersStore=me.IncludesShadersStore;class o1e{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 l1e{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 d_{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=d_.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=d_.KEEP,this.opDepthFail=d_.KEEP,this.opStencilDepthPass=d_.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}}d_.ALWAYS=519;d_.KEEP=7680;d_.REPLACE=7681;class DBe{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,n){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===n||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=n,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,n){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===n||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=n,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 c1e{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,n=1,s=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=s,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 Lue;(function(r){r[r.Unknown=0]="Unknown",r[r.Url=1]="Url",r[r.Temp=2]="Temp",r[r.Raw=3]="Raw",r[r.Dynamic=4]="Dynamic",r[r.RenderTarget=5]="RenderTarget",r[r.MultiRenderTarget=6]="MultiRenderTarget",r[r.Cube=7]="Cube",r[r.CubeRaw=8]="CubeRaw",r[r.CubePrefiltered=9]="CubePrefiltered",r[r.Raw3D=10]="Raw3D",r[r.Raw2DArray=11]="Raw2DArray",r[r.DepthStencil=12]="DepthStencil",r[r.CubeRawRGBD=13]="CubeRawRGBD",r[r.Depth=14]="Depth"})(Lue||(Lue={}));class _n extends c1e{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 Ce,this.onErrorObservable=new Ce,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=_n._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=n=>{n._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 s;(s=this._hardwareTexture)==null||s.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 n=i.indexOf(this);n!==-1&&i.splice(n,1),n=i.indexOf(e),n===-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)}}_n._Counter=0;const rvt="modulepreload",nvt=function(r){return"/view/"+r},yMe={},je=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));n=Promise.all(t.map(o=>{if(o=nvt(o),o in yMe)return;yMe[o]=!0;const l=o.endsWith(".css"),c=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${c}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":rvt,l||(u.as="script",u.crossOrigin=""),u.href=o,a&&u.setAttribute("nonce",a),document.head.appendChild(u),l)return new Promise((h,d)=>{u.addEventListener("load",h),u.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${o}`)))})}))}return n.then(()=>e()).catch(s=>{const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s})};function LJ(r,e){return r.endsWith(".dds")?je(()=>Promise.resolve().then(()=>Cxt),void 0).then(t=>new t._DDSTextureLoader):r.endsWith(".basis")?je(()=>Promise.resolve().then(()=>lMt),void 0).then(t=>new t._BasisTextureLoader):r.endsWith(".env")?je(()=>Promise.resolve().then(()=>Axt),void 0).then(t=>new t._ENVTextureLoader):r.endsWith(".hdr")?je(()=>Promise.resolve().then(()=>JTt),void 0).then(t=>new t._HDRTextureLoader):r.endsWith(".ktx")||r.endsWith(".ktx2")||e==="image/ktx"||e==="image/ktx2"?je(()=>Promise.resolve().then(()=>Mxt),void 0).then(t=>new t._KTXTextureLoader):r.endsWith(".tga")?je(()=>Promise.resolve().then(()=>qTt),void 0).then(t=>new t._TGATextureLoader):r.endsWith(".exr")?je(()=>Promise.resolve().then(()=>DMt),void 0).then(t=>new t._ExrTextureLoader):null}function u1e(r,e){if(dl()){const{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(r)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(r);return setTimeout(r,16)}class Qe{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()}Sr.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(){ge.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,n=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=n,this._stencilState.stencilTest=s,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,dl()){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(C).toLowerCase():"");A.indexOf("?")>-1&&(A=A.split("?")[0]);const P=LJ(A,p);n&&n.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=s,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!m,t),this._doNotHandleContextLost||(x._buffer=u);let w=null;a&&!h&&(w=x.onLoadedObservable.add(a)),h||this._internalTexturesCache.push(x);const M=(R,I)=>{n&&n.removePendingData(x),e===b?(w&&x.onLoadedObservable.remove(w),ei.UseFallbackTexture&&e!==ei.FallbackTexture&&this._createTextureBase(ei.FallbackTexture,t,x.invertY,n,s,null,o,l,c,u,x),R=(R||"Unknown error")+(ei.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:R,exception:I}),o&&o(R,I)):(ge.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,n,s,a,o,l,c,u,x,d,f,p,g,m))};if(P){const R=async I=>{(await P).loadData(I,x,(k,z,W,K,U,j)=>{j?M("TextureLoader failed to load data"):l(x,A,n,{width:k,height:z},x.invertY,!W,K,()=>(U(),!1),s)},g)};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,n?n.offlineProvider:void 0,!0,(I,D)=>{M("Unable to load "+(I&&I.responseURL,D))})}else{const R=I=>{y&&!this._doNotHandleContextLost&&(x._buffer=I),l(x,A,n,I,x.invertY,t,!1,c,s)};!_||v?u&&(typeof u.decoding=="string"||u.close)?R(u):Qe._FileToolsLoadImage(e||"",R,M,n?n.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof u=="string"||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob?Qe._FileToolsLoadImage(u,R,M,n?n.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:OS()?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.23.0"}static get Version(){return"7.23.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 o1e,this._stencilStateComposer=new l1e,this._stencilState=new d_,this._alphaState=new DBe,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 Ce,this.onCanvasFocusObservable=new Ce,this.onNewSceneAddedObservable=new Ce,this.onResizeObservable=new Ce,this.onCanvasPointerOutObservable=new Ce,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 Ce,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new Ce,this.onAfterShaderCompilationObservable=new Ce,this.onBeginFrameObservable=new Ce,this.onEndFrameObservable=new Ce,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new Ce,this.onContextRestoredObservable=new Ce,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 Ce,ei.Instances.push(this),this.startTime=hn.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,jl.SetMatrixPrecision(!!t.useHighPrecisionMatrix),ex()&&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 n=dl()&&window.devicePixelRatio||1,s=t.limitDeviceRatio||n;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(s,n):1,this._lastDevicePixelRatio=n,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const n=dl()&&window.devicePixelRatio||1,s=this._lastDevicePixelRatio/n;this._lastDevicePixelRatio=n,this._hardwareScalingLevel*=s}if(dl()&&OS())if(this._renderingCanvas){const n=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||n.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||n.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 n=0;n{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&OS()&&"ontouchend"in document},this._checkForMobile(),dl()&&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 Qe._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,n,s,a){throw Ji("FileTools")}_loadFile(e,t,i,n,s,a){const o=ABe(e,t,i,n,s,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,n,s,a){if(hZ.loadFile)return hZ.loadFile(e,t,i,n,s,a);throw Ji("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),Sr.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(),dl()&&window.removeEventListener("resize",this._checkForMobile);const e=ei.Instances.indexOf(this);e>=0&&ei.Instances.splice(e,1),ei.Instances.length||(ei.OnEnginesDisposedObservable.notifyObservers(this),ei.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Ji("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i(r=r.replace(/#/gm,"%23"),r),ho={DefaultRetryStrategy:vBe.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:r=>r,ScriptBaseUrl:"",ScriptPreprocessUrl:r=>r,CleanUrl:svt},FJ=(r,e)=>{if(!(r&&r.indexOf("data:")===0)&&ho.CorsBehavior)if(typeof ho.CorsBehavior=="string"||ho.CorsBehavior instanceof String)e.crossOrigin=ho.CorsBehavior;else{const t=ho.CorsBehavior(r);t&&(e.crossOrigin=t)}},Nue={getRequiredSize:null},qw=(r,e,t,i,n="",s)=>{const a=ei.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;r instanceof ArrayBuffer||ArrayBuffer.isView(r)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([r],{type:n})),l=!0):o=`data:${n};base64,`+Sz(r):r instanceof Blob?(o=URL.createObjectURL(r),l=!0):(o=ho.CleanUrl(r),o=ho.PreprocessUrl(o));const c=b=>{if(t){const C=o||r.toString();t(`Error while trying to load image: ${C.indexOf("http")===0||C.length<=128?C:C.slice(0,128)+"..."}`,b)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return s3(o,b=>{a.createImageBitmap(new Blob([b],{type:n}),{premultiplyAlpha:"none",...s}).then(C=>{e(C),l&&URL.revokeObjectURL(o)}).catch(C=>{t&&t("Error while trying to load image: "+r,C)})},void 0,i||void 0,!0,(b,C)=>{c(C)}),null;const u=new Image;if(Nue.getRequiredSize){const b=Nue.getRequiredSize(r);b.width&&(u.width=b.width),b.height&&(u.height=b.height)}FJ(o,u);const h=[],d=()=>{h.forEach(b=>{b.target.addEventListener(b.name,b.handler)})},f=()=>{h.forEach(b=>{b.target.removeEventListener(b.name,b.handler)}),h.length=0},p=()=>{f(),e(u),l&&u.src&&URL.revokeObjectURL(u.src)},g=b=>{f(),c(b),l&&u.src&&URL.revokeObjectURL(u.src)},m=b=>{if(b.blockedURI!==u.src||b.disposition==="report")return;f();const C=new Error(`CSP violation of policy ${b.effectiveDirective} ${b.blockedURI}. Current policy is ${b.originalPolicy}`);ei.UseFallbackTexture=!1,c(C),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""};h.push({target:u,name:"load",handler:p}),h.push({target:u,name:"error",handler:g}),h.push({target:document,name:"securitypolicyviolation",handler:m}),d();const _=o.substring(0,5)==="blob:",y=o.substring(0,5)==="data:",v=()=>{_||y||!oa.IsCustomRequestAvailable?u.src=o:s3(o,(b,C,A)=>{const E=!n&&A?A:n,P=new Blob([b],{type:E}),w=URL.createObjectURL(P);l=!0,u.src=w},void 0,i||void 0,!0,(b,C)=>{c(C)})},x=()=>{i&&i.loadImage(o,u)};if(!_&&!y&&i&&i.enableTexturesOffline)i.open(x,v);else{if(o.indexOf("file:")!==-1){const b=decodeURIComponent(o.substring(5).toLowerCase());if(LS.FilesToLoad[b]&&typeof URL<"u"){try{let C;try{C=URL.createObjectURL(LS.FilesToLoad[b])}catch{C=URL.createObjectURL(LS.FilesToLoad[b])}u.src=C,l=!0}catch{u.src=""}return u}}v()}return u},aw=(r,e,t,i,n)=>{const s=new FileReader,a={onCompleteObservable:new Ce,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),n&&(s.onerror=()=>{n(new NJ(`Unable to read ${r.name}`,r))}),s.onload=o=>{e(o.target.result)},t&&(s.onprogress=t),i?s.readAsArrayBuffer(r):s.readAsText(r),a},s3=(r,e,t,i,n,s,a)=>{if(r.name)return aw(r,e,t,n,s?u=>{s(void 0,u)}:void 0);const o=r;if(o.indexOf("file:")!==-1){let u=decodeURIComponent(o.substring(5).toLowerCase());u.indexOf("./")===0&&(u=u.substring(2));const h=LS.FilesToLoad[u];if(h)return aw(h,e,t,n,s?d=>s(void 0,new sw(d.message,d.file)):void 0)}const{match:l,type:c}=LBe(o);if(l){const u={onCompleteObservable:new Ce,abort:()=>()=>{}};try{const h=n?Jw(o):d1e(o);e(h,void 0,c)}catch(h){s?s(void 0,h):ge.Error(h.message||"Failed to parse the Data URL")}return nw.SetImmediate(()=>{u.onCompleteObservable.notifyObservers(u)}),u}return BJ(o,(u,h)=>{e(u,h==null?void 0:h.responseURL,h==null?void 0:h.getResponseHeader("content-type"))},t,i,n,s?u=>{s(u.request,new sw(u.message,u.request))}:void 0,a)},BJ=(r,e,t,i,n,s,a)=>{r=ho.CleanUrl(r),r=ho.PreprocessUrl(r);const o=ho.BaseUrl+r;let l=!1;const c={onCompleteObservable:new Ce,abort:()=>l=!0},u=()=>{let h=new oa,d=null,f;const p=()=>{h&&(t&&h.removeEventListener("progress",t),f&&h.removeEventListener("readystatechange",f),h.removeEventListener("loadend",g))};let g=()=>{p(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,f=null,g=null,s=void 0,a=void 0,e=void 0};c.abort=()=>{l=!0,g&&g(),h&&h.readyState!==(XMLHttpRequest.DONE||4)&&h.abort(),d!==null&&(clearTimeout(d),d=null),h=null};const m=y=>{const v=y.message||"Unknown error";s&&h?s(new jk(v,h)):ge.Error(v)},_=y=>{if(h){if(h.open("GET",o),a)try{a(h)}catch(v){m(v);return}n&&(h.responseType="arraybuffer"),t&&h.addEventListener("progress",t),g&&h.addEventListener("loadend",g),f=()=>{if(!(l||!h)&&h.readyState===(XMLHttpRequest.DONE||4)){if(f&&h.removeEventListener("readystatechange",f),h.status>=200&&h.status<300||h.status===0&&(!dl()||h1e())){try{e&&e(n?h.response:h.responseText,h)}catch(b){m(b)}return}const v=ho.DefaultRetryStrategy;if(v){const b=v(o,h,y);if(b!==-1){p(),h=new oa,d=setTimeout(()=>_(y+1),b);return}}const x=new jk("Error status: "+h.status+" "+h.statusText+" - Unable to load "+o,h);s&&s(x)}},h.addEventListener("readystatechange",f),h.send()}};_(0)};if(i&&i.enableSceneOffline){const h=f=>{f&&f.status>400?s&&s(f):u()},d=()=>{i&&i.loadFile(ho.BaseUrl+r,f=>{!l&&e&&e(f),c.onCompleteObservable.notifyObservers(c)},t?f=>{!l&&t&&t(f)}:void 0,h,n)};i.open(d,h)}else u();return c},h1e=()=>typeof location<"u"&&location.protocol==="file:",Mz=r=>OBe.test(r),LBe=r=>{const e=OBe.exec(r);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function Jw(r){return Ez(r.split(",")[1])}const d1e=r=>OJ(r.split(",")[1]),avt=()=>{Qe._FileToolsLoadImage=qw,hZ.loadFile=s3,MBe.loadFile=s3};avt();let _P;const NBe=(r,e,t,i,n,s,a,o,l,c)=>{_P={DecodeBase64UrlToBinary:r,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:n,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(_P,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(u){t.DefaultRetryStrategy=u}}),Object.defineProperty(_P,"BaseUrl",{get:function(){return t.BaseUrl},set:function(u){t.BaseUrl=u}}),Object.defineProperty(_P,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(u){t.PreprocessUrl=u}}),Object.defineProperty(_P,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(u){t.CorsBehavior=u}})};NBe(Jw,d1e,ho,Mz,h1e,s3,qw,aw,BJ,FJ);class X9{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=Sa(e);if(t)return t;ge.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let n=window||this;for(let s=0,a=i.length;s{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}const ovt={RandomId:Xh};function $k(r){let e=1;do e*=2;while(er-t?t:e}function BBe(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}function f1e(r){return r=r|r>>1,r=r|r>>2,r=r|r>>4,r=r|r>>8,r=r|r>>16,r-(r>>1)}function Ld(r,e,t=2){let i;switch(t){case 1:i=f1e(r);break;case 2:i=FBe(r);break;case 3:default:i=BBe(r);break}return Math.min(i,e)}class Ie{static get BaseUrl(){return ho.BaseUrl}static set BaseUrl(e){ho.BaseUrl=e}static get CleanUrl(){return ho.CleanUrl}static set CleanUrl(e){ho.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("://"){s3(e,s=>{i(s)},void 0,void 0,t,(s,a)=>{n(a)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ie.ScriptBaseUrl&&e.startsWith(Ie._DefaultCdnUrl)){const i=Ie.ScriptBaseUrl[Ie.ScriptBaseUrl.length-1]==="/"?Ie.ScriptBaseUrl.substring(0,Ie.ScriptBaseUrl.length-1):Ie.ScriptBaseUrl;e=e.replace(Ie._DefaultCdnUrl,i)}return e=Ie.ScriptPreprocessUrl(e),t&&(e=Ie.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,n){e=Ie.GetBabylonScriptURL(e),Ie.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ie.GetBabylonScriptURL(e),Ie.LoadScriptAsync(e)}static LoadScript(e,t,i,n){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i(`Unable to load script '${e}' in worker`,o)}return}else if(!dl()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const s=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),n&&(a.id=n),a.onload=()=>{t&&t()},a.onerror=o=>{i&&i(`Unable to load script '${e}'`,o)},s.appendChild(a)}static LoadScriptAsync(e,t){return new Promise((i,n)=>{this.LoadScript(e,()=>{i()},(s,a)=>{n(a||new Error(s))},t)})}static ReadFileAsDataURL(e,t,i){const n=new FileReader,s={onCompleteObservable:new Ce,abort:()=>n.abort()};return n.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},n.onload=a=>{t(a.target.result)},n.onprogress=i,n.readAsDataURL(e),s}static ReadFile(e,t,i,n,s){return aw(e,t,i,n,s)}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,n){bc.DeepCopy(e,t,i,n)}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(s)):e.toBlob(function(s){t(s)},i,n)}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"}Ie.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),n=window.open("");if(!n)return;const s=n.document.createElement("img");s.onload=function(){URL.revokeObjectURL(i)},s.src=i,n.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",n,s){if(typeof n=="string"||!t)this.ToBlob(e,function(a){a&&Ie.DownloadBlob(a,n),t&&t("")},i,s);else if(t){if(Ie._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const c=l.result;t(c)}});return}const a=e.toDataURL(i,s);t(a)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),n=document.createElement("a");document.body.appendChild(n),n.style.display="none",n.href=i,n.download=t,n.addEventListener("click",()=>{n.parentElement&&n.parentElement.removeChild(n)}),n.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,n,s="image/png",a=!1,o){throw Ji("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png",s){throw Ji("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,s="image/png",a=1,o=!1,l,c=!1,u=!1,h=!0,d){throw Ji("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",s=1,a=!1,o,l=!1,c=!1,u=!0,h){throw Ji("ScreenshotTools")}static RandomId(){return Xh()}static IsBase64(e){return Mz(e)}static DecodeBase64(e){return Jw(e)}static get errorsCount(){return ge.errorsCount}static Log(e){ge.Log(e)}static Warn(e){ge.Warn(e)}static Error(e){ge.Error(e)}static get LogCache(){return ge.LogCache}static ClearLogCache(){ge.ClearLogCache()}static set LogLevels(e){ge.LogLevels=e}static set PerformanceLogLevel(e){if((e&Ie.PerformanceUserMarkLogLevel)===Ie.PerformanceUserMarkLogLevel){Ie.StartPerformanceCounter=Ie._StartUserMark,Ie.EndPerformanceCounter=Ie._EndUserMark;return}if((e&Ie.PerformanceConsoleLogLevel)===Ie.PerformanceConsoleLogLevel){Ie.StartPerformanceCounter=Ie._StartPerformanceConsole,Ie.EndPerformanceCounter=Ie._EndPerformanceConsole;return}Ie.StartPerformanceCounter=Ie._StartPerformanceCounterDisabled,Ie.EndPerformanceCounter=Ie._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ie._Performance){if(!dl())return;Ie._Performance=window.performance}!t||!Ie._Performance.mark||Ie._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!Ie._Performance.mark||(Ie._Performance.mark(e+"-End"),Ie._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ie._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ie._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return hn.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,n=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,n=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(n!=null?n+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return ex()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}Ie.UseCustomRequestHeaders=!1;Ie.CustomRequestHeaders=oa.CustomRequestHeaders;Ie.GetDOMTextContent=Az;Ie._DefaultCdnUrl="https://cdn.babylonjs.com";Ie.GetAbsoluteUrl=typeof document=="object"?r=>{const e=document.createElement("a");return e.href=r,e.href}:typeof URL=="function"&&typeof location=="object"?r=>new URL(r,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};Ie.NoneLogLevel=ge.NoneLogLevel;Ie.MessageLogLevel=ge.MessageLogLevel;Ie.WarningLogLevel=ge.WarningLogLevel;Ie.ErrorLogLevel=ge.ErrorLogLevel;Ie.AllLogLevel=ge.AllLogLevel;Ie.IsWindowObjectExist=dl;Ie.PerformanceNoneLogLevel=0;Ie.PerformanceUserMarkLogLevel=1;Ie.PerformanceConsoleLogLevel=2;Ie.StartPerformanceCounter=Ie._StartPerformanceCounterDisabled;Ie.EndPerformanceCounter=Ie._EndPerformanceCounterDisabled;function lvt(r,e){return t=>{t.__bjsclassName__=r,t.__bjsmoduleName__=e??null}}class lp{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(c),s&&s()){o.breakLoop();break}}o.executeNext()},a)},n)}}Ie.Mix=Fue;Ie.IsExponentOfTwo=$k;ei.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 Go{constructor(e){this.length=0,this.data=new Array(e),this._id=Go._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}}Go._GlobalId=0;class yv extends Go{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],n=e(t,i);if(n)return n}return null}}function kBe(r){r.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class aa{constructor(){this._dirty=!0,this._tempColor=new at(0,0,0,0),this._globalCurve=new at(0,0,0,0),this._highlightsCurve=new at(0,0,0,0),this._midtonesCurve=new at(0,0,0,0),this._shadowsCurve=new at(0,0,0,0),this._positiveCurve=new at(0,0,0,0),this._negativeCurve=new at(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",n="vCameraColorCurveNeutral",s="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(n,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,n,s){e!=null&&(e=aa._Clamp(e,0,360),t=aa._Clamp(t,-100,100),i=aa._Clamp(i,-100,100),n=aa._Clamp(n,-100,100),t=aa._ApplyColorGradingSliderNonlinear(t),t*=.5,n=aa._ApplyColorGradingSliderNonlinear(n),t<0&&(t*=-1,e=(e+180)%360),aa._FromHSBToRef(e,t,50+.25*n,s),s.scaleToRef(2,s),s.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,n){let s=aa._Clamp(e,0,360);const a=aa._Clamp(t/100,0,1),o=aa._Clamp(i/100,0,1);if(a===0)n.r=o,n.g=o,n.b=o;else{s/=60;const l=Math.floor(s),c=s-l,u=o*(1-a),h=o*(1-a*c),d=o*(1-a*(1-c));switch(l){case 0:n.r=o,n.g=d,n.b=u;break;case 1:n.r=h,n.g=o,n.b=u;break;case 2:n.r=u,n.g=o,n.b=d;break;case 3:n.r=u,n.g=h,n.b=o;break;case 4:n.r=d,n.g=u,n.b=o;break;default:n.r=o,n.g=u,n.b=h;break}}n.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return ot.Clone(()=>new aa,this)}serialize(){return ot.Serialize(this)}static Parse(e){return ot.Parse(()=>new aa,e,null,null)}}aa.PrepareUniforms=kBe;V([Q()],aa.prototype,"_globalHue",void 0);V([Q()],aa.prototype,"_globalDensity",void 0);V([Q()],aa.prototype,"_globalSaturation",void 0);V([Q()],aa.prototype,"_globalExposure",void 0);V([Q()],aa.prototype,"_highlightsHue",void 0);V([Q()],aa.prototype,"_highlightsDensity",void 0);V([Q()],aa.prototype,"_highlightsSaturation",void 0);V([Q()],aa.prototype,"_highlightsExposure",void 0);V([Q()],aa.prototype,"_midtonesHue",void 0);V([Q()],aa.prototype,"_midtonesDensity",void 0);V([Q()],aa.prototype,"_midtonesSaturation",void 0);V([Q()],aa.prototype,"_midtonesExposure",void 0);ot._ColorCurvesParser=aa.Parse;function UBe(r,e){e.EXPOSURE&&r.push("exposureLinear"),e.CONTRAST&&r.push("contrast"),e.COLORGRADING&&r.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&r.push("vInverseScreenSize"),e.VIGNETTE&&(r.push("vignetteSettings1"),r.push("vignetteSettings2")),e.COLORCURVES&&kBe(r),e.DITHER&&r.push("ditherIntensity")}function zBe(r,e){e.COLORGRADING&&r.push("txColorTransform")}class Gr{constructor(){this.colorCurves=new aa,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Gr.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new at(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Gr.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new Ce}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===Gr._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case Gr.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Gr.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&&aa.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,n),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=t??n/i;let a=Math.tan(this.vignetteCameraFov*.5),o=a*s;const l=Math.sqrt(o*a);o=Fue(o,l,this.vignetteStretch),a=Fue(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 ot.Clone(()=>new Gr,this)}serialize(){return ot.Serialize(this)}static Parse(e){const t=ot.Parse(()=>new Gr,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}}Gr.TONEMAPPING_STANDARD=0;Gr.TONEMAPPING_ACES=1;Gr.TONEMAPPING_KHR_PBR_NEUTRAL=2;Gr.PrepareUniforms=UBe;Gr.PrepareSamplers=zBe;Gr._VIGNETTEMODE_MULTIPLY=0;Gr._VIGNETTEMODE_OPAQUE=1;V([fBe()],Gr.prototype,"colorCurves",void 0);V([Q()],Gr.prototype,"_colorCurvesEnabled",void 0);V([ki("colorGradingTexture")],Gr.prototype,"_colorGradingTexture",void 0);V([Q()],Gr.prototype,"_colorGradingEnabled",void 0);V([Q()],Gr.prototype,"_colorGradingWithGreenDepth",void 0);V([Q()],Gr.prototype,"_colorGradingBGR",void 0);V([Q()],Gr.prototype,"_exposure",void 0);V([Q()],Gr.prototype,"_toneMappingEnabled",void 0);V([Q()],Gr.prototype,"_toneMappingType",void 0);V([Q()],Gr.prototype,"_contrast",void 0);V([Q()],Gr.prototype,"vignetteStretch",void 0);V([Q()],Gr.prototype,"vignetteCenterX",void 0);V([Q()],Gr.prototype,"vignetteCenterY",void 0);V([Q()],Gr.prototype,"vignetteWeight",void 0);V([Zw()],Gr.prototype,"vignetteColor",void 0);V([Q()],Gr.prototype,"vignetteCameraFov",void 0);V([Q()],Gr.prototype,"_vignetteBlendMode",void 0);V([Q()],Gr.prototype,"_vignetteEnabled",void 0);V([Q()],Gr.prototype,"_ditheringEnabled",void 0);V([Q()],Gr.prototype,"_ditheringIntensity",void 0);V([Q()],Gr.prototype,"_skipFinalColorClamp",void 0);V([Q()],Gr.prototype,"_applyByPostProcess",void 0);V([Q()],Gr.prototype,"_isEnabled",void 0);ot._ImageProcessingConfigurationParser=Gr.Parse;xe("BABYLON.ImageProcessingConfiguration",Gr);function kJ(r){return r.getPipelineContext===void 0}class cvt{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,n,s){if(s.drawBuffersExtensionDisabled){const a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}const uvt=/(flat\s)?\s*varying\s*.*/;class VBe{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return uvt.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const n=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#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(s,""),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,(n||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 mg{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=mg._Counter++}}mg._Counter=0;class ow extends mg{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class iT{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 hvt{}class ir extends Qe{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return Sr.ShadersRepository}static set ShadersRepository(e){Sr.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,n){if(i=i||{},super(t??i.antialias,i,n),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 s=null;if(e.getContext){if(s=e,this._renderingCanvas=s,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 ir.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,m=new RegExp(f).exec(l);if(m&&m.length>0&&parseInt(m[m.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,ge.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},s.addEventListener("webglcontextlost",this._onContextLost,!1),s.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=s.getContext("webgl2",i)||s.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(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.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 VBe:new cvt;const a=`Babylon.js v${ir.Version}`;ge.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a);const o=up(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,supportIBLShadows: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,n=!1){var o,l;const s=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=s;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?(ir._TempClearColorUint32[0]=e.r*255,ir._TempClearColorUint32[1]=e.g*255,ir._TempClearColorUint32[2]=e.b*255,ir._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,ir._TempClearColorUint32),c=!1):(ir._TempClearColorInt32[0]=e.r*255,ir._TempClearColorInt32[1]=e.g*255,ir._TempClearColorInt32[2]=e.b*255,ir._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,ir._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),n&&(this._gl.clearStencil(0),a|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(a)}_viewport(e,t,i,n){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||n!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,n,s,a=0,o=0){var h,d,f,p,g,m;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),l._currentLOD=a):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)&&ge.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,(g=u._hardwareTexture)==null?void 0:g.underlyingResource,a):c.framebufferTexture2D(c.FRAMEBUFFER,_,c.TEXTURE_2D,(m=u._hardwareTexture)==null?void 0:m.underlyingResource,a)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,n):(i||(i=e.width,a&&(i=i/Math.pow(2,a))),n||(n=e.height,a&&(n=n/Math.pow(2,a))),this._viewport(0,0,i,n)),this.wipeCaches()}setState(e,t=0,i,n=!1,s,a,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=this.cullBackFaces??s??!0?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const c=n?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 n=e;this._currentRenderTarget=null;const s=this._gl;if(n._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,n._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,n._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(a=e.texture)!=null&&a.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(n._MSAAFramebuffer&&this._bindUnboundFramebuffer(n._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 n=new ow(i);return this.bindArrayBuffer(n),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),n.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),n.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),n.capacity=e),this._resetVertexBufferBinding(),n.references=1,n}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const n=this._gl.createBuffer(),s=new ow(n);if(!n)throw new Error("Unable to create index buffer");this.bindIndexBuffer(s);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(),s.references=1,s.is32Bits=a.BYTES_PER_ELEMENT===4,s}_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 n=e.program,s=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,s,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,n,s,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!==n&&(l.type=n,c=!0),l.normalized!==s&&(l.normalized=s,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=n,l.normalized=s,l.stride=a,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),n===this._gl.UNSIGNED_INT||n===this._gl.INT?this._gl.vertexAttribIPointer(t,i,n,a,o):this._gl.vertexAttribPointer(t,i,n,s,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const n=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){const o=n[s];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,n){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,n),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,n,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const a=s.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,n,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,n){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,n)),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,ge.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,f=new _n(this,n),p=e.width||e,g=e.height||e,m=e.depth||0,_=e.layers||0,y=this._getSamplingParameters(o,s),v=_!==0?d.TEXTURE_2D_ARRAY:m!==0?d.TEXTURE_3D:d.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(a,l,c),b=this._getInternalFormat(l),C=this._getWebGLTextureType(a);return this._bindTextureDirectly(v,f),_!==0?(f.is2DArray=!0,d.texImage3D(v,0,x,p,g,_,0,b,C,null)):m!==0?(f.is3D=!0,d.texImage3D(v,0,x,p,g,m,0,b,C,null)):d.texImage2D(v,0,x,p,g,0,b,C,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),s&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),f._useSRGBBuffer=c,f.baseWidth=p,f.baseHeight=g,f.width=p,f.height=g,f.depth=_,f.isReady=!0,f.samples=u,f.generateMipMaps=s,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,n,s=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,g){return this._createTextureBase(e,t,i,n,s,a,o,(...m)=>this._prepareWebGLTexture(...m,u),(m,_,y,v,x,b)=>{const C=this._gl,A=y.width===m&&y.height===_;x._creationFlags=p??0;const E=this._getTexImageParametersForCreateTexture(x.format,x._useSRGBBuffer);if(A)return C.texImage2D(C.TEXTURE_2D,0,E.internalFormat,E.format,E.type,y),!1;const P=this._caps.maxTextureSize;if(y.width>P||y.height>P||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=m,this._workingCanvas.height=_,this._workingContext.drawImage(y,0,0,y.width,y.height,0,0,m,_),C.texImage2D(C.TEXTURE_2D,0,E.internalFormat,E.format,E.type,this._workingCanvas),x.width=m,x.height=_),!1;{const w=new _n(this,2);this._bindTextureDirectly(C.TEXTURE_2D,w,!0),C.texImage2D(C.TEXTURE_2D,0,E.internalFormat,E.format,E.type,y),this._rescaleTexture(w,x,n,E.format,()=>{this._releaseTexture(w),this._bindTextureDirectly(C.TEXTURE_2D,x,!0),b()})}return!0},l,c,u,h,d,f,g)}_getTexImageParametersForCreateTexture(e,t){let i,n;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),n=i):(i=this._getInternalFormat(e,!1),n=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:n,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,n,s){}_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 n=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(n,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(n,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(n)),this._bindTextureDirectly(n,null),t.samplingMode=e}updateTextureDimensions(e,t,i,n=1){}updateTextureWrappingMode(e,t,i=null,n=null){const s=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&n!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(n),e),e._cachedWrapR=n),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,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,n,0,s)}_uploadDataToTextureDirectly(e,t,i=0,n=0,s,a=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),u=s===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,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-n,0)),g=a?e.height:Math.pow(2,Math.max(f-n,0));o.texImage2D(h,n,u,p,g,0,c,l,t)}updateTextureData(e,t,i,n,s,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,n,s,a,d,h,t),c&&this._gl.generateMipmap(p),this._bindTextureDirectly(f,null)}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){const s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,n,s){const a=this._gl;if(!a)return;const o=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!n&&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,n,s,a,o,l,c,u){const h=this.getCaps().maxTextureSize,d=Math.min(h,this.needPOTTextures?Ld(n.width,h):n.width),f=Math.min(h,this.needPOTTextures?Ld(n.height,h):n.height),p=this._gl;if(p){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(s===void 0?!0:!!s),e.baseWidth=n.width,e.baseHeight=n.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,n,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,c)})&&this._prepareWebGLTextureContinuation(e,i,a,o,c)}}_setupFramebufferDepthAttachments(e,t,i,n,s=1){const a=this._gl;if(e&&t)return this._createRenderBuffer(i,n,s,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,n,s,o,o,a.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,n,s,a.STENCIL_INDEX8,a.STENCIL_INDEX8,a.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,n,s,a,o=!0){const c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,n,s,a,o)}_updateRenderBuffer(e,t,i,n,s,a,o,l=!0){const c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),n>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,n,a,t,i):c.renderbufferStorage(c.RENDERBUFFER,s,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&&(Z2t(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let n=0;n-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||n){if(this._activateCurrentTexture(),t&&t.isMultiview)throw ge.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&&(s=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const n=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(n,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,n){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,n=!1,s=""){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;n?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,n){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let s=0;s=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;dl()&&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()),X2t(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 n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),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 s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,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(n),t.deleteFramebuffer(s),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,n,s=!0,a=!0){const o=s?4:3,l=s?this._gl.RGBA:this._gl.RGB,c=new Uint8Array(n*i*o);return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,n,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=Qe._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=Qe._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}}ir._TempClearColorUint32=new Uint32Array(4);ir._TempClearColorInt32=new Int32Array(4);ir.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"]}];ir._ConcatenateShader=CBe;ir._IsSupported=null;ir._HasMajorPerformanceCaveat=null;ir.prototype.createUniformBuffer=function(r,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new ow(t);return this.bindUniformBuffer(i),r instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,r,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(r),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};ir.prototype.createDynamicUniformBuffer=function(r,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new ow(t);return this.bindUniformBuffer(i),r instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,r,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(r),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};ir.prototype.updateUniformBuffer=function(r,e,t,i){this.bindUniformBuffer(r),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)};ir.prototype.bindUniformBuffer=function(r){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,r?r.underlyingResource:null)};ir.prototype.bindUniformBufferBase=function(r,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,r?r.underlyingResource:null)};ir.prototype.bindUniformBlock=function(r,e,t){const i=r.program,n=this._gl.getUniformBlockIndex(i,e);n!==4294967295&&this._gl.uniformBlockBinding(i,n,t)};class Ci{constructor(e,t,i,n,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=n??"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 n=this._uniformLocationPointer-i;for(let s=0;s0){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}n=[];for(let s=0;s1&&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&&(Ci._UpdatedUbosInFrame[this._name]||(Ci._UpdatedUbosInFrame[this._name]=0),Ci._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 n=this._uniformLocations[e];if(n===void 0){if(this._buffer){ge.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),n=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let s=0;s0){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}ge.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,n=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,n?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 ee{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,n,s,a,o,l,c,u,h=!1,d=!1,f=1,p=!1){this._isDisposed=!1;let g=!1;if(this.engine=e,typeof n=="object"&&n!==null?(g=n.updatable??!1,s=n.postponeInternalCreation,a=n.stride,o=n.instanced,l=n.offset,c=n.size,u=n.type,h=n.normalized??!1,d=n.useBytes??!1,f=n.divisor??1,p=n.takeBufferOwnership??!1,this._label=n.label):g=!!n,t instanceof fl?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new fl(e,t,g,a,s,o,d,f,this._label),this._ownsBuffer=!0),this.uniqueId=ee._Counter++,this._kind=i,u===void 0){const _=this.getData();this.type=_?ee.GetDataType(_):ee.FLOAT}else this.type=u;const m=ee.GetTypeByteLength(this.type);d?(this._size=c||(a?a/m:ee.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*m,this.byteOffset=l||0):(this._size=c||a||ee.DeduceStride(i),this.byteStride=a?a*m:this._buffer.byteStride||this._size*m,this.byteOffset=(l||0)*m),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?ee.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/ee.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/ee.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*ee.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){ee.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case ee.UVKind:case ee.UV2Kind:case ee.UV3Kind:case ee.UV4Kind:case ee.UV5Kind:case ee.UV6Kind:return 2;case ee.NormalKind:case ee.PositionKind:return 3;case ee.ColorKind:case ee.ColorInstanceKind:case ee.MatricesIndicesKind:case ee.MatricesIndicesExtraKind:case ee.MatricesWeightsKind:case ee.MatricesWeightsExtraKind:case ee.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?ee.BYTE:e instanceof Uint8Array?ee.UNSIGNED_BYTE:e instanceof Int16Array?ee.SHORT:e instanceof Uint16Array?ee.UNSIGNED_SHORT:e instanceof Int32Array?ee.INT:e instanceof Uint32Array?ee.UNSIGNED_INT:ee.FLOAT}static GetTypeByteLength(e){switch(e){case ee.BYTE:case ee.UNSIGNED_BYTE:return 1;case ee.SHORT:case ee.UNSIGNED_SHORT:return 2;case ee.INT:case ee.UNSIGNED_INT:case ee.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,s,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)||n!==0||e.length!==u)if(e instanceof Array){const h=n/4;return e.slice(h,h+u)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,n,u);{const h=e.byteOffset+n;if(h&3&&(ge.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}}ee._Counter=0;ee.BYTE=5120;ee.UNSIGNED_BYTE=5121;ee.SHORT=5122;ee.UNSIGNED_SHORT=5123;ee.INT=5124;ee.UNSIGNED_INT=5125;ee.FLOAT=5126;ee.PositionKind="position";ee.NormalKind="normal";ee.TangentKind="tangent";ee.UVKind="uv";ee.UV2Kind="uv2";ee.UV3Kind="uv3";ee.UV4Kind="uv4";ee.UV5Kind="uv5";ee.UV6Kind="uv6";ee.ColorKind="color";ee.ColorInstanceKind="instanceColor";ee.MatricesIndicesKind="matricesIndices";ee.MatricesWeightsKind="matricesWeights";ee.MatricesIndicesExtraKind="matricesIndicesExtra";ee.MatricesWeightsExtraKind="matricesWeightsExtra";class wl{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(ee.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let n;const s=oe.Vector3[0],a=oe.Vector3[1],o=oe.Vector3[2];if(t){const c=this.pickedMesh.getVerticesData(ee.NormalKind);let u=i?O.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?O.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?O.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),n=new O(u.x+h.x+d.x,u.y+h.y+d.y,u.z+h.z+d.z)}else{const c=this.pickedMesh.getVerticesData(ee.PositionKind),u=i?O.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?O.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?O.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);n=O.Cross(f,p)}const l=(c,u)=>{let h=c.getWorldMatrix();c.nonUniformScaling&&(oe.Matrix[0].copyFrom(h),h=oe.Matrix[0],h.setTranslationFromFloats(0,0,0),h.invert(),h.transposeToRef(oe.Matrix[1]),h=oe.Matrix[1]),O.TransformNormalToRef(u,h,u)};if(e&&l(this.pickedMesh,n),this.ray){const c=oe.Vector3[0].copyFrom(n);e||l(this.pickedMesh,c),O.Dot(c,this.ray.direction)>0&&n.negateInPlace()}return n.normalize(),n}getTextureCoordinates(e=ee.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 n=Ne.FromArray(i,t[this.faceId*3]*2),s=Ne.FromArray(i,t[this.faceId*3+1]*2),a=Ne.FromArray(i,t[this.faceId*3+2]*2);return n=n.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new Ne(n.x+s.x+a.x,n.y+s.y+a.y)}}class Xk{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new Ce,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[ee.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[ee.PositionKind]=new ee(this._scene.getEngine(),e,ee.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[ee.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(n=>n!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,n=0,s=0,a=!1){var l;const o=this._scene.getEngine();for(let c=0;cc!=null),n.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let c=0,u=n.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(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.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=dr.LeftClick&&i<=dr.RightClick&&(l.type=n===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,n,s,a){const o=this._CreateMouseEvent(e,t,i,n,s,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=rT.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case dr.MouseWheelX:o.deltaX=n;break;case dr.MouseWheelY:o.deltaY=n;break;case dr.MouseWheelZ:o.deltaZ=n;break}return o}static _CreateMouseEvent(e,t,i,n,s,a){const o=this._CreateEvent(a),l=s.pollInput(e,t,dr.Horizontal),c=s.pollInput(e,t,dr.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=s.pollInput(e,t,10),o.movementY=s.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,s),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,n){const s=this._CreateEvent(n);return this._CheckNonCharacterKeys(s,i),s.deviceType=ji.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=t===1?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(ji.Keyboard),n=i&&t.pollInput(ji.Keyboard,0,18)===1,s=i&&t.pollInput(ji.Keyboard,0,17)===1,a=i&&(t.pollInput(ji.Keyboard,0,91)===1||t.pollInput(ji.Keyboard,0,92)===1||t.pollInput(ji.Keyboard,0,93)===1),o=i&&t.pollInput(ji.Keyboard,0,16)===1;e.altKey=n,e.ctrlKey=s,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class dvt{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(n,s,a,o)=>{const l=lS.CreateDeviceEvent(n,s,a,o,this);i(n,s,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===ji.Mouse||e===ji.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const xMe=255,bMe=Object.keys(dr).length/2;class fvt{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ie.IsSafari(),this._usingMacOS=ex()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=s=>{},this._keyboardUpEvent=s=>{},this._keyboardBlurEvent=s=>{},this._pointerMoveEvent=s=>{},this._pointerDownEvent=s=>{},this._pointerUpEvent=s=>{},this._pointerCancelEvent=s=>{},this._pointerWheelEvent=s=>{},this._pointerBlurEvent=s=>{},this._pointerMacOSChromeOutEvent=s=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=ex()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=ex()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=s=>{},this._gamepadDisconnectedEvent=s=>{},this._eventPrefix=Ie.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=n,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 n=this._inputs[e][t];if(!n)throw`Unable to find device ${ji[e]}`;e>=ji.DualShock&&e<=ji.DualSense&&this._updateDevice(e,t,i);const s=n[i];if(s===void 0)throw`Unable to find input ${i} for device ${ji[e]} in slot ${t}`;return i===dr.Move&&Ie.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}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 n=+i,s=t[n];if(s)for(let a=0;a{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ji.Keyboard,0,xMe));const t=this._inputs[ji.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(ji.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(ji.Keyboard,0,xMe));const t=this._inputs[ji.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 n of this._metaKeys){const s=lS.CreateDeviceEvent(ji.Keyboard,0,n,0,this,this._elementToAttachTo);t[n]=0,this._onInputChanged(ji.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(ji.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[ji.Keyboard][0];for(let t=0;t{const n=this._getPointerType(i);let s=n===ji.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(n===ji.Touch&&s===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(n,s);else{Ie.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[n]||(this._inputs[n]={}),this._inputs[n][s]||this._addPointerDevice(n,s,i.clientX,i.clientY);const a=this._inputs[n][s];if(a){const o=i;o.inputIndex=dr.Move,a[dr.Horizontal]=i.clientX,a[dr.Vertical]=i.clientY,n===ji.Touch&&a[dr.LeftClick]===0&&(a[dr.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(n,s,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(n,s,o))}},this._pointerDownEvent=i=>{const n=this._getPointerType(i);let s=n===ji.Mouse?0:i.pointerId;if(n===ji.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)s=o,this._activeTouchIds[o]=i.pointerId;else{Ie.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[n]||(this._inputs[n]={}),this._inputs[n][s]?n===ji.Touch&&this._onDeviceConnected(n,s):this._addPointerDevice(n,s,i.clientX,i.clientY);const a=this._inputs[n][s];if(a){const o=a[dr.Horizontal],l=a[dr.Vertical];if(n===ji.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[dr.Horizontal]=i.clientX,a[dr.Vertical]=i.clientY,a[i.button+2]=1;const c=i;c.inputIndex=i.button+2,this._onInputChanged(n,s,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=dr.Move,this._onInputChanged(n,s,c))}},this._pointerUpEvent=i=>{var o,l,c,u,h;const n=this._getPointerType(i),s=n===ji.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(n===ji.Touch){if(s===-1)return;this._activeTouchIds[s]=-1}const a=(o=this._inputs[n])==null?void 0:o[s];if(a&&a[i.button+2]!==0){const d=a[dr.Horizontal],f=a[dr.Vertical];a[dr.Horizontal]=i.clientX,a[dr.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=dr.Move,this._onInputChanged(n,s,p)),p.inputIndex=i.button+2,n===ji.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(n,s,p),n===ji.Touch&&this._onDeviceDisconnected(n,s)}},this._pointerCancelEvent=i=>{var n,s,a,o;if(i.pointerType==="mouse"){const l=this._inputs[ji.Mouse][0];this._mouseId>=0&&((s=(n=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(n,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=dr.LeftClick;c<=dr.BrowserForward;c++)if(l[c]===1){l[c]=0;const u=lS.CreateDeviceEvent(ji.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(ji.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[ji.Touch][l][dr.LeftClick]=0;const c=lS.CreateDeviceEvent(ji.Touch,l,dr.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(ji.Touch,l,c),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(ji.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,n,s,a,o;if(this.isDeviceAvailable(ji.Mouse)){const l=this._inputs[ji.Mouse][0];this._mouseId>=0&&((n=(i=this._elementToAttachTo).hasPointerCapture)!=null&&n.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=dr.LeftClick;c<=dr.BrowserForward;c++)if(l[c]===1){l[c]=0;const u=lS.CreateDeviceEvent(ji.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(ji.Mouse,0,u)}}if(this.isDeviceAvailable(ji.Touch)){const l=this._inputs[ji.Touch];for(let c=0;c{const n=ji.Mouse,s=0;this._inputs[n]||(this._inputs[n]=[]),this._inputs[n][s]||(this._pointerActive=!0,this._registerDevice(n,s,bMe));const a=this._inputs[n][s];if(a){a[dr.MouseWheelX]=i.deltaX||0,a[dr.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[dr.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[dr.MouseWheelX]!==0&&(o.inputIndex=dr.MouseWheelX,this._onInputChanged(n,s,o)),a[dr.MouseWheelY]!==0&&(o.inputIndex=dr.MouseWheelY,this._onInputChanged(n,s,o)),a[dr.MouseWheelZ]!==0&&(o.inputIndex=dr.MouseWheelZ,this._onInputChanged(n,s,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(ji.Mouse)){const i=this._inputs[ji.Mouse][0];i[dr.MouseWheelX]=0,i[dr.MouseWheelY]=0,i[dr.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 n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=n.buttons.length?s[i]=n.axes[i-n.buttons.length].valueOf():s[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?ji.DualSense:ji.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?ji.Xbox:e.indexOf("057e")!==-1?ji.Switch:ji.Generic}_getPointerType(e){let t=ji.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=ji.Touch),t}}class Kue{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new Ce,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class pvt{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(ji).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 Kue(this._deviceInputSystem,a,o);l._addDevice(c)}},n=(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)},s=(a,o,l)=>{if(l)for(const c of this._registeredManagers)c._onInputChanged(a,o,l)};typeof _native<"u"?this._deviceInputSystem=new dvt(i,n,s):this._deviceInputSystem=new fvt(e,i,n,s)}dispose(){this._deviceInputSystem.dispose()}}class KBe{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(ji).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new pvt(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new Ce(i=>{for(const n of this._devices)if(n)for(const s of n)s&&this.onDeviceConnectedObservable.notifyObserver(i,s)}),this.onDeviceDisconnectedObservable=new Ce,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 n,s;const i=(n=this._devices[e])==null?void 0:n[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(s=this._devices[e])!=null&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var n,s;(s=(n=this._devices[e])==null?void 0:n[t])==null||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case ji.Keyboard:case ji.Mouse:this._firstDevice[e]=0;break;case ji.Touch:case ji.DualSense:case ji.DualShock:case ji.Xbox:case ji.Switch:case ji.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=dr.MouseWheelX&&t.inputIndex<=dr.MouseWheelZ?Wt.POINTERWHEEL:Wt.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new ap(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new ap(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,pe.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 n=this._scene,s=new WBe(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(s.nearInteractionPickingInfo=e)),n.onPrePointerObservable.notifyObservers(s,i),!!s.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 s=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(s.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=dr.Move,!this._checkPrePointerObservable(e,i,Wt.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Wt.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,Ca.CreateNew(e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,Ca.CreateNew(e.pickedMesh,t,e));break;case 1:a.processTrigger(4,Ca.CreateNew(e.pickedMesh,t,e));break;case 2:a.processTrigger(3,Ca.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>Uo.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,Ca.CreateNew(o.pickedMesh,t)))},Uo.LongPressDelay)}}else for(const a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n;const s=Wt.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),n=new ap(s,t,e),this._setRayOnPointerInfo(e,t)):n=new ap(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(n,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const n=new PointerEvent("pointerup",t);n.inputIndex=dr.Move;const s=new CMe;i?s.doubleClick=!0:s.singleClick=!0,!this._checkPrePointerObservable(e,n,Wt.POINTERUP)&&this._processPointerUp(e,n,s)}_processPointerUp(e,t,i){const n=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.observers.length>this._cameraObserverCount)){const a=Wt.POINTERPICK,o=new ap(a,t,e);this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(o,a)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,Ca.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,Ca.CreateNew(e.pickedMesh,t,e));const a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,Ca.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of n._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const s=this._pickedDownMesh._getActionManagerForTrigger(16);s&&s.processTrigger(16,Ca.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new ap(Wt.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),n.onPointerObservable.notifyObservers(s,Wt.POINTERUP),n.onPointerUp&&n.onPointerUp(t,e,Wt.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=Wt.POINTERTAP:i.doubleClick&&(a=Wt.POINTERDOUBLETAP),a){const o=new ap(a,t,e);n.onPointerObservable.hasObservers()&&n.onPointerObservable.hasSpecificMask(a)&&n.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,n=null){const s=this._scene,a=s.getEngine();n||(n=a.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new KBe(a),this._initActionManager=o=>{if(!this._meshPickProceed){const l=s.skipPointerUpPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.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>Uo.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=Wt.POINTERTAP,d=new ap(h,u,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(h)&&s.onPointerObservable.notifyObservers(d,h),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,u)=>{var g,m;const h=new CMe;this._currentPickResult=null;let d=null,f=o.hasSpecificMask(Wt.POINTERPICK)||l.hasSpecificMask(Wt.POINTERPICK)||o.hasSpecificMask(Wt.POINTERTAP)||l.hasSpecificMask(Wt.POINTERTAP)||o.hasSpecificMask(Wt.POINTERDOUBLETAP)||l.hasSpecificMask(Wt.POINTERDOUBLETAP);!f&&Rd&&(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=!Uo.ExclusiveDoubleClickMode;if(y||(y=!o.hasSpecificMask(Wt.POINTERDOUBLETAP)&&!l.hasSpecificMask(Wt.POINTERDOUBLETAP),y&&!Rd.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(y=!d.hasSpecificTrigger(6)))),y)(Date.now()-this._previousStartingPointerTime>Uo.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),Uo.DoubleClickDelay)};this._delayedClicks[_]=x}let v=o.hasSpecificMask(Wt.POINTERDOUBLETAP)||l.hasSpecificMask(Wt.POINTERDOUBLETAP);!v&&Rd.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)>Uo.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Uo.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=dr.MouseWheelX&&o.inputIndex<=dr.MouseWheelZ?Wt.POINTERWHEEL:Wt.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new wl,o);return}s.pointerMovePredicate||(s.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&c.layerMask)!==0));const l=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var c;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Uo.ExclusiveDoubleClickMode){for(let u=0;uu.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&u.layerMask)!==0)),this._pickedDownMesh=null;let l;s.skipPointerDownPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerDown?l=new wl:l=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),s.preventDefaultOnPointerUp&&n&&(o.preventDefault(),n.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,o,(l,c)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Wt.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&s.onPrePointerObservable.hasSpecificMask(Wt.POINTERTAP)&&this._checkPrePointerObservable(null,o,Wt.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&s.onPrePointerObservable.hasSpecificMask(Wt.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Wt.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),!(!s.cameraToUseForPointers&&!s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=u=>u.isPickable&&u.isVisible&&u.isReady()&&u.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&u.layerMask)!==0)),!this._meshPickProceed&&(Rd&&Rd.HasTriggers||this._checkForPicking()||s.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=Rg.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const c=new Bue(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const c=new pZ(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(14,Ca.CreateNewFromScene(s,o))},this._onKeyUp=o=>{const l=Rg.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const c=new Bue(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const c=new pZ(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(15,Ca.CreateNewFromScene(s,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===ji.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===dr.LeftClick||l.inputIndex===dr.MiddleClick||l.inputIndex===dr.RightClick||l.inputIndex===dr.BrowserBack||l.inputIndex===dr.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===dr.Move?this._onPointerMove(l):(l.inputIndex===dr.MouseWheelX||l.inputIndex===dr.MouseWheelY||l.inputIndex===dr.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===ji.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===dr.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===dr.Move&&this._onPointerMove(l)}):o.deviceType===ji.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,n){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let a;s&&(a=s._getActionManagerForTrigger(10),a&&a.processTrigger(10,Ca.CreateNew(s,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,Ca.CreateNew(e,n,{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]}}Uo.DragMovementThreshold=10;Uo.LongPressDelay=500;Uo.DoubleClickDelay=300;Uo.ExclusiveDoubleClickMode=!1;class zo{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){zo.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){zo.Enabled&&(this._startMonitoringTime=hn.Now)}endMonitoring(e=!0){if(!zo.Enabled)return;e&&this.fetchNewFrame();const t=hn.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=hn.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}zo.Enabled=!0;class Dc{constructor(e,t,i,n){this.normal=new O(e,t,i),this.d=n}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Dc(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=Dc._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,s=this.normal.y,a=this.normal.z,o=this.d,l=n*i[0]+s*i[1]+a*i[2]+o*i[3],c=n*i[4]+s*i[5]+a*i[6]+o*i[7],u=n*i[8]+s*i[9]+a*i[10]+o*i[11],h=n*i[12]+s*i[13]+a*i[14]+o*i[15];return new Dc(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 n=t.x-e.x,s=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=s*c-a*l,h=a*o-n*c,d=n*l-s*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 O.Dot(this.normal,e)<=t}signedDistanceTo(e){return O.Dot(e,this.normal)+this.d}static FromArray(e){return new Dc(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new Dc(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new Dc(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 n=-(t.x*e.x+t.y*e.y+t.z*e.z);return O.Dot(i,t)+n}}Dc._TmpMatrix=pe.Identity();class lf{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new Dc(0,0,0,0));return lf.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){lf.GetNearPlaneToRef(e,t[0]),lf.GetFarPlaneToRef(e,t[1]),lf.GetLeftPlaneToRef(e,t[2]),lf.GetRightPlaneToRef(e,t[3]),lf.GetTopPlaneToRef(e,t[4]),lf.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 Rz{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Rz._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 mvt{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Hue;(function(r){r[r.BackwardCompatible=0]="BackwardCompatible",r[r.Intermediate=1]="Intermediate",r[r.Aggressive=2]="Aggressive"})(Hue||(Hue={}));class Ut extends vo{static DefaultMaterialFactory(e){throw Ji("StandardMaterial")}static CollisionCoordinatorFactory(){throw Ji("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 Uo.DragMovementThreshold}static set DragMovementThreshold(e){Uo.DragMovementThreshold=e}static get LongPressDelay(){return Uo.LongPressDelay}static set LongPressDelay(e){Uo.LongPressDelay=e}static get DoubleClickDelay(){return Uo.DoubleClickDelay}static set DoubleClickDelay(e){Uo.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Uo.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Uo.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const n=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return oe.Vector4[0].set(n.x,n.y,n.z,s?-1:1),e&&(i?e.setFloat3(t,oe.Vector4[0].x,oe.Vector4[0].y,oe.Vector4[0].z):e.setVector4(t,oe.Vector4[0])),oe.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=JFe(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=Ut.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=Ut.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 Uo(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new at(.2,.2,.3,1),this.ambientColor=new Pe(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new Ce,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 Ce,this._onDisposeObserver=null,this.onBeforeRenderObservable=new Ce,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new Ce,this.onAfterRenderCameraObservable=new Ce,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new Ce,this.onAfterAnimationsObservable=new Ce,this.onBeforeDrawPhaseObservable=new Ce,this.onAfterDrawPhaseObservable=new Ce,this.onReadyObservable=new Ce,this.onBeforeCameraRenderObservable=new Ce,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new Ce,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new Ce,this.onAfterActiveMeshesEvaluationObservable=new Ce,this.onBeforeParticlesRenderingObservable=new Ce,this.onAfterParticlesRenderingObservable=new Ce,this.onDataLoadedObservable=new Ce,this.onNewCameraAddedObservable=new Ce,this.onCameraRemovedObservable=new Ce,this.onNewLightAddedObservable=new Ce,this.onLightRemovedObservable=new Ce,this.onNewGeometryAddedObservable=new Ce,this.onGeometryRemovedObservable=new Ce,this.onNewTransformNodeAddedObservable=new Ce,this.onTransformNodeRemovedObservable=new Ce,this.onNewMeshAddedObservable=new Ce,this.onMeshRemovedObservable=new Ce,this.onNewSkeletonAddedObservable=new Ce,this.onSkeletonRemovedObservable=new Ce,this.onNewMaterialAddedObservable=new Ce,this.onNewMultiMaterialAddedObservable=new Ce,this.onMaterialRemovedObservable=new Ce,this.onMultiMaterialRemovedObservable=new Ce,this.onNewTextureAddedObservable=new Ce,this.onTextureRemovedObservable=new Ce,this.onBeforeRenderTargetsRenderObservable=new Ce,this.onAfterRenderTargetsRenderObservable=new Ce,this.onBeforeStepObservable=new Ce,this.onAfterStepObservable=new Ce,this.onActiveCameraChanged=new Ce,this.onActiveCamerasChanged=new Ce,this.onBeforeRenderingGroupObservable=new Ce,this.onAfterRenderingGroupObservable=new Ce,this.onMeshImportedObservable=new Ce,this.onAnimationFileImportedObservable=new Ce,this._registeredForLateAnimationBindings=new yv(256),this._pointerPickingConfiguration=new mvt,this.onPrePointerObservable=new Ce,this.onPointerObservable=new Ce,this.onPreKeyboardObservable=new Ce,this.onKeyboardObservable=new Ce,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Ut.FOGMODE_NONE,this.fogColor=new Pe(.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 O(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new yv(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new zo,this._activeIndices=new zo,this._activeParticles=new zo,this._activeBones=new zo,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 Go(256),this._processedMaterials=new Go(256),this._renderTargets=new yv(256),this._materialsRenderTargets=new yv(256),this._activeParticleSystems=new Go(256),this._activeSkeletons=new yv(32),this._softwareSkinnedMeshes=new yv(32),this._activeAnimatables=new Array,this._transformMatrix=pe.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Mo.Create(),this._beforeClearStage=Mo.Create(),this._beforeRenderTargetClearStage=Mo.Create(),this._gatherRenderTargetsStage=Mo.Create(),this._gatherActiveCameraRenderTargetsStage=Mo.Create(),this._isReadyForMeshStage=Mo.Create(),this._beforeEvaluateActiveMeshStage=Mo.Create(),this._evaluateSubMeshStage=Mo.Create(),this._preActiveMeshStage=Mo.Create(),this._cameraDrawRenderTargetStage=Mo.Create(),this._beforeCameraDrawStage=Mo.Create(),this._beforeRenderTargetDrawStage=Mo.Create(),this._beforeRenderingGroupDrawStage=Mo.Create(),this._beforeRenderingMeshStage=Mo.Create(),this._afterRenderingMeshStage=Mo.Create(),this._afterRenderingGroupDrawStage=Mo.Create(),this._afterCameraDrawStage=Mo.Create(),this._afterCameraPostProcessStage=Mo.Create(),this._afterRenderTargetDrawStage=Mo.Create(),this._afterRenderTargetPostProcessStage=Mo.Create(),this._afterRenderStage=Mo.Create(),this._pointerMoveStage=Mo.Create(),this._pointerDownStage=Mo.Create(),this._pointerUpStage=Mo.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||ei.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(ei._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new Rc(this),Xk&&(this.postProcessManager=new Xk(this)),dl()&&this.attachControl(),this._createUbo(),Gr&&(this._imageProcessingConfiguration=new Gr),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(),n=i.currentRenderPassId;i.currentRenderPassId=((a=this.activeCamera)==null?void 0:a.renderPassId)??n;let s=!0;for(this._pendingData.length>0&&(s=!1),(o=this.prePassRenderer)==null||o.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const h of this._isReadyForMeshStage)h.action(l,c)||(s=!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)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(const l of this.particleSystems)l.isReady()||(s=!1);if(this.layers)for(const l of this.layers)l.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=n,s}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=hn.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,n){!i&&!n&&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?lf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=lf.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):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 Ci(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 Rz.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(n=>{this.removeMesh(n)}),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 n=this.getLightById(e);if(n)return n;const s=this.getCameraById(e);if(s)return s;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 n=this.getLightByName(e);if(n)return n;const s=this.getCameraByName(e);if(s)return s;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=s,this._skipEvaluateActiveMeshesCompletely=e,n)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 n=this._activeMeshes.length;for(let s=0;s0&&s.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),a!==s&&a._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=s):a._internalAbstractMeshDataInfo._onlyForInstances=!1,a._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,a)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let n=0;n0){const n=this.getActiveSubMeshCandidates(t),s=n.length;i=i||s===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 s=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ie.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let o=0;o0),this._renderId++}for(const o of this._cameraDrawRenderTargetStage)s=o.action(this.activeCamera)||s;this._intermediateRendering=!1}this._engine.currentRenderPassId=((a=e.outputRenderTarget)==null?void 0:a.renderPassId)??e.renderPassId??0,s&&!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),n.snapshotRendering&&n.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&&(n.trigger===13&&n._executeCurrent(Ca.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,c=>{const u=c.mesh?c.mesh:c;return a===u})||n.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Ut.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ut.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let n=0;const s=this._engine.getLockstepMaxSteps();let a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&n0)for(let o=0;o0),this._intermediateRendering=!0;for(let o=0;o0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(n==null?void 0:n.renderPassId)??0,this.activeCamera=n,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{s.onAnimationEndObservable.clear(),s.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 s of e)s.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(s){ge.Error("An error occurred while calling onDisposeObservable!",s)}if(this.detachControl(),this._engine.getInputElement())for(let s=0;ss.dispose(!0)),this._disposeList(this.transformNodes,s=>s.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 n=this._engine.scenes.indexOf(this);n>-1&&this._engine.scenes.splice(n,1),ei._LastCreatedScene===this&&(this._engine.scenes.length>0?ei._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:ei._LastCreatedScene=null),n=this._engine._virtualScenes.indexOf(this),n>-1&&this._engine._virtualScenes.splice(n,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??(n=>n.dispose());for(const n of i)t(n);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(n=>{if(n.computeWorldMatrix(!0),!n.subMeshes||n.subMeshes.length===0||n.infiniteDistance)return;const s=n.getBoundingInfo(),a=s.boundingBox.minimumWorld,o=s.boundingBox.maximumWorld;O.CheckExtends(a,t,i),O.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,n,s=!1){throw Ji("Ray")}createPickingRayToRef(e,t,i,n,s,a=!1,o=!1){throw Ji("Ray")}createPickingRayInCameraSpace(e,t,i){throw Ji("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,n){throw Ji("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,n,s,a){const o=Ji("Ray",!0);return o&&ge.Warn(o),new wl}pickWithBoundingInfo(e,t,i,n,s){const a=Ji("Ray",!0);return a&&ge.Warn(a),new wl}pickWithRay(e,t,i,n){throw Ji("Ray")}multiPick(e,t,i,n,s){throw Ji("Ray")}multiPickWithRay(e,t,i){throw Ji("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 n=[];for(const s in e){const a=e[s];fn&&fn.MatchesQuery(a,t)&&(!i||i(a))&&n.push(a)}return n}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,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t,i=!0,n=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,n)}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,n,s,a,o){const l=s3(e,t,i,n?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_loadFileAsync(e,t,i,n,s){return new Promise((a,o)=>{this._loadFile(e,l=>{a(l)},t,i,n,(l,c)=>{o(c)},s)})}_requestFile(e,t,i,n,s,a,o){const l=BJ(e,t,i,n?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}_requestFileAsync(e,t,i,n,s){return new Promise((a,o)=>{this._requestFile(e,l=>{a(l)},t,i,n,l=>{o(l)},s)})}_readFile(e,t,i,n,s){const a=aw(e,t,i,n,s);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((n,s)=>{this._readFile(e,a=>{n(a)},t,i,a=>{s(a)})})}getPerfCollector(){throw Ji("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)}}Ut.FOGMODE_NONE=0;Ut.FOGMODE_EXP=1;Ut.FOGMODE_EXP2=2;Ut.FOGMODE_LINEAR=3;Ut.MinDeltaTime=1;Ut.MaxDeltaTime=1e3;xe("BABYLON.Scene",Ut);class ys extends Dn{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,n=null,s=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=(n==null?void 0:n.clone())??pe.Identity(),this._restMatrix=s??this._localMatrix.clone(),this._bindMatrix=a??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new pe,this._absoluteBindMatrix=new pe,this._absoluteInverseBindMatrix=new pe,this._finalMatrix=new pe,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=oe.Vector3[0],t=oe.Quaternion[0],i=oe.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??Oe.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=O.Zero(),this._localRotation=Oe.Zero(),this._localPosition=O.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,pe.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(s)}}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(s,1),n||this._raiseOnAnimationEnd())}}else{const s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,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 n;for(n=0;n0)return;this._animationTimeLast=e}this.deltaTime=r!==void 0?r: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 n=0;nr.playOrder-e.playOrder)};Ut.prototype.beginWeightedAnimation=function(r,e,t,i=1,n,s=1,a,o,l,c,u=!1){const h=this.beginAnimation(r,e,t,n,s,a,o,!1,l,c,u);return h.weight=i,h};Ut.prototype.beginAnimation=function(r,e,t,i,n=1,s,a,o=!0,l,c,u=!1){e>t&&n>0&&(n*=-1),o&&this.stopAnimation(r,void 0,l),a||(a=new m1e(this,r,e,t,i,n,s,void 0,c,u));const h=l?l(r):!0;if(r.animations&&h&&a.appendAnimations(r,r.animations),r.getAnimatables){const d=r.getAnimatables();for(let f=0;fi&&s>0)s*=-1;else if(i>t&&s<0){const u=i;i=t,t=u}return new m1e(this,r,t,i,n,s,a,e,o,l)};Ut.prototype.beginDirectHierarchyAnimation=function(r,e,t,i,n,s,a,o,l,c=!1){const u=r.getDescendants(e),h=[];h.push(this.beginDirectAnimation(r,t,i,n,s,a,o,l,c));for(const d of u)h.push(this.beginDirectAnimation(d,t,i,n,s,a,o,l,c));return h};Ut.prototype.getAnimatableByTarget=function(r){for(let e=0;e0?l:-l,n),f.scaleAndAddToRef(l,t)}n.normalize()}for(let h=0;h0)n.copyFrom(i);else if(r.animations.length===1){if(Oe.SlerpToRef(i,t.currentValue,Math.min(1,r.totalWeight),n),r.totalAdditiveWeight===0)return n}else if(r.animations.length>1){let s=1,a,o;if(r.totalWeight<1){const c=1-r.totalWeight;a=[],o=[],a.push(i),o.push(c)}else{if(r.animations.length===2&&(Oe.SlerpToRef(r.animations[0].currentValue,r.animations[1].currentValue,r.animations[1].weight/r.totalWeight,e),r.totalAdditiveWeight===0))return e;a=[],o=[],s=r.totalWeight}for(let c=0;c=a&&m.frame<=o&&(i?(y=m.value.clone(),d?(_=y.getTranslation(),y.setTranslation(_.scaleInPlace(f))):p&&n?(_=y.getTranslation(),y.setTranslation(_.multiplyInPlace(n))):y=m.value):y=m.value,g.push({frame:m.frame+t,value:y}));return this.animations[0].createRange(e,a+t,o+t),!0};class gvt{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=dt.ANIMATIONLOOPMODE_CYCLE}}var jue;(function(r){r[r.CW=0]="CW",r[r.CCW=1]="CCW"})(jue||(jue={}));let HBe=class{static Interpolate(e,t,i,n,s){const a=1-3*n+3*t,o=3*n-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)*s+Math.pow(c,3)}};class ng{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),n=Math.atan2(i.y,i.x);return new ng(n)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new ng(Math.PI/2);i=Math.sqrt(i);let n=e.dot(t)/i;n=Xt.Clamp(n,-1,1);const s=Math.acos(n);return new ng(s)}static FromRadians(e){return new ng(e)}static FromDegrees(e){return new ng(e*Math.PI/180)}}class jBe{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const n=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,a=(n-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 Ne((s*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*s)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=ng.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let c=ng.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),u=ng.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=ng.FromDegrees(this.orientation===0?l-u:u-l)}}class eD{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new Ne(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new Ne(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this}addArcTo(e,t,i,n,s=36){if(this.closed)return this;const a=this._points[this._points.length-1],o=new Ne(e,t),l=new Ne(i,n),c=new jBe(a,o,l);let u=c.angle.radians()/s;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<=s;l++){const c=l/s,u=a(c,o.x,e,i),h=a(c,o.y,t,n);this.addLineTo(u,h)}return this}addBezierCurveTo(e,t,i,n,s,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,s),f=l(h,c.y,t,n,a);this.addLineTo(d,f)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let n=i-1,s=0;sNumber.EPSILON){if(c<0&&(a=this._points[s],l=-l,o=this._points[n],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,n=0;n1)return Ne.Zero();const t=e*this.length();let i=0;for(let n=0;n=i&&t<=c){const u=l.normalize(),h=t-i;return new Ne(a.x+u.x*h,a.y+u.y*h)}i=c}return Ne.Zero()}static StartingAt(e,t){return new eD(e,t)}}class qS{constructor(e,t=null,i,n=!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:O.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:pe.Identity()};for(let s=0;st){const c=e;e=t,t=c}const i=this.getCurve(),n=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(s++,l.push(n)),l.push(...i.slice(s,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 n=0;nt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,n=e.length();if(n===0&&(n=1),t==null){let s;Xt.WithinEpsilon(Math.abs(e.y)/n,1,Ki)?Xt.WithinEpsilon(Math.abs(e.x)/n,1,Ki)?Xt.WithinEpsilon(Math.abs(e.z)/n,1,Ki)?s=O.Zero():s=new O(0,0,1):s=new O(1,0,0):s=new O(0,-1,0),i=O.Cross(e,s)}else i=O.Cross(e,t),O.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 n=i[0],s,a=0;const o=e*this.length();for(let l=1;lo){const h=(a-o)/c,d=n.subtract(s),f=s.add(d.scaleInPlace(h));return this._setPointAtData(e,1-h,f,l-1,t)}n=s}return this._pointAtData}_setPointAtData(e,t,i,n,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=n,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=pe.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),n=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=Oe.RotationQuaternionFromAxis(n,s,i),u=Oe.RotationQuaternionFromAxis(o,l,a);Oe.Slerp(c,u,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class A0{static CreateQuadraticBezier(e,t,i,n){n=n>2?n:3;const s=[],a=(o,l,c,u)=>(1-o)*(1-o)*l+2*o*(1-o)*c+o*o*u;for(let o=0;o<=n;o++)s.push(new O(a(o/n,e.x,t.x,i.x),a(o/n,e.y,t.y,i.y),a(o/n,e.z,t.z,i.z)));return new A0(s)}static CreateCubicBezier(e,t,i,n,s){s=s>3?s: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<=s;l++)a.push(new O(o(l/s,e.x,t.x,i.x,n.x),o(l/s,e.y,t.y,i.y,n.y),o(l/s,e.z,t.z,i.z,n.z)));return new A0(a)}static CreateHermiteSpline(e,t,i,n,s){const a=[],o=1/s;for(let l=0;l<=s;l++)a.push(O.Hermite(e,t,i,n,l*o));return new A0(a)}static CreateCatmullRomSpline(e,t,i){const n=[],s=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}}Ja.EASINGMODE_EASEIN=0;Ja.EASINGMODE_EASEOUT=1;Ja.EASINGMODE_EASEINOUT=2;class $Be extends Ja{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class XBe extends Ja{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 _vt extends Ja{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 n=Math.pow(i,t),s=1-i,a=(1-n)/s+n*.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))/(s*a),d=(1-Math.pow(i,u))/(s*a),f=(h+d)*.5,p=e-f,g=f-h;return-Math.pow(1/i,t-c)/(g*g)*(p-g)*(p+g)}}class vvt extends Ja{easeInCore(e){return e*e*e}}class yvt extends Ja{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),n=Math.max(0,this.springiness);return n==0?t=e:t=(Math.exp(n*e)-1)/(Math.exp(n)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class YBe extends Ja{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 xvt extends Ja{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class g1e extends Ja{easeInCore(e){return e*e}}class bvt extends Ja{easeInCore(e){return e*e*e*e}}class Cvt extends Ja{easeInCore(e){return e*e*e*e*e}}class _1e extends Ja{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Avt extends Ja{constructor(e=0,t=0,i=1,n=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=n}easeInCore(e){return HBe.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class UJ{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new UJ(this.frame,this.action,this.onlyOnce)}}class QBe{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Qm{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 Qm(e[0].name+"_merged",e[0]._scene,n);for(const l of e){i&&l.normalize(s,a);for(const c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}constructor(e,t=null,i=-1,n=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 Ce,this.onAnimationLoopObservable=new Ce,this.onAnimationGroupLoopObservable=new Ce,this.onAnimationGroupEndObservable=new Ce,this.onAnimationGroupPauseObservable=new Ce,this.onAnimationGroupPlayObservable=new Ce,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||ei.LastCreatedScene,this._weight=i,this._playOrder=n,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new QBe;i.animation=e,i.target=t;const n=e.getKeys();return this._from>n[0].frame&&(this._from=n[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};s.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,n,s){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++]=s:e&&this._checkAnimationGroupEnded(s,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 n=new Qm(e||this.name,this._scene,this._weight,this._playOrder);n._from=this.from,n._to=this.to,n._speedRatio=this.speedRatio,n._loopAnimation=this.loopAnimation,n._isAdditive=this.isAdditive,n._enableBlending=this.enableBlending,n._blendingSpeed=this.blendingSpeed,n.metadata=this.metadata,n.mask=this.mask;for(const s of this._targetedAnimations)n.addTargetedAnimation(i?s.animation.clone():s.animation,t?t(s.target):s.target);return n}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;tg[0].frame&&(c=g[0].frame),u=t&&g<=i||s&&m.frame>=t&&m.frame<=i){const _={frame:m.frame,value:m.value.clone?m.value.clone():m.value,inTangent:m.inTangent,outTangent:m.outTangent,interpolation:m.interpolation,lockedTangent:m.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 Xue;(function(r){r[r.Include=0]="Include",r[r.Exclude=1]="Exclude"})(Xue||(Xue={}));class Evt{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 Yk(r,e,t){try{const i=r.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function ZBe(r=25){let e;return(t,i,n)=>{const s=performance.now();e===void 0||s-e>r?(e=s,setTimeout(()=>{Yk(t,i,n)},0)):Yk(t,i,n)}}function v1e(r,e,t,i,n){const s=()=>{let a;const o=l=>{l.done?t(l.value):a===void 0?a=!0:s()};do a=void 0,!n||!n.aborted?e(r,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};s()}function zJ(r,e){let t;return v1e(r,Yk,i=>t=i,i=>{throw i},e),t}function VJ(r,e,t){return new Promise((i,n)=>{v1e(r,e,i,n,t)})}function qBe(r,e){return(...t)=>zJ(r(...t),e)}function Tvt(r,e,t){return(...i)=>VJ(r(...i),e,t)}class Yc{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new Yc(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 Yc(this.x,this.y,this.width,this.height)}}class di extends Dn{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===di.PERSPECTIVE_CAMERA)this.fovMode===di.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,n=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??n)-(this.orthoBottom??-n)}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,n=!0){super(e,i,!1),this._position=O.Zero(),this._upVector=O.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=di.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Yc(0,0,1,1),this.layerMask=268435455,this.fovMode=di.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=di.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new Ce,this.onProjectionMatrixChangedObservable=new Ce,this.onAfterCheckInputsObservable=new Ce,this.onRestoreStateObservable=new Ce,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new pe,this._postProcesses=new Array,this._activeMeshes=new Go(256),this._globalPosition=O.Zero(),this._computedViewMatrix=pe.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=pe.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Oe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),n&&!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?(ge.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 pe.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 s,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(),n=t.useReverseDepthBuffer;if(this.mode===di.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=pe.PerspectiveFovRHToRef:l=pe.PerspectiveFovLHToRef,l(this.fov,t.getAspectRatio(this),n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===di.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,n)}else{const l=t.getRenderWidth()/2,c=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?pe.ObliqueOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):pe.OrthoOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?pe.ObliqueOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,n?this.maxZ:this.minZ,n?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):pe.OrthoOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-c,this.orthoTop??c,n?this.maxZ:this.minZ,n?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=(s=this.oblique)==null?void 0:s.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?O.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?lf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=lf.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(n=>{n._updateFrustumPlanes(),i=i||e.isInFrustum(n._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw Ji("Ray")}getForwardRayToRef(e,t=100,i,n){throw Ji("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 n=this._rigCameras.pop();n&&n.dispose()}if(this._parentContainer){const n=this._parentContainer.cameras.indexOf(this);n>-1&&this._parentContainer.cameras.splice(n,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==di.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let n=this._postProcesses.length;for(;--n>=0;){const s=this._postProcesses[n];s&&s.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=Ie.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==di.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const n=this.createRigCamera(this.name+"_R",1);n&&(n._isRightCamera=!0),i&&n&&(this._rigCameras.push(i),this._rigCameras.push(n))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return pe.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=Ie.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;edi._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=di.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=ot.Parse(n,e,t);if(e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=O.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(O.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(O.FromArray(e.target)),e.cameraRigMode){const a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a{throw Ji("UniversalCamera")};di.PERSPECTIVE_CAMERA=0;di.ORTHOGRAPHIC_CAMERA=1;di.FOVMODE_VERTICAL_FIXED=0;di.FOVMODE_HORIZONTAL_FIXED=1;di.RIG_MODE_NONE=0;di.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;di.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;di.RIG_MODE_STEREOSCOPIC_INTERLACED=14;di.RIG_MODE_VR=20;di.RIG_MODE_CUSTOM=22;di.ForceAttachControlToAlwaysPreventDefault=!1;V([ta("position")],di.prototype,"_position",void 0);V([ta("upVector")],di.prototype,"_upVector",void 0);V([Q()],di.prototype,"orthoLeft",null);V([Q()],di.prototype,"orthoRight",null);V([Q()],di.prototype,"orthoBottom",null);V([Q()],di.prototype,"orthoTop",null);V([Q()],di.prototype,"fov",void 0);V([Q()],di.prototype,"projectionPlaneTilt",void 0);V([Q()],di.prototype,"minZ",void 0);V([Q()],di.prototype,"maxZ",void 0);V([Q()],di.prototype,"inertia",void 0);V([Q()],di.prototype,"mode",null);V([Q()],di.prototype,"layerMask",void 0);V([Q()],di.prototype,"fovMode",void 0);V([Q()],di.prototype,"cameraRigMode",void 0);V([Q()],di.prototype,"interaxialDistance",void 0);V([Q()],di.prototype,"isStereoscopicSideBySide",void 0);class mZ{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Id{constructor(e,t,i){this.vectors=Qh(8,O.Zero),this.center=O.Zero(),this.centerWorld=O.Zero(),this.extendSize=O.Zero(),this.extendSizeWorld=O.Zero(),this.directions=Qh(3,O.Zero),this.vectorsWorld=Qh(8,O.Zero),this.minimumWorld=O.Zero(),this.maximumWorld=O.Zero(),this.minimum=O.Zero(),this.maximum=O.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,s=e.y,a=e.z,o=t.x,l=t.y,c=t.z,u=this.vectors;this.minimum.copyFromFloats(n,s,a),this.maximum.copyFromFloats(o,l,c),u[0].copyFromFloats(n,s,a),u[1].copyFromFloats(o,l,c),u[2].copyFromFloats(o,s,a),u[3].copyFromFloats(n,l,a),u[4].copyFromFloats(n,s,c),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(n,l,c),u[7].copyFromFloats(o,s,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||pe.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Id._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const s=n*e,a=i.scaleInPlace(s*.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,n=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)s[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=s[o];O.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)}O.FromArrayToRef(e.m,0,n[0]),O.FromArrayToRef(e.m,4,n[1]),O.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return Id.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Id.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,s=t.y,a=t.z,o=i.x,l=i.y,c=i.z,u=e.x,h=e.y,d=e.z,f=-Ki;return!(o-uu-n||l-hh-s||c-dd-a)}intersectsSphere(e){return Id.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,s=i.x,a=i.y,o=i.z,l=n.x,c=n.y,u=n.z,h=e.x,d=e.y,f=e.z,p=t.x,g=t.y,m=t.z;return!(lp||cg||um)}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,n){const s=Id._TmpVector3[0];return O.ClampToRef(i,e,t,s),O.DistanceSquared(i,s)<=n*n}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const n=t[i];for(let s=0;s<8;++s)if(n.dotCoordinate(e[s])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let n=!0;const s=t[i];for(let a=0;a<8;++a)if(s.dotCoordinate(e[a])>=0){n=!1;break}if(n)return!1}return!0}}Id._TmpVector3=Qh(3,O.Zero);class gg{constructor(e,t,i){this.center=O.Zero(),this.centerWorld=O.Zero(),this.minimum=O.Zero(),this.maximum=O.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=O.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=n*.5,this._update(i||pe.IdentityReadOnly)}scale(e){const t=this.radius*e,i=gg._TmpVector3,n=i[0].setAll(t),s=this.center.subtractToRef(n,i[1]),a=this.center.addToRef(n,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{O.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=gg._TmpVector3[0];O.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 n=0;n<6;n++)if(e[n].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=O.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=O.Dot(e.centerWorld,r),n=Math.abs(O.Dot(e.directions[0],r))*e.extendSize.x,s=Math.abs(O.Dot(e.directions[1],r))*e.extendSize.y,a=Math.abs(O.Dot(e.directions[2],r))*e.extendSize.z,o=n+s+a;t.min=i-o,t.max=i+o},gd=(r,e,t)=>(AMe(r,e,cae),AMe(r,t,uae),!(cae.min>uae.max||uae.min>cae.max));class vu{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Id(e,t,i),this.boundingSphere=new gg(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=vu._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=vu._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,n,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=O.Minimize(this.minimum,e),i=O.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=oe.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=oe.Vector3[0];return O.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),O.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,vu._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(!gg.Intersects(this.boundingSphere,e.boundingSphere)||!Id.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!(!gd(i.directions[0],i,n)||!gd(i.directions[1],i,n)||!gd(i.directions[2],i,n)||!gd(n.directions[0],i,n)||!gd(n.directions[1],i,n)||!gd(n.directions[2],i,n)||!gd(O.Cross(i.directions[0],n.directions[0]),i,n)||!gd(O.Cross(i.directions[0],n.directions[1]),i,n)||!gd(O.Cross(i.directions[0],n.directions[2]),i,n)||!gd(O.Cross(i.directions[1],n.directions[0]),i,n)||!gd(O.Cross(i.directions[1],n.directions[1]),i,n)||!gd(O.Cross(i.directions[1],n.directions[2]),i,n)||!gd(O.Cross(i.directions[2],n.directions[0]),i,n)||!gd(O.Cross(i.directions[2],n.directions[1]),i,n)||!gd(O.Cross(i.directions[2],n.directions[2]),i,n))}}vu._TmpVector3=Qh(2,O.Zero);class GJ{static extractMinAndMaxIndexed(e,t,i,n,s,a){for(let o=i;o!Array.isArray(r)&&!Array.isArray(e))],GJ,"extractMinAndMaxIndexed",null);V([M_.filter((...[r])=>!Array.isArray(r))],GJ,"extractMinAndMax",null);function JBe(r,e,t,i,n=null){const s=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return GJ.extractMinAndMaxIndexed(r,e,t,i,s,a),n&&(s.x-=s.x*n.x+n.y,s.y-=s.y*n.x+n.y,s.z-=s.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:s,maximum:a}}function JS(r,e,t,i=null,n){const s=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return n||(n=3),GJ.extractMinAndMax(r,e,t,n,s,a),i&&(s.x-=s.x*i.x+i.y,s.y-=s.y*i.x+i.y,s.z-=s.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:s,maximum:a}}class pl{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 n;this.effect=e,t!==void 0&&(this.defines=t),i&&((n=this.drawContext)==null||n.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}class yc{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 pl(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,n=!0){const s=this._drawWrapper;s.setEffect(e,t,n),i!==void 0&&(s.materialContext=i),e||(s.defines=null,s.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,n,s,a,o,l=!0){return new yc(e,t,i,n,s,a,o,l)}constructor(e,t,i,n,s,a,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=s,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(ee.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 n=this._renderingMesh.getBoundingInfo();i={minimum:n.minimum.clone(),maximum:n.maximum.clone()}}else i=JBe(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new vu(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 n=this.indexStart;nl&&(l=d)}return new yc(e,o,l-o+1,t,i,n,s,a)}}class Y9{}class vt{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=qBe(this._applyToCoroutine.bind(this)),this.uniqueId=vt._UniqueIDGenerator,vt._UniqueIDGenerator++}set(e,t){switch(e.length||ge.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case ee.PositionKind:this.positions=e;break;case ee.NormalKind:this.normals=e;break;case ee.TangentKind:this.tangents=e;break;case ee.UVKind:this.uvs=e;break;case ee.UV2Kind:this.uvs2=e;break;case ee.UV3Kind:this.uvs3=e;break;case ee.UV4Kind:this.uvs4=e;break;case ee.UV5Kind:this.uvs5=e;break;case ee.UV6Kind:this.uvs6=e;break;case ee.ColorKind:this.colors=e;break;case ee.MatricesIndicesKind:this.matricesIndices=e;break;case ee.MatricesWeightsKind:this.matricesWeights=e;break;case ee.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case ee.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(ee.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(ee.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(ee.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(ee.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(ee.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(ee.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(ee.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(ee.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(ee.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(ee.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(ee.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(ee.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(ee.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(ee.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 n=e;n.subMeshes=[];for(const s of this.materialInfos)new yc(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,n)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(ee.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(ee.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(ee.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(ee.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(ee.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(ee.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(ee.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(ee.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(ee.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(ee.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(ee.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(ee.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(ee.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(ee.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const s=oe.Vector3[0],a=oe.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return zJ(this._mergeCoroutine(void 0,a,t,!1,i,n,s))}*_mergeCoroutine(e,t,i=!1,n,s,a=!1,o=!1){var f,p;this._validate();let l=t.map(g=>g.vertexData),c=this;if(o)for(const g of l)g&&(g._validate(),!this.normals&&g.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&g.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&g.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&g.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&g.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&g.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&g.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&g.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&g.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&g.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&g.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&g.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&g.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const g of l)if(g){if(o)this.normals&&!g.normals&&(g.normals=new Float32Array(g.positions.length)),this.tangents&&!g.tangents&&(g.tangents=new Float32Array(g.positions.length/3*4)),this.uvs&&!g.uvs&&(g.uvs=new Float32Array(g.positions.length/3*2)),this.uvs2&&!g.uvs2&&(g.uvs2=new Float32Array(g.positions.length/3*2)),this.uvs3&&!g.uvs3&&(g.uvs3=new Float32Array(g.positions.length/3*2)),this.uvs4&&!g.uvs4&&(g.uvs4=new Float32Array(g.positions.length/3*2)),this.uvs5&&!g.uvs5&&(g.uvs5=new Float32Array(g.positions.length/3*2)),this.uvs6&&!g.uvs6&&(g.uvs6=new Float32Array(g.positions.length/3*2)),this.colors&&!g.colors&&(g.colors=new Float32Array(g.positions.length/3*4),g.colors.fill(1)),this.matricesIndices&&!g.matricesIndices&&(g.matricesIndices=new Float32Array(g.positions.length/3*4)),this.matricesWeights&&!g.matricesWeights&&(g.matricesWeights=new Float32Array(g.positions.length/3*4)),this.matricesIndicesExtra&&!g.matricesIndicesExtra&&(g.matricesIndicesExtra=new Float32Array(g.positions.length/3*4)),this.matricesWeightsExtra&&!g.matricesWeightsExtra&&(g.matricesWeightsExtra=new Float32Array(g.positions.length/3*4));else if(g._validate(),!this.normals!=!g.normals||!this.tangents!=!g.tangents||!this.uvs!=!g.uvs||!this.uvs2!=!g.uvs2||!this.uvs3!=!g.uvs3||!this.uvs4!=!g.uvs4||!this.uvs5!=!g.uvs5||!this.uvs6!=!g.uvs6||!this.colors!=!g.colors||!this.matricesIndices!=!g.matricesIndices||!this.matricesWeights!=!g.matricesWeights||!this.matricesIndicesExtra!=!g.matricesIndicesExtra||!this.matricesWeightsExtra!=!g.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let g=0,m=0,_=0;const y=[];let v=null;const x=[];for(const C of this.splitBasedOnMaterialID())x.push({vertexData:C,transform:e});for(const C of t)if(C.vertexData)for(const A of C.vertexData.splitBasedOnMaterialID())x.push({vertexData:A,transform:C.transform});x.sort((C,A)=>{const E=C.vertexData.materialInfos?C.vertexData.materialInfos[0].materialIndex:0,P=A.vertexData.materialInfos?A.vertexData.materialInfos[0].materialIndex:0;return E>P?1:E===P?0:-1});for(const C of x){const A=C.vertexData;if(A.materialInfos?g=A.materialInfos[0].materialIndex:g=0,v&&v.materialIndex===g)v.indexCount+=A.indices.length,v.verticesCount+=A.positions.length/3;else{const E=new Y9;E.materialIndex=g,E.indexStart=m,E.indexCount=A.indices.length,E.verticesStart=_,E.verticesCount=A.positions.length/3,y.push(E),v=E}m+=A.indices.length,_+=A.positions.length/3}const b=x.splice(0,1)[0];c=b.vertexData,e=b.transform,l=x.map(C=>C.vertexData),t=x,this.materialInfos=y}const u=l.reduce((g,m)=>{var _;return g+(((_=m.indices)==null?void 0:_.length)??0)},((f=c.indices)==null?void 0:f.length)??0);let d=s||l.some(g=>g.indices===c.indices)?(p=c.indices)==null?void 0:p.slice():c.indices;if(u>0){let g=(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&&vt._FlipFaces(d,0,g)}let m=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[g+v]=_.indices[v]+m;y&&y.determinant()<0&&vt._FlipFaces(d,g,_.indices.length),m+=_.positions.length/3,g+=_.indices.length,n&&(yield)}}return this.indices=d,this.positions=vt._MergeElement(ee.PositionKind,c.positions,e,t.map(g=>[g.vertexData.positions,g.transform])),n&&(yield),c.normals&&(this.normals=vt._MergeElement(ee.NormalKind,c.normals,e,t.map(g=>[g.vertexData.normals,g.transform])),n&&(yield)),c.tangents&&(this.tangents=vt._MergeElement(ee.TangentKind,c.tangents,e,t.map(g=>[g.vertexData.tangents,g.transform])),n&&(yield)),c.uvs&&(this.uvs=vt._MergeElement(ee.UVKind,c.uvs,e,t.map(g=>[g.vertexData.uvs,g.transform])),n&&(yield)),c.uvs2&&(this.uvs2=vt._MergeElement(ee.UV2Kind,c.uvs2,e,t.map(g=>[g.vertexData.uvs2,g.transform])),n&&(yield)),c.uvs3&&(this.uvs3=vt._MergeElement(ee.UV3Kind,c.uvs3,e,t.map(g=>[g.vertexData.uvs3,g.transform])),n&&(yield)),c.uvs4&&(this.uvs4=vt._MergeElement(ee.UV4Kind,c.uvs4,e,t.map(g=>[g.vertexData.uvs4,g.transform])),n&&(yield)),c.uvs5&&(this.uvs5=vt._MergeElement(ee.UV5Kind,c.uvs5,e,t.map(g=>[g.vertexData.uvs5,g.transform])),n&&(yield)),c.uvs6&&(this.uvs6=vt._MergeElement(ee.UV6Kind,c.uvs6,e,t.map(g=>[g.vertexData.uvs6,g.transform])),n&&(yield)),c.colors&&(this.colors=vt._MergeElement(ee.ColorKind,c.colors,e,t.map(g=>[g.vertexData.colors,g.transform])),(c.hasVertexAlpha!==void 0||t.some(g=>g.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=c.hasVertexAlpha||t.some(g=>g.vertexData.hasVertexAlpha)),n&&(yield)),c.matricesIndices&&(this.matricesIndices=vt._MergeElement(ee.MatricesIndicesKind,c.matricesIndices,e,t.map(g=>[g.vertexData.matricesIndices,g.transform])),n&&(yield)),c.matricesWeights&&(this.matricesWeights=vt._MergeElement(ee.MatricesWeightsKind,c.matricesWeights,e,t.map(g=>[g.vertexData.matricesWeights,g.transform])),n&&(yield)),c.matricesIndicesExtra&&(this.matricesIndicesExtra=vt._MergeElement(ee.MatricesIndicesExtraKind,c.matricesIndicesExtra,e,t.map(g=>[g.vertexData.matricesIndicesExtra,g.transform])),n&&(yield)),c.matricesWeightsExtra&&(this.matricesWeightsExtra=vt._MergeElement(ee.MatricesWeightsExtraKind,c.matricesWeightsExtra,e,t.map(g=>[g.vertexData.matricesWeightsExtra,g.transform]))),this}static _MergeElement(e,t,i,n){const s=n.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&s.length==0)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const a=s.reduce((l,c)=>l+c[0].length,t.length),o=e===ee.PositionKind?vt._TransformVector3Coordinates:e===ee.NormalKind?vt._TransformVector3Normals:e===ee.TangentKind?vt._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 s)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=ee.DeduceStride(n);if(s.length%a!==0)throw new Error("The "+n+"s array count must be a multiple of "+a);return s.length/a},t=e(ee.PositionKind,this.positions),i=(n,s)=>{const a=e(n,s);if(a!==t)throw new Error("The "+n+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i(ee.NormalKind,this.normals),this.tangents&&i(ee.TangentKind,this.tangents),this.uvs&&i(ee.UVKind,this.uvs),this.uvs2&&i(ee.UV2Kind,this.uvs2),this.uvs3&&i(ee.UV3Kind,this.uvs3),this.uvs4&&i(ee.UV4Kind,this.uvs4),this.uvs5&&i(ee.UV5Kind,this.uvs5),this.uvs6&&i(ee.UV6Kind,this.uvs6),this.colors&&i(ee.ColorKind,this.colors),this.matricesIndices&&i(ee.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(ee.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(ee.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(ee.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return vt.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 vt._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return vt._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new vt;if(e.isVerticesDataPresent(ee.PositionKind)&&(n.positions=e.getVerticesData(ee.PositionKind,t,i)),e.isVerticesDataPresent(ee.NormalKind)&&(n.normals=e.getVerticesData(ee.NormalKind,t,i)),e.isVerticesDataPresent(ee.TangentKind)&&(n.tangents=e.getVerticesData(ee.TangentKind,t,i)),e.isVerticesDataPresent(ee.UVKind)&&(n.uvs=e.getVerticesData(ee.UVKind,t,i)),e.isVerticesDataPresent(ee.UV2Kind)&&(n.uvs2=e.getVerticesData(ee.UV2Kind,t,i)),e.isVerticesDataPresent(ee.UV3Kind)&&(n.uvs3=e.getVerticesData(ee.UV3Kind,t,i)),e.isVerticesDataPresent(ee.UV4Kind)&&(n.uvs4=e.getVerticesData(ee.UV4Kind,t,i)),e.isVerticesDataPresent(ee.UV5Kind)&&(n.uvs5=e.getVerticesData(ee.UV5Kind,t,i)),e.isVerticesDataPresent(ee.UV6Kind)&&(n.uvs6=e.getVerticesData(ee.UV6Kind,t,i)),e.isVerticesDataPresent(ee.ColorKind)){const s=e.geometry||e,a=s.getVertexBuffer(ee.ColorKind),o=s.getVerticesData(ee.ColorKind,t,i);if(a.getSize()===3){const l=new Float32Array(o.length*4/3);for(let c=0,u=0;c!Array.isArray(r))],vt,"_TransformVector3Coordinates",null);V([M_.filter((...[r])=>!Array.isArray(r))],vt,"_TransformVector3Normals",null);V([M_.filter((...[r])=>!Array.isArray(r))],vt,"_TransformVector4Normals",null);V([M_.filter((...[r])=>!Array.isArray(r))],vt,"_FlipFaces",null);class hl{static get ForceFullSceneLoadingForIncremental(){return hl._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){hl._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return hl._ShowLoadingScreen}static set ShowLoadingScreen(e){hl._ShowLoadingScreen=e}static get loggingLevel(){return hl._LoggingLevel}static set loggingLevel(e){hl._LoggingLevel=e}static get CleanBoneMatrixWeights(){return hl._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){hl._CleanBoneMatrixWeights=e}}hl._ForceFullSceneLoadingForIncremental=!1;hl._ShowLoadingScreen=!0;hl._CleanBoneMatrixWeights=!1;hl._LoggingLevel=0;let bn=!1;const Mvt={get UseOpenGLOrientationForUV(){return bn},set UseOpenGLOrientationForUV(r){bn=r}};function e9e(r,e,t,i,n,s,a,o){const l=e*ee.GetTypeByteLength(t),c=a*e;if(o.length!==c)throw new Error("Output length is not valid");if(t!==ee.FLOAT||n!==l){ee.ForEach(r,i,n,e,t,c,s,(u,h)=>o[h]=u);return}if(r instanceof Array){const u=i/4;o.set(r,u)}else if(r instanceof ArrayBuffer){const u=new Float32Array(r,i,c);o.set(u)}else{const u=r.byteOffset+i;if(u%4){ge.Warn("CopyFloatData: copied misaligned data."),o.set(new Float32Array(r.buffer.slice(u,u+c*4)));return}const d=new Float32Array(r.buffer,u,c);o.set(d)}}class ul{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 ul(ul.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||ei.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.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,n){i&&Array.isArray(t)&&(t=new Float32Array(t));const s=new ee(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:n,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const n=e.getKind();this._vertexBuffers[n]&&i&&this._vertexBuffers[n].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[n]=e;const s=this._meshes,a=s.length;if(n===ee.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let c=0;c65535);for(const n of this._meshes)n._createGlobalSubMesh(!0),n.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 n of this._meshes)n._createGlobalSubMesh(!0),n.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,n=i.indexOf(e);n!==-1&&(i.splice(n,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(ee.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===ee.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 n=this._meshes,s=n.length;for(let a=0;a0){for(let n=0;n0){for(let n=0;n0){for(let n=0;n-1&&this._parentContainer.geometries.splice(n,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new vt;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(ee.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){const o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData(ee.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){const o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData(ee.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){const o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(bn)for(let l=1;l0){const o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData(ee.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(ee.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(ee.MatricesIndicesExtraKind,l,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData(ee.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(ee.MatricesIndicesKind,a,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(ee.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(ee.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(ul._CleanMatricesWeights(e,t),t.setVerticesData(ee.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(ee.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;n=h.bones.length}else return;const s=t.getVerticesData(ee.MatricesIndicesKind),a=t.getVerticesData(ee.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 g=0;g<4;g++)o[h+g]*=p;if(l)for(let g=0;g<4;g++)l[h+g]*=p}else f>=4?(l[h+f-4]=1-d,a[h+f-4]=n):(o[h+f]=1-d,s[h+f]=n)}t.setVerticesData(ee.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(ee.MatricesIndicesExtraKind,a)}static Parse(e,t,i){const n=new ul(e.id,t,void 0,e.updatable);return n._loadedUniqueId=e.uniqueId,fn&&fn.AddTagsTo(n,e.tags),e.delayLoadingFile?(n.delayLoadState=4,n.delayLoadingFile=i+e.delayLoadingFile,n._boundingInfo=new vu(O.FromArray(e.boundingBoxMinimum),O.FromArray(e.boundingBoxMaximum)),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(ee.UVKind),e.hasUVs2&&n._delayInfo.push(ee.UV2Kind),e.hasUVs3&&n._delayInfo.push(ee.UV3Kind),e.hasUVs4&&n._delayInfo.push(ee.UV4Kind),e.hasUVs5&&n._delayInfo.push(ee.UV5Kind),e.hasUVs6&&n._delayInfo.push(ee.UV6Kind),e.hasColors&&n._delayInfo.push(ee.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(ee.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(ee.MatricesWeightsKind),n._delayLoadingFunction=vt.ImportVertexData):vt.ImportVertexData(e,n),t.pushGeometry(n,!0),n}}const Rvt=pe.Compose(O.One(),Oe.FromEulerAngles(0,Math.PI,0),O.Zero());class Yt extends Dn{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&Yt.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!==Yt.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 O(0,0,1),this._up=new O(0,1,0),this._right=new O(1,0,0),this._position=O.Zero(),this._rotation=O.Zero(),this._rotationQuaternion=null,this._scaling=O.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Yt.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=pe.Zero(),this._usePivotMatrix=!1,this._absolutePosition=O.Zero(),this._absoluteScaling=O.Zero(),this._absoluteRotationQuaternion=Oe.Identity(),this._pivotMatrix=pe.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new Ce,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 O.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return O.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return O.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=pe.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Yt.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=pe.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const s of this.getChildTransformNodes(!0))s.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||Oe.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,n;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){const s=oe.Matrix[0];this.parent.getWorldMatrix().invertToRef(s),O.TransformCoordinatesFromFloatsToRef(t,i,n,s,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=O.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=oe.Matrix[0];return this._localMatrix.invertToRef(e),O.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=O.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,s=0){const a=Yt._LookAtVectorCache,o=s===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,n),s===1&&this.parent)if(this.rotationQuaternion){const l=oe.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const c=oe.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=oe.Quaternion[0];Oe.FromEulerVectorToRef(this.rotation,l);const c=oe.Matrix[0];l.toRotationMatrix(c);const u=oe.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=O.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return O.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const s=-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?Oe.RotationYawPitchRollToRef(s+t,o+i,n,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=n),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==1){const n=oe.Matrix[0];i.invertToRef(n),e=O.TransformCoordinates(e,n)}return this.setPivotMatrix(pe.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=O.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=O.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),O.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 n=oe.Quaternion[0],s=oe.Vector3[0],a=oe.Vector3[1],o=oe.Matrix[1];pe.IdentityToRef(o);const l=oe.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=Yt._TmpRotation,Oe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),pe.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,n,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(pe.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 n;if(!i||i===0)n=Oe.RotationAxisToRef(e,t,Yt._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);else{if(this.parent){const s=this.parent.getWorldMatrix(),a=oe.Matrix[0];s.invertToRef(a),e=O.TransformNormal(e,a),s.determinant()<0&&(t*=-1)}n=Oe.RotationAxisToRef(e,t,Yt._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Oe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=oe.Vector3[0],s=oe.Vector3[1],a=oe.Vector3[2],o=oe.Quaternion[0],l=oe.Matrix[0],c=oe.Matrix[1],u=oe.Matrix[2],h=oe.Matrix[3];return e.subtractToRef(this.position,n),pe.TranslationToRef(n.x,n.y,n.z,l),pe.TranslationToRef(-n.x,-n.y,-n.z,c),pe.RotationAxisToRef(t,i,u),c.multiplyToRef(u,h),h.multiplyToRef(l,h),h.decompose(s,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(!i||i===0){const s=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(s)}else this.setAbsolutePosition(this.getAbsolutePosition().add(n));return this}addRotation(e,t,i){let n;this.rotationQuaternion?n=this.rotationQuaternion:(n=oe.Quaternion[1],Oe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const s=oe.Quaternion[0];return Oe.RotationYawPitchRollToRef(t,e,i,s),n.multiplyInPlace(s),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Yt.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 n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.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 s=this._getEffectiveParent(),a=Yt._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const c=t.getWorldMatrix(),u=new O(c.m[12],c.m[13],c.m[14]);o=Yt._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(Oe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=Yt._TmpRotation,Oe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const c=oe.Matrix[1];pe.ScalingToRef(a.x,a.y,a.z,c);const u=oe.Matrix[0];l.toRotationMatrix(u),this._pivotMatrix.multiplyToRef(c,oe.Matrix[4]),oe.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 pe.ComposeToRef(a,l,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),n.useBillboardPath){if(this._transformToBoneReferal){const d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),oe.Matrix[7])}else oe.Matrix[7].copyFrom(s.getWorldMatrix());const c=oe.Vector3[5],u=oe.Vector3[6],h=oe.Quaternion[0];oe.Matrix[7].decompose(u,h,c),pe.ScalingToRef(u.x,u.y,u.z,oe.Matrix[7]),oe.Matrix[7].setTranslation(c),Yt.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(h,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef(oe.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),oe.Matrix[6]),oe.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const c=oe.Vector3[0];if(this._worldMatrix.getTranslationToRef(c),oe.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&oe.Matrix[1].multiplyToRef(Rvt,oe.Matrix[1]),oe.Matrix[1].setTranslationFromFloats(0,0,0),oe.Matrix[1].invertToRef(oe.Matrix[0]),(this.billboardMode&Yt.BILLBOARDMODE_ALL)!==Yt.BILLBOARDMODE_ALL){oe.Matrix[0].decompose(void 0,oe.Quaternion[0],void 0);const u=oe.Vector3[1];oe.Quaternion[0].toEulerAnglesToRef(u),(this.billboardMode&Yt.BILLBOARDMODE_X)!==Yt.BILLBOARDMODE_X&&(u.x=0),(this.billboardMode&Yt.BILLBOARDMODE_Y)!==Yt.BILLBOARDMODE_Y&&(u.y=0),(this.billboardMode&Yt.BILLBOARDMODE_Z)!==Yt.BILLBOARDMODE_Z&&(u.z=0),pe.RotationYawPitchRollToRef(u.y,u.x,u.z,oe.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(oe.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(oe.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const c=oe.Vector3[0];this._worldMatrix.getTranslationToRef(c);const u=t.globalPosition;this._worldMatrix.invertToRef(oe.Matrix[1]);const h=oe.Vector3[1];O.TransformCoordinatesToRef(u,oe.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(Oe.RotationYawPitchRollToRef(d,p,0,oe.Quaternion[0]),(this.billboardMode&Yt.BILLBOARDMODE_ALL)!==Yt.BILLBOARDMODE_ALL){const g=oe.Vector3[1];oe.Quaternion[0].toEulerAnglesToRef(g),(this.billboardMode&Yt.BILLBOARDMODE_X)!==Yt.BILLBOARDMODE_X&&(g.x=0),(this.billboardMode&Yt.BILLBOARDMODE_Y)!==Yt.BILLBOARDMODE_Y&&(g.y=0),(this.billboardMode&Yt.BILLBOARDMODE_Z)!==Yt.BILLBOARDMODE_Z&&(g.z=0),pe.RotationYawPitchRollToRef(g.y,g.x,g.z,oe.Matrix[0])}else pe.FromQuaternionToRef(oe.Quaternion[0],oe.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(oe.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(oe.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._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=pe.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew Yt(e,this.getScene()),this);if(n.name=e,n.id=e,t&&(n.parent=t),!i){const s=this.getDescendants(!0);for(let a=0;anew Yt(e.name,t),e,t,i);if(e.localMatrix?n.setPreTransformMatrix(pe.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(pe.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(n._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let s=0;s(!t||t(n))&&n instanceof Yt),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 n of i)n.parent=null,n.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let n=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=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&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Yt.BILLBOARDMODE_NONE=0;Yt.BILLBOARDMODE_X=1;Yt.BILLBOARDMODE_Y=2;Yt.BILLBOARDMODE_Z=4;Yt.BILLBOARDMODE_ALL=7;Yt.BILLBOARDMODE_USE_POSITION=128;Yt.BillboardUseParentOrientation=!1;Yt._TmpRotation=Oe.Zero();Yt._TmpScaling=O.Zero();Yt._TmpTranslation=O.Zero();Yt._LookAtVectorCache=new O(0,0,0);Yt._RotationAxisCache=new Oe;V([ta("position")],Yt.prototype,"_position",void 0);V([ta("rotation")],Yt.prototype,"_rotation",void 0);V([pBe("rotationQuaternion")],Yt.prototype,"_rotationQuaternion",void 0);V([ta("scaling")],Yt.prototype,"_scaling",void 0);V([Q("billboardMode")],Yt.prototype,"_billboardMode",void 0);V([Q()],Yt.prototype,"scalingDeterminant",void 0);V([Q("infiniteDistance")],Yt.prototype,"_infiniteDistance",void 0);V([Q()],Yt.prototype,"ignoreNonUniformScaling",void 0);V([Q()],Yt.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class t9e{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new O(0,0,0),this._diffPositionForCollisions=new O(0,0,0),this._collisionResponse=!0}}var Yue;(function(r){r[r.LOCAL=0]="LOCAL",r[r.WORLD=1]="WORLD",r[r.BONE=2]="BONE"})(Yue||(Yue={}));let go=class{};go.X=new O(1,0,0);go.Y=new O(0,1,0);go.Z=new O(0,0,1);var Que;(function(r){r[r.X=0]="X",r[r.Y=1]="Y",r[r.Z=2]="Z"})(Que||(Que={}));function Ivt(r,e,t){let i=null;switch(e){case ee.PositionKind:i=n=>n.getPositions();break;case ee.NormalKind:i=n=>n.getNormals();break;case ee.TangentKind:i=n=>n.getTangents();break;case ee.UVKind:i=n=>n.getUVs();break;default:return}for(let n=0;n0&&(pe.FromFloat32ArrayToRefScaled(t,Math.floor(i[d+f]*16),p,c),l.addToSelf(c));if(s&&a)for(f=0;f<4;f++)p=a[d+f],p>0&&(pe.FromFloat32ArrayToRefScaled(t,Math.floor(s[d+f]*16),p,c),l.addToSelf(c));u(r[h],r[h+1],r[h+2],l,o),o.toArray(r,h)}}class wvt{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=O.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Dvt{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new wvt,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 t9e,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class vr extends Yt{static get BILLBOARDMODE_NONE(){return Yt.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Yt.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Yt.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Yt.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Yt.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Yt.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 Dvt,this._waitingMaterialId=null,this.cullingStrategy=vr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new Ce,this.onCollisionPositionChangeObservable=new Ce,this.onMaterialChangedObservable=new Ce,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=Pe.Red(),this.outlineWidth=.02,this.overlayColor=Pe.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 O(.5,1,.5),this.ellipsoidOffset=new O(0,0,0),this.edgesWidth=1,this.edgesColor=new at(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 Ce,this._onCollisionPositionChange=(i,n,s=null)=>{n.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Qe.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Ci(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!==Yt.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 n=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;n=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(n)}_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,n){return this}updateVerticesData(e,t,i,n){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 vu(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(ee.MatricesIndicesKind)&&this.isVerticesDataPresent(ee.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Yt.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 n=new pe;(this.rotationQuaternion?this.rotationQuaternion:Oe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const a=O.Zero(),o=this.definedFacingForward?-1:1;return O.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,n,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const n=this.definedFacingForward?1:-1;return new O(e*n,t,i*n)}_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 vu(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(n){const o=n._vertexData||(n._vertexData={});return o[a]||this.copyVerticesData(a,o),o[a]}return this.getVerticesData(a)};if(t||(t=s(i)),!t)return null;if(n?(n._outputData?n._outputData.set(t):n._outputData=new Float32Array(t),t=n._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&Ivt(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){const a=s(ee.MatricesIndicesKind),o=s(ee.MatricesWeightsKind);if(o&&a){const l=this.numBoneInfluencers>4,c=l?s(ee.MatricesIndicesExtraKind):null,u=l?s(ee.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this);vr._ApplySkeleton(t,i,h,a,o,c,u)}}if(e.updatePositionsArray!==!1&&i===ee.PositionKind){const a=this._internalAbstractMeshDataInfo._positions||[],o=a.length;if(a.length=t.length/3,o1||!n.IsGlobal)&&n.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 n=this.getBoundingInfo(),s=e.getBoundingInfo();if(n.intersects(s,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 n;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const s=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=s;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=oe.Matrix[0],i=oe.Matrix[1];return pe.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,n=!1,s,a=!1){const o=new wl,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(n)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:O.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 g=0;g1&&!a&&!m.canIntersects(e))continue;const _=m.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=n.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),n.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:O.Zero()}e.depthSortedFacets=[];for(let o=0;oKi?s.maximum.x-s.minimum.x:Ki,e.bbSize.y=s.maximum.y-s.minimum.y>Ki?s.maximum.y-s.minimum.y:Ki,e.bbSize.z=s.maximum.z-s.minimum.z>Ki?s.maximum.z-s.minimum.z:Ki;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=s,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),O.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&vt.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;ls.subDiv.max||o<0||o>s.subDiv.max||l<0||l>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,n,s=!1,a=!0){const o=this.getWorldMatrix(),l=oe.Matrix[5];o.invertToRef(l);const c=oe.Vector3[8];O.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);const u=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,n,s,a);return n&&O.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,o,n),u}getClosestFacetAtLocalCoordinates(e,t,i,n,s=!1,a=!0){let o=null,l=0,c=0,u=0,h=0,d=0,f=0,p=0,g=0;const m=this.getFacetLocalPositions(),_=this.getFacetLocalNormals(),y=this.getFacetsAtLocalCoordinates(e,t,i);if(!y)return null;let v=Number.MAX_VALUE,x=v,b,C,A;for(let E=0;E=0||s&&!a&&h<=0)&&(h=C.x*A.x+C.y*A.y+C.z*A.z,d=-(C.x*e+C.y*t+C.z*i-h)/(C.x*C.x+C.y*C.y+C.z*C.z),f=e+C.x*d,p=t+C.y*d,g=i+C.z*d,l=f-e,c=p-t,u=g-i,x=l*l+c*c+u*u,xe.emitter===this)}}vr.OCCLUSION_TYPE_NONE=0;vr.OCCLUSION_TYPE_OPTIMISTIC=1;vr.OCCLUSION_TYPE_STRICT=2;vr.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;vr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;vr.CULLINGSTRATEGY_STANDARD=0;vr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;vr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;vr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;V([M_.filter((...[r,e,t,i,n])=>!Array.isArray(r)&&!Array.isArray(e)&&!Array.isArray(t)&&!Array.isArray(i)&&!Array.isArray(n))],vr,"_ApplySkeleton",null);xe("BABYLON.AbstractMesh",vr);class y3{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){ot.Clone(()=>e,this)}serialize(){return ot.Serialize(this)}parse(e,t,i){ot.Parse(()=>this,e,t,i)}}V([Q()],y3.prototype,"func",null);V([Q()],y3.prototype,"funcRef",null);V([Q()],y3.prototype,"funcMask",null);V([Q()],y3.prototype,"opStencilFail",null);V([Q()],y3.prototype,"opDepthFail",null);V([Q()],y3.prototype,"opStencilDepthPass",null);V([Q()],y3.prototype,"mask",null);V([Q()],y3.prototype,"enabled",null);function Yo(r){r.indexOf("vClipPlane")===-1&&r.push("vClipPlane"),r.indexOf("vClipPlane2")===-1&&r.push("vClipPlane2"),r.indexOf("vClipPlane3")===-1&&r.push("vClipPlane3"),r.indexOf("vClipPlane4")===-1&&r.push("vClipPlane4"),r.indexOf("vClipPlane5")===-1&&r.push("vClipPlane5"),r.indexOf("vClipPlane6")===-1&&r.push("vClipPlane6")}function x3(r,e,t){const i=!!(r.clipPlane??e.clipPlane),n=!!(r.clipPlane2??e.clipPlane2),s=!!(r.clipPlane3??e.clipPlane3),a=!!(r.clipPlane4??e.clipPlane4),o=!!(r.clipPlane5??e.clipPlane5),l=!!(r.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),n&&t.push("#define CLIPPLANE2"),s&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function i9e(r,e,t){let i=!1;const n=!!(r.clipPlane??e.clipPlane),s=!!(r.clipPlane2??e.clipPlane2),a=!!(r.clipPlane3??e.clipPlane3),o=!!(r.clipPlane4??e.clipPlane4),l=!!(r.clipPlane5??e.clipPlane5),c=!!(r.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==n&&(t.CLIPPLANE=n,i=!0),t.CLIPPLANE2!==s&&(t.CLIPPLANE2=s,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 wo(r,e,t){let i=e.clipPlane??t.clipPlane;RI(r,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,RI(r,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,RI(r,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,RI(r,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,RI(r,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,RI(r,"vClipPlane6",i)}function RI(r,e,t){t&&r.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const SMe=Pe.Black(),EMe={NUM_MORPH_INFLUENCERS:0};function Xo(r,e,t){if(!r||r.LOGARITHMICDEPTH||r.indexOf&&r.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&ge.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function ic(r,e,t,i=!1){t&&r.fogEnabled&&(!e||e.applyFog)&&r.fogMode!==0&&(t.setFloat4("vFogInfos",r.fogMode,r.fogStart,r.fogEnd,r.fogDensity),i?(r.fogColor.toLinearSpaceToRef(SMe,r.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",SMe)):t.setColor3("vFogColor",r.fogColor))}function tb(r,e,t){EMe.NUM_MORPH_INFLUENCERS=t,Iz(r,e,EMe)}function Iz(r,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&ei.LastCreatedEngine){const n=ei.LastCreatedEngine.getCaps().maxVertexAttribs,s=e.morphTargetManager;if(s!=null&&s.isUsingTextureForTargets)return;const a=s&&s.supportsNormals&&t.NORMAL,o=s&&s.supportsTangents&&t.TANGENT,l=s&&s.supportsUVs&&t.UV1;for(let c=0;cn&&ge.Error("Cannot add more vertex attributes for mesh "+e.name)}}function k_(r,e=!1){r.push("world0"),r.push("world1"),r.push("world2"),r.push("world3"),e&&(r.push("previousWorld0"),r.push("previousWorld1"),r.push("previousWorld2"),r.push("previousWorld3"))}function Np(r,e){const t=r.morphTargetManager;!r||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function tD(r,e){e.bindToEffect(r,"Scene")}function Is(r,e,t){e._needUVs=!0,e[t]=!0,r.optimizeUVAllocation&&r.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=r.coordinatesIndex+1,e["MAINUV"+(r.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function Ps(r,e,t){const i=r.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function iD(r,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&r.push("bakedVertexAnimationSettingsInstanced")}function Ovt(r,e){return e.set(r),e}function rc(r,e,t){if(!(!e||!r)&&(r.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(r.computeBonesUsingShaders=!1),r.useBones&&r.computeBonesUsingShaders&&r.skeleton)){const i=r.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const n=i.getTransformMatrixTexture(r);e.setTexture("boneSampler",n),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const n=i.getTransformMatrices(r);n&&(e.setMatrices("mBones",n),t&&r.getScene().prePassRenderer&&r.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[r.uniqueId]||(t.previousBones[r.uniqueId]=n.slice()),e.setMatrices("mPreviousBones",t.previousBones[r.uniqueId]),Ovt(n,t.previousBones[r.uniqueId])))}}}function r9e(r,e,t){r.transferToEffect(e,t+"")}function Pz(r,e,t,i,n,s=!0){r._bindLight(e,t,i,n,s)}function $u(r,e,t,i,n=4){const s=Math.min(e.lightSources.length,n);for(let a=0;a0&&(i.addCPUSkinningFallback(0,e),r.push("matricesIndices"),r.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(r.push("matricesIndicesExtra"),r.push("matricesWeightsExtra")))}function Do(r,e){(e.INSTANCES||e.THIN_INSTANCES)&&k_(r,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&r.push("instanceColor")}function Bl(r,e,t=4,i=0){let n=0;for(let s=0;s0&&(n=i+s,e.addFallback(n,"LIGHT"+s)),r.SHADOWS||(r["SHADOW"+s]&&e.addFallback(i,"SHADOW"+s),r["SHADOWPCF"+s]&&e.addFallback(i,"SHADOWPCF"+s),r["SHADOWPCSS"+s]&&e.addFallback(i,"SHADOWPCSS"+s),r["SHADOWPOISSON"+s]&&e.addFallback(i,"SHADOWPOISSON"+s),r["SHADOWESM"+s]&&e.addFallback(i,"SHADOWESM"+s),r["SHADOWCLOSEESM"+s]&&e.addFallback(i,"SHADOWCLOSEESM"+s));return n++}function WJ(r,e){return e.fogEnabled&&r.applyFog&&e.fogMode!==0}function Tu(r,e,t,i,n,s,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=n&&WJ(r,e),a.NONUNIFORMSCALING=r.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o)}function Xu(r,e,t,i,n=4,s=!1){if(!t._areLightsDirty)return t._needNormals;let a=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(r.lightsEnabled&&!s){for(const c of e.lightSources)if(wz(r,e,c,a,t,i,o),a++,a===n)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let c=a;c0&&(a.shadowEnabled=!0,o.prepareDefines(n,i))}}t.lightmapMode!=us.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,n["LIGHTMAPEXCLUDED"+i]=!0,n["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==us.LIGHTMAP_SHADOWSONLY):(n["LIGHTMAPEXCLUDED"+i]=!1,n["LIGHTMAPNOSPECULAR"+i]=!1)}function Mu(r,e,t,i,n,s=null,a=!1){let o=$J(r,i);s!==!1&&(o=i9e(t,r,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==n&&(i.INSTANCES=n,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function KJ(r,e){if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){e.NUM_BONE_INFLUENCERS=r.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(r.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=r.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=r.getScene().prePassRenderer;if(i&&i.enabled){const n=i.excludedSkinnedMesh.indexOf(r)===-1;e.BONES_VELOCITY_ENABLED=n}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function HJ(r,e){const t=r.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 y1e(r,e){const t=r.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function xo(r,e,t,i,n=!1,s=!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&&r.isVerticesDataPresent("normal"),e._needNormals&&r.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?r.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){const o=r.useVertexColors&&r.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=r.hasVertexAlpha&&o&&s}return r.isVerticesDataPresent("instanceColor")&&(r.hasInstances||r.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&KJ(r,e),n&&HJ(r,e),a&&y1e(r,e),!0}function rD(r,e){if(r.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=r.activeCamera.outputRenderTarget!==null&&r.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function jJ(r,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,n=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=r.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!r.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||n!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Dz(r,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const n=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_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:10,define:"PREPASS_NDC_DEPTH",index:"PREPASS_NDC_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(r.prePassRenderer&&r.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=r.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=r.prePassRenderer.generateNormalsInWorldSpace;for(let s=0;s{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const n=t||ei.LastCreatedScene;n&&(this._scene=n,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||Ie.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new pl(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Ci(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),tt.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 n=t.materialDefines;return n?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,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===tt.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===tt.MATERIAL_OPAQUE||this._transparencyMode===tt.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 n of i.subMeshes)if(n.getMaterial()===this)for(const s of n._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e)}e&&this.markAsDirty(tt.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(t??this.sideOrientation)===tt.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}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 n=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),n._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,tD(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 n=this._scene.getEngine();this._cachedDepthWriteState=n.getDepthWrite(),n.setDepthWrite(!1)}if(this.disableColorWrite){const n=this._scene.getEngine();this._cachedColorWriteState=n.getColorWrite(),n.setColorWrite(!1)}if(this.depthFunction!==0){const n=this._scene.getEngine();this._cachedDepthFunctionState=n.getDepthFunction()||0,n.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),tt._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const n of this.pluginManager._plugins){const s=e.pluginManager.getPlugin(n.name);s&&n.copyTo(s)}}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,n){const s={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(s.clipPlane&&(a.clipPlane=new Dc(0,0,0,1)),this._storeEffectOnSubMeshes){let u=!0,h=null;if(e.subMeshes){const d=new yc(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,s.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?h=d.effect.getCompilationError():(u=!1,setTimeout(l,16)))}u&&(this.allowShaderHotSwapping=o,h&&n&&n(h),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);s.clipPlane&&(a.clipPlane=c)};l()}forceCompilationAsync(e,t){return new Promise((i,n)=>{this.forceCompilation(e,()=>{i()},t,s=>{n(s)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(tt._DirtyCallbackArray.length=0,e&tt.TextureDirtyFlag&&tt._DirtyCallbackArray.push(tt._TextureDirtyCallBack),e&tt.LightDirtyFlag&&tt._DirtyCallbackArray.push(tt._LightsDirtyCallBack),e&tt.FresnelDirtyFlag&&tt._DirtyCallbackArray.push(tt._FresnelDirtyCallBack),e&tt.AttributesDirtyFlag&&tt._DirtyCallbackArray.push(tt._AttributeDirtyCallBack),e&tt.MiscDirtyFlag&&tt._DirtyCallbackArray.push(tt._MiscDirtyCallBack),e&tt.PrePassDirtyFlag&&tt._DirtyCallbackArray.push(tt._PrePassDirtyCallBack),tt._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(tt._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 n of i.subMeshes)if(n.getMaterial(!1)===this)for(const s of n._drawWrappers)!s||!s.defines||!s.defines.markAllAsDirty||this._materialContext===s.materialContext&&e(s.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(tt._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(tt._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(tt._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(tt._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(tt._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(tt._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(tt._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(tt._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(tt._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(tt._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 n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const s=this._parentContainer.materials.indexOf(this);s>-1&&this._parentContainer.materials.splice(s,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const s in this.meshMap){const a=this.meshMap[s];a&&(a.material=null,this.releaseVertexArrayObject(a,e))}else{const s=n.meshes;for(const a of s)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 n of e.subMeshes)i._releaseVertexArrayObject(n.effect),t&&n.effect&&n.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=ot.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 ge.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const s=Ie.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,n){var s;if(e.plugins)for(const a in e.plugins){const o=e.plugins[a];let l=(s=t.pluginManager)==null?void 0:s.getPlugin(o.name);if(!l){const c=Ie.Instantiate("BABYLON."+a);c&&(l=new c(t))}l==null||l.parse(o,i,n)}}}tt.TriangleFillMode=0;tt.WireFrameFillMode=1;tt.PointFillMode=2;tt.PointListDrawMode=3;tt.LineListDrawMode=4;tt.LineLoopDrawMode=5;tt.LineStripDrawMode=6;tt.TriangleStripDrawMode=7;tt.TriangleFanDrawMode=8;tt.ClockWiseSideOrientation=0;tt.CounterClockWiseSideOrientation=1;tt.TextureDirtyFlag=1;tt.LightDirtyFlag=2;tt.FresnelDirtyFlag=4;tt.AttributesDirtyFlag=8;tt.MiscDirtyFlag=16;tt.PrePassDirtyFlag=32;tt.AllDirtyFlag=63;tt.MATERIAL_OPAQUE=0;tt.MATERIAL_ALPHATEST=1;tt.MATERIAL_ALPHABLEND=2;tt.MATERIAL_ALPHATESTANDBLEND=3;tt.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;tt.MATERIAL_NORMALBLENDMETHOD_RNM=1;tt.OnEventObservable=new Ce;tt._AllDirtyCallBack=r=>r.markAllAsDirty();tt._ImageProcessingDirtyCallBack=r=>r.markAsImageProcessingDirty();tt._TextureDirtyCallBack=r=>r.markAsTexturesDirty();tt._FresnelDirtyCallBack=r=>r.markAsFresnelDirty();tt._MiscDirtyCallBack=r=>r.markAsMiscDirty();tt._PrePassDirtyCallBack=r=>r.markAsPrePassDirty();tt._LightsDirtyCallBack=r=>r.markAsLightDirty();tt._AttributeDirtyCallBack=r=>r.markAsAttributesDirty();tt._FresnelAndMiscDirtyCallBack=r=>{tt._FresnelDirtyCallBack(r),tt._MiscDirtyCallBack(r)};tt._TextureAndMiscDirtyCallBack=r=>{tt._TextureDirtyCallBack(r),tt._MiscDirtyCallBack(r)};tt._DirtyCallbackArray=[];tt._RunDirtyCallBacks=r=>{for(const e of tt._DirtyCallbackArray)e(r)};V([Q()],tt.prototype,"id",void 0);V([Q()],tt.prototype,"uniqueId",void 0);V([Q()],tt.prototype,"name",void 0);V([Q()],tt.prototype,"metadata",void 0);V([Q()],tt.prototype,"checkReadyOnEveryCall",void 0);V([Q()],tt.prototype,"checkReadyOnlyOnce",void 0);V([Q()],tt.prototype,"state",void 0);V([Q("alpha")],tt.prototype,"_alpha",void 0);V([Q("backFaceCulling")],tt.prototype,"_backFaceCulling",void 0);V([Q("cullBackFaces")],tt.prototype,"_cullBackFaces",void 0);V([Q()],tt.prototype,"sideOrientation",void 0);V([Q("alphaMode")],tt.prototype,"_alphaMode",void 0);V([Q()],tt.prototype,"_needDepthPrePass",void 0);V([Q()],tt.prototype,"disableDepthWrite",void 0);V([Q()],tt.prototype,"disableColorWrite",void 0);V([Q()],tt.prototype,"forceDepthWrite",void 0);V([Q()],tt.prototype,"depthFunction",void 0);V([Q()],tt.prototype,"separateCullingPass",void 0);V([Q("fogEnabled")],tt.prototype,"_fogEnabled",void 0);V([Q()],tt.prototype,"pointSize",void 0);V([Q()],tt.prototype,"zOffset",void 0);V([Q()],tt.prototype,"zOffsetUnits",void 0);V([Q()],tt.prototype,"pointsCloud",null);V([Q()],tt.prototype,"fillMode",null);V([Q()],tt.prototype,"useLogarithmicDepth",null);V([Q()],tt.prototype,"transparencyMode",null);class Tf extends tt{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=(...n)=>{const s=t.apply(e,n);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(n,s)=>{const a=i.apply(e,[n,s]);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&&n.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Tf(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,fn&&fn.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(n=>i.subMaterials.push(t.getLastMaterialById(n))),i}}xe("BABYLON.MultiMaterial",Tf);class n9e{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class x1e{}class Lvt{constructor(){this.visibleInstances={},this.batchCache=new Zue,this.batchCacheReplacementModeInFrozenMode=new Zue,this.instancesBufferSize=32*16*4}}class Zue{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Nvt{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Fvt{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 Re extends vr{static _GetDefaultSideOrientation(e){return e||Re.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(ee.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(ee.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 Ce),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new Ce),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new Ce),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new Ce),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new Ce),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 n=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),bc.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,n.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const s=e._ranges;for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&s[a]&&this.createAnimationRange(a,s[a].from,s[a].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,fn&&fn.HasTags(e)&&fn.AddTagsTo(this,fn.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 s=e.getDescendants(!0);for(let a=0;a{o&&c&&(this._uniformBuffer?this.transferToEffect(l):c.bindOnlyWorldMatrix(l))},n&&this._copySource(n,s,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 Ce(this._internalMeshDataInfo._onMeshReadyObserverAdded),n&&n.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const n=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));n.parent=e||this.parent,n.position=this.position.clone(),n.scaling=this.scaling.clone(),this.rotationQuaternion?n.rotationQuaternion=this.rotationQuaternion.clone():n.rotation=this.rotation.clone(),i&&i(this,n);for(const s of this.getChildTransformNodes(!0))s.getClassName()==="InstancedMesh"&&n.getClassName()==="Mesh"&&s.sourceMesh===this?s.instantiateHierarchy(n,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:n},i):s.instantiateHierarchy(n,t,i);return n}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 ge.Warn("You cannot use a mesh as LOD level twice"),this;const i=new n9e(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||n.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,s))return!1}else if(!p.isReady(this,s))return!1}}else if(!a.isReady(this,s))return!1}const o=i.currentRenderPassId;for(const f of this.lightSources){const p=f.getShadowGenerators();if(!p)continue;const g=p.values();for(let m=g.next();m.done!==!0;m=g.next()){const _=m.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 n=i.length;let s=!1;if(e)s=!0;else for(const a of this.subMeshes){if(a.indexStart+a.indexCount>n){s=!0;break}if(a.verticesStart+a.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new yc(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,n=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)yc.CreateFromIndices(0,n,s===e-1?t-n:i,this,void 0,!1),n+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,n){if(this._geometry)this._geometry.setVerticesData(e,t,i,n);else{const s=new vt;s.set(t,e);const a=this.getScene();new ul(ul.RandomId(),a,s,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=ul.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(ee.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(ee.PositionKind,i,!1,!1),t){const n=this.getIndices(),s=this.getVerticesData(ee.NormalKind);if(!s)return this;vt.ComputeNormals(i,n,s),this.updateVerticesData(ee.NormalKind,s,!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(ul.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let n=this._geometry;n||(n=new ul(ul.RandomId(),this.getScene(),void 0,void 0,this)),n.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const n=new vt;n.indices=e;const s=this.getScene();new ul(ul.RandomId(),s,n,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,n=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();let a;if(this._unIndexed)a=null;else switch(this._getRenderingFillMode(i)){case tt.PointFillMode:a=null;break;case tt.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case tt.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return this._bindDirect(t,a,n)}_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 s=this.getScene().getEngine();return this._unIndexed||t==tt.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==tt.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.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(),n=i._isInIntermediateRendering(),s=n?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),c=n?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,n,s){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.instancesBufferSizeb._distanceToCamera>C._distanceToCamera?-1:b._distanceToCamera1&&n.activeCamera===n.activeCameras[0]||s<=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=n.getEngine();let c=0,u=null;this.ignoreCameraMaxZ&&n.activeCamera&&!n._isInIntermediateRendering()&&(c=n.activeCamera.maxZ,u=n.activeCamera,n.activeCamera.maxZ=0,n.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,n.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,n.updateTransformMatrix(!0)),this}else if(!p.isReady(this,d))return u&&(u.maxZ=c,n.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((E=e._drawWrapper)!=null&&E._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return u&&(u.maxZ=c,n.updateTransformMatrix(!0)),this;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let g;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?g=e._drawWrapper:g=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const m=(g==null?void 0:g.effect)??null;for(const P of n._beforeRenderingMeshStage)P.action(this,e,o,m);if(!g||!m)return u&&(u.maxZ=c,n.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 P=_._getWorldMatrixDeterminant();y=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),P<0&&(y=y===tt.ClockWiseSideOrientation?tt.CounterClockWiseSideOrientation:tt.ClockWiseSideOrientation),f.sideOrientation=y}else y=f.sideOrientation;const v=this._internalMeshDataInfo._effectiveMaterial._preBind(g,y);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const x=this._internalMeshDataInfo._effectiveMaterial,b=x.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,m,b,!1);const C=_.getWorldMatrix();x._storeEffectOnSubMeshes?x.bindForSubMesh(C,this,e):x.bind(C,this),!x.backFaceCulling&&x.separateCullingPass&&(l.setState(!0,x.zOffset,!1,!v,x.cullBackFaces,x.stencil,x.zOffsetUnits),this._processRendering(this,e,m,b,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,m,b,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const P of n._afterRenderingMeshStage)P.action(this,e,o,m);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),u&&(u.maxZ=c,n.updateTransformMatrix(!0)),n.performancePriority===2&&!f.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(ee.MatricesWeightsKind)&&(this.isVerticesDataPresent(ee.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(ee.MatricesWeightsKind),t=e.length;for(let i=0;i_&&n++,b!==0&&v++,y+=b,_=b}if(c[v]++,v>a&&(a=v),y===0)s++;else{const x=1/y;let b=0;for(let C=0;Cu&&o++}}const h=this.skeleton.bones.length,d=this.getVerticesData(ee.MatricesIndicesKind),f=this.getVerticesData(ee.MatricesIndicesExtraKind);let p=0;for(let m=0;m=h||y<0)&&p++}const g="Number of Weights = "+i/4+` Maximum influences = `+a+` Missing Weights = `+s+` Not Sorted = `+n+` Not Normalized = `+o+` WeightCounts = [`+c+`] Number of bones = `+h+` Bad Bone Indices = `+p;return{skinned:!0,valid:s===0&&o===0&&p===0,report:g}}_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 Ie.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(n=>{n.refreshBoundingInfo(),n._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 n=this.getScene().multiMaterials;for(i=n.length-1;i>-1;i--)if(n[i].id===e)return this.material=n[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(ee.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(ee.PositionKind);const n=O.Zero();let s;for(s=0;s{const d=h.width,f=h.height,g=this.getEngine().createCanvas(d,f).getContext("2d");g.drawImage(h,0,0);const m=g.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(m,d,f,t,i,s,a,o),n&&n(this)};return Ie.LoadImage(e,u,l||(()=>{}),c.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,n,s,a,o,l=!1){if(!this.isVerticesDataPresent(ee.PositionKind)||!this.isVerticesDataPresent(ee.NormalKind)||!this.isVerticesDataPresent(ee.UVKind))return ge.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const c=this.getVerticesData(ee.PositionKind,!0,!0),u=this.getVerticesData(ee.NormalKind),h=this.getVerticesData(ee.UVKind);let d=O.Zero();const f=O.Zero(),p=Ne.Zero();a=a||Ne.Zero(),o=o||new Ne(1,1);for(let g=0;g{var c;return!((c=this.getVertexBuffer(l))!=null&&c.getIsInstanced())}),i=this.getIndices(),n={},s=(l,c)=>{const u=new Float32Array(i.length*c);let h=0;for(let d=0;d{const o=n.length-1-a,l=n[o];for(let c=0;c{for(let o=0;o-1&&(n.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(n.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(n.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let s=0;s4,c=l?this.getVerticesData(ee.MatricesIndicesExtraKind):null,u=l?this.getVerticesData(ee.MatricesWeightsExtraKind):null,h=e.getTransformMatrices(this),d=O.Zero(),f=new pe,p=new pe;let g=0,m;for(let _=0;_0&&(pe.FromFloat32ArrayToRefScaled(h,Math.floor(a[g+m]*16),y,p),f.addToSelf(p));if(l)for(m=0;m<4;m++)y=u[g+m],y>0&&(pe.FromFloat32ArrayToRefScaled(h,Math.floor(c[g+m]*16),y,p),f.addToSelf(p));O.TransformCoordinatesFromFloatsToRef(i._sourcePositions[_],i._sourcePositions[_+1],i._sourcePositions[_+2],f,d),d.toArray(n,_),t&&(O.TransformNormalFromFloatsToRef(i._sourceNormals[_],i._sourceNormals[_+1],i._sourceNormals[_+2],f,d),d.toArray(s,_)),f.reset()}return this.updateVerticesData(ee.PositionKind,n),t&&this.updateVerticesData(ee.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach(function(n){const a=n.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld,i=a.maximumWorld):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}),!t||!i?{min:O.Zero(),max:O.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?Re.MinMax(e):e;return O.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,n,s,a){return zJ(Re._MergeMeshesCoroutine(e,t,i,n,s,a,!1))}static MergeMeshesAsync(e,t=!0,i,n,s,a){return VJ(Re._MergeMeshesCoroutine(e,t,i,n,s,a,!0),ZBe())}static*_MergeMeshesCoroutine(e,t=!0,i,n,s,a,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let A=0;for(l=0;l=65536)return ge.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(s=!1);const c=new Array,u=new Array,h=new Array,d=e[0].sideOrientation;for(l=0;l{const E=A.computeWorldMatrix(!0);return{vertexData:vt.ExtractFromMesh(A,!1,!1),transform:E}},{vertexData:g,transform:m}=p(f);o&&(yield);const _=new Array(e.length-1);for(let A=1;A{throw Ji("GroundMesh")};Re._GoldbergMeshParser=(r,e)=>{throw Ji("GoldbergMesh")};Re._LinesMeshParser=(r,e)=>{throw Ji("LinesMesh")};Re._GreasedLineMeshParser=(r,e)=>{throw Ji("GreasedLineMesh")};Re._GreasedLineRibbonMeshParser=(r,e)=>{throw Ji("GreasedLineRibbonMesh")};Re._TrailMeshParser=(r,e)=>{throw Ji("TrailMesh")};xe("BABYLON.Mesh",Re);Re._instancedMeshFactory=(r,e)=>{const t=new W0(r,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class W0 extends vr{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&&Ie.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&&Ie.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&&Ie.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&&Ie.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||ge.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,n){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,n),this.sourceMesh}updateVerticesData(e,t,i,n){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,n),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 n=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,ee.PositionKind),n),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||ge.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!==Yt.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new pe);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,oe.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(oe.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 n=i.next();n.done!==!0;n=i.next())n.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=Dr.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=ot.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=ot.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)})),ot.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const n=Dn.Construct("Light_Type_"+e,t,i);return n||null}static Parse(e,t){const i=Dr.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=ot.Parse(i,e,t);if(e.excludedMeshesIds&&(n._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(n._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(n.falloffType=e.falloffType),e.lightmapMode!==void 0&&(n.lightmapMode=e.lightmapMode),e.animations){for(let s=0;s{const s=t.apply(e,n);for(const a of n)a._resyncLightSource(this);return s};const i=e.splice;e.splice=(n,s)=>{const a=i.apply(e,[n,s]);for(const o of a)o._resyncLightSource(this);return a};for(const n of e)n._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...n)=>{const s=t.apply(e,n);return this._resyncMeshes(),s};const i=e.splice;e.splice=(n,s)=>{const a=i.apply(e,[n,s]);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===Dr.INTENSITYMODE_AUTOMATIC&&(t===Dr.LIGHTTYPEID_DIRECTIONALLIGHT?i=Dr.INTENSITYMODE_ILLUMINANCE:i=Dr.INTENSITYMODE_LUMINOUSINTENSITY),t){case Dr.LIGHTTYPEID_POINTLIGHT:case Dr.LIGHTTYPEID_SPOTLIGHT:switch(i){case Dr.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Dr.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Dr.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case Dr.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Dr.INTENSITYMODE_ILLUMINANCE:e=1;break;case Dr.INTENSITYMODE_LUMINANCE:{let n=this.radius;n=Math.max(n,.001),e=2*Math.PI*(1-Math.cos(n));break}}break;case Dr.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Dr.FALLOFF_DEFAULT=us.FALLOFF_DEFAULT;Dr.FALLOFF_PHYSICAL=us.FALLOFF_PHYSICAL;Dr.FALLOFF_GLTF=us.FALLOFF_GLTF;Dr.FALLOFF_STANDARD=us.FALLOFF_STANDARD;Dr.LIGHTMAP_DEFAULT=us.LIGHTMAP_DEFAULT;Dr.LIGHTMAP_SPECULAR=us.LIGHTMAP_SPECULAR;Dr.LIGHTMAP_SHADOWSONLY=us.LIGHTMAP_SHADOWSONLY;Dr.INTENSITYMODE_AUTOMATIC=us.INTENSITYMODE_AUTOMATIC;Dr.INTENSITYMODE_LUMINOUSPOWER=us.INTENSITYMODE_LUMINOUSPOWER;Dr.INTENSITYMODE_LUMINOUSINTENSITY=us.INTENSITYMODE_LUMINOUSINTENSITY;Dr.INTENSITYMODE_ILLUMINANCE=us.INTENSITYMODE_ILLUMINANCE;Dr.INTENSITYMODE_LUMINANCE=us.INTENSITYMODE_LUMINANCE;Dr.LIGHTTYPEID_POINTLIGHT=us.LIGHTTYPEID_POINTLIGHT;Dr.LIGHTTYPEID_DIRECTIONALLIGHT=us.LIGHTTYPEID_DIRECTIONALLIGHT;Dr.LIGHTTYPEID_SPOTLIGHT=us.LIGHTTYPEID_SPOTLIGHT;Dr.LIGHTTYPEID_HEMISPHERICLIGHT=us.LIGHTTYPEID_HEMISPHERICLIGHT;V([qr()],Dr.prototype,"diffuse",void 0);V([qr()],Dr.prototype,"specular",void 0);V([Q()],Dr.prototype,"falloffType",void 0);V([Q()],Dr.prototype,"intensity",void 0);V([Q()],Dr.prototype,"range",null);V([Q()],Dr.prototype,"intensityMode",null);V([Q()],Dr.prototype,"radius",null);V([Q()],Dr.prototype,"_renderPriority",void 0);V([Ke("_reorderLightsInScene")],Dr.prototype,"renderPriority",void 0);V([Q("shadowEnabled")],Dr.prototype,"_shadowEnabled",void 0);V([Q("excludeWithLayerMask")],Dr.prototype,"_excludeWithLayerMask",void 0);V([Q("includeOnlyWithLayerMask")],Dr.prototype,"_includeOnlyWithLayerMask",void 0);V([Q("lightmapMode")],Dr.prototype,"_lightmapMode",void 0);class s9e extends vo{}class a9e{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 Lz extends vo{constructor(e){super(),this._wasAddedToScene=!1,e=e||ei.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 W0){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 n=[],s=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(s.push(o),t.delete(l))}const a=s;for(;a.length>0;){const o=a.shift();n.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&&(ge.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>ge.Error(o.name))),n}_addNodeAndDescendantsToList(e,t,i,n){if(!(!i||n&&!n(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,n)}}_isNodeInContainer(e){return e instanceof vr&&this.meshes.indexOf(e)!==-1||e instanceof Yt&&this.transformNodes.indexOf(e)!==-1||e instanceof Dr&&this.lights.indexOf(e)!==-1||e instanceof di&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return ge.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 ge.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 ge.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 ge.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ie.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},s={},a=new a9e,o=[],l=[],c={doNotInstantiate:!0,...i},u=(g,m)=>{if(n[g.uniqueId]=m.uniqueId,s[m.uniqueId]=m,e&&(m.name=e(g.name)),m instanceof Re){const _=m;if(_.morphTargetManager){const y=g.morphTargetManager;_.morphTargetManager=y.clone();for(let v=0;v{if(u(g,m),g.parent){const _=n[g.parent.uniqueId],y=s[_];y?m.parent=y:m.parent=g.parent}if(m.position&&g.position&&m.position.copyFrom(g.position),m.rotationQuaternion&&g.rotationQuaternion&&m.rotationQuaternion.copyFrom(g.rotationQuaternion),m.rotation&&g.rotation&&m.rotation.copyFrom(g.rotation),m.scaling&&g.scaling&&m.scaling.copyFrom(g.scaling),m.material){const _=m;if(_.material)if(t){const y=g.material;if(l.indexOf(y)===-1){let v=y.clone(e?e(y.name):"Clone of "+y.name);if(l.push(y),n[y.uniqueId]=v.uniqueId,s[v.uniqueId]=v,y.getClassName()==="MultiMaterial"){const x=y;for(const b of x.subMaterials)b&&(v=b.clone(e?e(b.name):"Clone of "+b.name),l.push(b),n[b.uniqueId]=v.uniqueId,s[v.uniqueId]=v);x.subMaterials=x.subMaterials.map(b=>b&&s[n[b.uniqueId]])}}_.getClassName()!=="InstancedMesh"&&(_.material=s[n[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)}m.parent===null&&a.rootNodes.push(m)};return f.forEach(g=>{if(g.getClassName()==="InstancedMesh"){const m=g,_=m.sourceMesh,y=n[_.uniqueId],x=(typeof y=="number"?s[y]:_).createInstance(m.name);p(m,x)}else{let m=!0;g.getClassName()==="TransformNode"||g.getClassName()==="Node"||g.skeleton||!g.getTotalVertices||g.getTotalVertices()===0?m=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?m=!c.doNotInstantiate(g):m=!c.doNotInstantiate);const _=m?g.createInstance(`instance of ${g.name}`):g.clone(`Clone of ${g.name}`,null,!0);if(!_)throw new Error(`Could not clone or instantiate node on Asset Container ${g.name}`);p(g,_)}}),this.skeletons.forEach(g=>{if(c.predicate&&!c.predicate(g))return;const m=g.clone(e?e(g.name):"Clone of "+g.name);for(const _ of this.meshes)if(_.skeleton===g&&!_.isAnInstance){const y=s[n[_.uniqueId]];if(!y||y.isAnInstance||(y.skeleton=m,o.indexOf(m)!==-1))continue;o.push(m);for(const v of m.bones)v._linkedTransformNode&&(v._linkedTransformNode=s[n[v._linkedTransformNode.uniqueId]])}a.skeletons.push(m)}),this.animationGroups.forEach(g=>{if(c.predicate&&!c.predicate(g))return;const m=g.clone(e?e(g.name):"Clone of "+g.name,_=>s[n[_.uniqueId]]||_);a.animationGroups.push(m)}),a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ie.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()||Ie.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 n of e){let s=!0;if(i){for(const a of i)if(n===a){s=!1;break}}s&&(t.push(n),n._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new s9e);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 Re("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=ei.LastCreatedScene,t,i=null){if(!e)return ge.Error("No scene available to merge animations to"),[];const n=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=n(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,n)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=n(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 n=t.pop();if(n instanceof Re?(n.geometry&&this.geometries.indexOf(n.geometry)===-1&&this.geometries.push(n.geometry),this.meshes.push(n)):n instanceof Yt?this.transformNodes.push(n):n instanceof Dr?this.lights.push(n):n instanceof di&&this.cameras.push(n),n instanceof vr){if(n.material&&this.materials.indexOf(n.material)===-1){this.materials.push(n.material);for(const s of n.material.getActiveTextures())this.textures.indexOf(s)===-1&&this.textures.push(s)}n.skeleton&&this.skeletons.indexOf(n.skeleton)===-1&&this.skeletons.push(n.skeleton),n.morphTargetManager&&this.morphTargetManagers.indexOf(n.morphTargetManager)===-1&&this.morphTargetManagers.push(n.morphTargetManager)}for(const s of n.getChildren())i.has(s)||t.push(s);i.add(n)}this.populateRootNodes()}}class Bvt{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||ei.LastCreatedScene,!!e){if(this._scene=e,!Qe.audioEngine){Ie.Warn("No audio engine initialized, failed to create an audio analyser");return}this._audioEngine=Qe.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(r,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 Ce,this.onAudioLockedObservable=new Ce,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!dl())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const n=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{n&&n.canPlayType&&(n.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||n.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{n&&n.canPlayType&&n.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,ge.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 vp{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=Qe.audioEngine)!=null&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:Qe.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,n=null,s){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 Ce,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=O.Zero(),this._localDirection=new O(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||ei.LastCreatedScene,!!i)if(this._scene=i,vp._SceneComponentInitialization(i),this._readyToPlayCallback=n,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&&ge.Error("XHR "+d.status+" error on: "+h+"."),ge.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)):ge.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{ge.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Qe.audioEngine&&!Qe.audioEngine.WarnedWebAudioUnsupported&&(ge.Error("Web Audio is not supported by your browser."),Qe.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(e=Qe.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=Qe.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=Qe.audioEngine)!=null&&t.audioContext&&Qe.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{ge.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;(t=Qe.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=Qe.audioEngine)!=null&&e.canUseWebAudio&&Qe.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Qe.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=Qe.audioEngine)!=null&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(t=Qe.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=Qe.audioEngine)!=null&&u.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,p;(f=Qe.audioEngine)==null||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(p=Qe.audioEngine)==null?void 0:p.onAudioUnlockedObservable.addOnce(()=>{c()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(h=Qe.audioEngine)==null?void 0:h.onAudioUnlockedObservable.addOnce(()=>{c()}))};c()}}else{const c=()=>{var u,h,d;if((u=Qe.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=Qe.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=Qe.audioEngine)==null?void 0:d.audioContext.currentTime)+e:Qe.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=Qe.audioEngine)==null?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var u;((u=Qe.audioEngine)==null?void 0:u.audioContext.state)==="suspended"?(Qe.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Qe.audioEngine.onAudioUnlockedObservable.addOnce(()=>{c()}))):c()},500):c()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){ge.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=Qe.audioEngine)!=null&&t.audioContext&&this._soundSource){const i=e?Qe.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=Qe.audioEngine)!=null&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Qe.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(i=Qe.audioEngine)!=null&&i.canUseWebAudio&&this._soundGain&&(t&&Qe.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Qe.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Qe.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Qe.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 n=e.getBoundingInfo();this.setPosition(n.boundingSphere.centerWorld)}(t=Qe.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 vp(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,n){const s=e.name;let a;e.url?a=i+e.url:a=i+s;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(!n)l=new vp(s,a,t,()=>{t.removePendingData(l)},o),t.addPendingData(l);else{const c=()=>{n._isReadyToPlay?(l._audioBuffer=n.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(c,300)};l=new vp(s,new ArrayBuffer(0),t,null,o),c()}if(e.position){const c=O.FromArray(e.position);l.setPosition(c)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const c=O.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=Qe.audioEngine)==null||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}vp._SceneComponentInitialization=r=>{throw Ji("AudioSceneComponent")};xe("BABYLON.Sound",vp);class l9e{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||ei.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=Qe.audioEngine)!=null&&e.canUseWebAudio&&Qe.audioEngine.audioContext&&(this._outputAudioNode=Qe.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Qe.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Qe.audioEngine&&Qe.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=Qe.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=Qe.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if((e=Qe.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t{var a;let n=[],s;if(t.sounds=t.sounds||[],r.sounds!==void 0&&r.sounds!==null)for(let o=0,l=r.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&&(n=t.activeCameras[0]),this.audioListenerPositionProvider){const a=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(a.x||0,a.y||0,a.z||0)}else n?this._cachedCameraPosition.equals(n.globalPosition)||(this._cachedCameraPosition.copyFrom(n.globalPosition),i.audioContext.listener.setPosition(n.globalPosition.x,n.globalPosition.y,n.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 n?(n.rigCameras&&n.rigCameras.length>0&&(n=n.rigCameras[0]),n.getViewMatrix().invertToRef(this._invertMatrixTemp),O.TransformNormalToRef(Jh._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 s;for(s=0;s{let e=r._getComponent(bt.NAME_AUDIO);e||(e=new Jh(r),r._addComponent(e))};class c9e{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 n=0;for(const a of i)n+=a;const s=n>0?1/n: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 ot.Serialize(this)}parse(e,t,i){ot.Parse(()=>this,e,t,i)}}V([ki(),Ke("_markSubMeshesAsAttributesDirty")],nT.prototype,"texture",void 0);V([Q(),Ke("_markSubMeshesAsAttributesDirty")],nT.prototype,"isEnabled",void 0);V([Q()],nT.prototype,"animationParameters",void 0);V([Q()],nT.prototype,"time",void 0);class Iv{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=Fu.Zero(),this._cachedBaseSize=Fu.Zero(),this._initialSamplingMode=2,this._texture=Iv._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 gZ(r,e,t=!1,i){switch(r){case 3:{const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&s.set(new Int8Array(i)),s}case 0:{const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}case 4:{const s=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&s.set(new Int16Array(i)),s}case 5:case 8:case 9:case 10:case 2:{const s=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&s.set(new Uint16Array(i)),s}case 6:{const s=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&s.set(new Int32Array(i)),s}case 7:case 11:case 12:case 13:case 14:case 15:{const s=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&s.set(new Uint32Array(i)),s}case 1:{const s=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&s.set(new Float32Array(i)),s}}const n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&n.set(new Uint8Array(i)),n}ir.prototype._readTexturePixelsSync=function(r,e,t,i=-1,n=0,s=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=r._hardwareTexture)==null?void 0:d.underlyingResource,n):u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,(f=r._hardwareTexture)==null?void 0:f.underlyingResource,n);let h=r.type!==void 0?this._getWebGLTextureType(r.type):u.UNSIGNED_BYTE;if(o)s||(s=gZ(r.type,4*e*t));else switch(h){case u.UNSIGNED_BYTE:s||(s=new Uint8Array(4*e*t)),h=u.UNSIGNED_BYTE;break;default:s||(s=new Float32Array(4*e*t)),h=u.FLOAT;break}return a&&this.flushFramebuffer(),u.readPixels(l,c,e,t,u.RGBA,h,s),u.bindFramebuffer(u.FRAMEBUFFER,this._currentFramebuffer),s};ir.prototype._readTexturePixels=function(r,e,t,i=-1,n=0,s=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(r,e,t,i,n,s,a,o,l,c))};class Cn extends Iv{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=Xh()),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=Cn.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 Ce,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Cn._IsScene(e)?this._scene=e:this._engine=e:this._scene=ei.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 pe.IdentityReadOnly}getReflectionTextureMatrix(){return pe.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,s,a){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!s,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=ot.Serialize(this);return ot.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let n=0;n{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Cn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;V([Q()],Cn.prototype,"uniqueId",void 0);V([Q()],Cn.prototype,"name",void 0);V([Q()],Cn.prototype,"metadata",void 0);V([Q("hasAlpha")],Cn.prototype,"_hasAlpha",void 0);V([Q("getAlphaFromRGB")],Cn.prototype,"_getAlphaFromRGB",void 0);V([Q()],Cn.prototype,"level",void 0);V([Q("coordinatesIndex")],Cn.prototype,"_coordinatesIndex",void 0);V([Q()],Cn.prototype,"optimizeUVAllocation",void 0);V([Q("coordinatesMode")],Cn.prototype,"_coordinatesMode",void 0);V([Q()],Cn.prototype,"wrapU",null);V([Q()],Cn.prototype,"wrapV",null);V([Q()],Cn.prototype,"wrapR",void 0);V([Q()],Cn.prototype,"anisotropicFilteringLevel",void 0);V([Q()],Cn.prototype,"isCube",null);V([Q()],Cn.prototype,"is3D",null);V([Q()],Cn.prototype,"is2DArray",null);V([Q()],Cn.prototype,"gammaSpace",null);V([Q()],Cn.prototype,"invertZ",void 0);V([Q()],Cn.prototype,"lodLevelInAlpha",void 0);V([Q()],Cn.prototype,"lodGenerationOffset",null);V([Q()],Cn.prototype,"lodGenerationScale",null);V([Q()],Cn.prototype,"linearSpecularLOD",null);V([ki()],Cn.prototype,"irradianceTexture",null);V([Q()],Cn.prototype,"isRenderTarget",void 0);function XJ(r,e,t=!1){const i=e.width,n=e.height;if(r instanceof Float32Array){let c=r.byteLength/r.BYTES_PER_ELEMENT;const u=new Uint8Array(c);for(;--c>=0;){let h=r[c];h<0?h=0:h>1&&(h=1),u[c]=h*255}r=u}const s=document.createElement("canvas");s.width=i,s.height=n;const a=s.getContext("2d");if(!a)return null;const o=a.createImageData(i,n);if(o.data.set(r),a.putImageData(o,0,0),t){const c=document.createElement("canvas");c.width=i,c.height=n;const u=c.getContext("2d");return u?(u.translate(0,n),u.scale(1,-1),u.drawImage(s,0,0),c.toDataURL("image/png")):null}return s.toDataURL("image/png")}function b1e(r,e=0,t=0){const i=r.getInternalTexture();if(!i)return null;const n=r._readPixelsSync(e,t);return n?XJ(n,r.getSize(),i.invertY):null}async function C1e(r,e=0,t=0){const i=r.getInternalTexture();if(!i)return null;const n=await r.readPixels(e,t);return n?XJ(n,r.getSize(),i.invertY):null}const kvt={GenerateBase64StringFromPixelData:XJ,GenerateBase64StringFromTexture:b1e,GenerateBase64StringFromTextureAsync:C1e};class be extends Cn{static _CreateVideoTexture(e,t,i,n=!1,s=!1,a=be.TRILINEAR_SAMPLINGMODE,o={},l,c=5){throw Ji("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,n,s=be.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 Ce,this._isBlocking=!0,this.name=e||"",this.url=e;let g,m=!1,_=null,y=!0;typeof i=="object"&&i!==null?(g=i.noMipmap??!1,n=i.invertY??!bn,s=i.samplingMode??be.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,m=i.useSRGBBuffer??!1,_=i.internalTexture??null,y=i.gammaSpace??y):g=!!i,this._gammaSpace=y,this._noMipmap=g,this._invertY=n===void 0?!bn:n,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=c,this._mimeType=h,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=m,this._forcedExtension=p,u&&(this._format=u);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const b=()=>{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()},C=(A,E)=>{this._loadingError=!0,this._errorObject={message:A,exception:E},o&&o(A,E),be.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!_){this._delayedOnLoad=b,this._delayedOnError=C;return}if(this._texture=_??this._getFromCache(this.url,g,s,this._invertY,m,this.isCube),this._texture)if(this._texture.isReady)nw.SetImmediate(()=>b());else{const A=this._texture.onLoadedObservable.add(b);this._texture.onErrorObservable.add(E=>{var P;C(E.message,E.exception),(P=this._texture)==null||P.onLoadedObservable.remove(A)})}else if(!v||!v.useDelayedTextureLoading){try{this._texture=x.createTexture(this.url,g,this._invertY,v,s,b,C,this._buffer,void 0,this._format,this._forcedExtension,h,d,f,m)}catch(A){throw C("error loading",A),A}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=b,this._delayedOnError=C}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,s=>s.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,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?nw.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,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,O.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,n.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,n.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=pe.Zero(),this._rowGenerationMatrix=new pe,this._t0=O.Zero(),this._t1=O.Zero(),this._t2=O.Zero()),pe.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(pe.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,oe.Matrix[0]),pe.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,oe.Matrix[1]),pe.ScalingToRef(this._cachedUScale,this._cachedVScale,0,oe.Matrix[2]),pe.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,oe.Matrix[3]),oe.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(oe.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(oe.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(oe.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),pe.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,n=>n.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===be.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=pe.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=pe.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 be.PLANAR_MODE:{pe.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 be.PROJECTION_MODE:{pe.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:pe.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 ot.Clone(()=>new be(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i;const e=this.name;be.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(be._SerializeInternalTextureUniqueId);return t?((be.SerializeBuffers||be.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,"+Sz(this._buffer):(be.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?b1e(this):C1e(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,be._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=X9.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 be._CubeTextureParser(e,t,i);const n=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!n)return null;let s;if(n){const l=t.getEngine().getLoadedTexturesCache();for(const c of l)if(c.uniqueId===e.internalTextureUniqueId){s=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=be._CreateMirror(e.name,e.renderTargetSize,t,l);return c._waitingRenderList=e.renderList,c.mirrorPlane=Dc.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:")||be.UseSerializedUrlIfAny)&&(u=e.url);const h={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{a(c)},internalTexture:s};c=new be(u,t,h)}return c}},e,t)}static CreateFromBase64String(e,t,i,n,s,a=be.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,u,h){return new be("data:"+t,i,n,s,a,o,l,e,!1,c,void 0,void 0,u,h)}static LoadFromDataString(e,t,i,n=!1,s,a=!0,o=be.TRILINEAR_SAMPLINGMODE,l=null,c=null,u=5,h,d){return e.substr(0,5)!=="data:"&&(e="data:"+e),new be(e,i,s,a,o,l,c,t,n,u,void 0,void 0,h,d)}}be.SerializeBuffers=!0;be.ForceSerializeBuffers=!1;be.OnTextureLoadErrorObservable=new Ce;be._SerializeInternalTextureUniqueId=!1;be._CubeTextureParser=(r,e,t)=>{throw Ji("CubeTexture")};be._CreateMirror=(r,e,t,i)=>{throw Ji("MirrorTexture")};be._CreateRenderTargetTexture=(r,e,t,i,n)=>{throw Ji("RenderTargetTexture")};be.NEAREST_SAMPLINGMODE=1;be.NEAREST_NEAREST_MIPLINEAR=8;be.BILINEAR_SAMPLINGMODE=2;be.LINEAR_LINEAR_MIPNEAREST=11;be.TRILINEAR_SAMPLINGMODE=3;be.LINEAR_LINEAR_MIPLINEAR=3;be.NEAREST_NEAREST_MIPNEAREST=4;be.NEAREST_LINEAR_MIPNEAREST=5;be.NEAREST_LINEAR_MIPLINEAR=6;be.NEAREST_LINEAR=7;be.NEAREST_NEAREST=1;be.LINEAR_NEAREST_MIPNEAREST=9;be.LINEAR_NEAREST_MIPLINEAR=10;be.LINEAR_LINEAR=2;be.LINEAR_NEAREST=12;be.EXPLICIT_MODE=0;be.SPHERICAL_MODE=1;be.PLANAR_MODE=2;be.CUBIC_MODE=3;be.PROJECTION_MODE=4;be.SKYBOX_MODE=5;be.INVCUBIC_MODE=6;be.EQUIRECTANGULAR_MODE=7;be.FIXED_EQUIRECTANGULAR_MODE=8;be.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;be.CLAMP_ADDRESSMODE=0;be.WRAP_ADDRESSMODE=1;be.MIRROR_ADDRESSMODE=2;be.UseSerializedUrlIfAny=!1;V([Q()],be.prototype,"url",void 0);V([Q()],be.prototype,"uOffset",void 0);V([Q()],be.prototype,"vOffset",void 0);V([Q()],be.prototype,"uScale",void 0);V([Q()],be.prototype,"vScale",void 0);V([Q()],be.prototype,"uAng",void 0);V([Q()],be.prototype,"vAng",void 0);V([Q()],be.prototype,"wAng",void 0);V([Q()],be.prototype,"uRotationCenter",void 0);V([Q()],be.prototype,"vRotationCenter",void 0);V([Q()],be.prototype,"wRotationCenter",void 0);V([Q()],be.prototype,"homogeneousRotationInUVTransform",void 0);V([Q()],be.prototype,"isBlocking",null);xe("BABYLON.Texture",be);ot._TextureParser=be.Parse;ir.prototype.updateRawTexture=function(r,e,t,i,n=null,s=0,a=!1){if(!r)return;const o=this._getRGBABufferInternalSizedFormat(s,t,a),l=this._getInternalFormat(t),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,r,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(r._bufferView=e,r.format=t,r.type=s,r.invertY=i,r._compression=n),r.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],r.width,r.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,r.width,r.height,0,l,c,e),r.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r.isReady=!0};ir.prototype.createRawTexture=function(r,e,t,i,n,s,a,o=null,l=0,c=0,u=!1){const h=new _n(this,3);h.baseWidth=e,h.baseHeight=t,h.width=e,h.height=t,h.format=i,h.generateMipMaps=n,h.samplingMode=a,h.invertY=s,h._compression=o,h.type=l,h._useSRGBBuffer=this._getUseSRGBBuffer(u,!n),this._doNotHandleContextLost||(h._bufferView=r),this.updateRawTexture(h,r,i,s,o,l,h._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0);const d=this._getSamplingParameters(a,n);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),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(h),h};ir.prototype.createRawCubeTexture=function(r,e,t,i,n,s,a,o=null){const l=this._gl,c=new _n(this,8);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=r);const u=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);h===l.RGB&&(h=l.RGBA),u===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(n=!1,a=1,ge.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?(n=!1,a=1,ge.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?(n=!1,ge.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):u===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(n=!1,ge.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=s,c._compression=o,!this.needPOTTextures||$k(c.width)&&$k(c.height)||(n=!1),r)this.updateRawCubeTexture(c,r,t,i,s,o);else{const m=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,_,m,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),r&&n&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const g=this._getSamplingParameters(a,n);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,g.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,g.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=n,c.samplingMode=a,c.isReady=!0,c};ir.prototype.updateRawCubeTexture=function(r,e,t,i,n,s=null,a=0){r._bufferViewArray=e,r.format=t,r.type=i,r.invertY=n,r._compression=s;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,r,!0),this._unpackFlipY(n===void 0?!0:!!n),r.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let p=e[f];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,this.getCaps().s3tc[s],r.width,r.height,0,p):(h&&(p=u9e(p,r.width,r.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,a,u,r.width,r.height,0,c,l,p))}(!this.needPOTTextures||$k(r.width)&&$k(r.height))&&r.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),r.isReady=!0};ir.prototype.createRawCubeTextureFromUrl=function(r,e,t,i,n,s,a,o,l=null,c=null,u=3,h=!1){const d=this._gl,f=this.createRawCubeTexture(null,t,i,n,!s,h,u,null);e==null||e.addPendingData(f),f.url=r,f.isReady=!1,this._internalTexturesCache.push(f);const p=(m,_)=>{e==null||e.removePendingData(f),c&&m&&c(m.status+" "+m.statusText,_)},g=m=>{const _=f.width,y=a(m);if(y){if(o){const v=this._getWebGLTextureType(n);let x=this._getInternalFormat(i);const b=this._getRGBABufferInternalSizedFormat(n);let C=!1;x===d.RGB&&(x=d.RGBA,C=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const A=o(y);for(let E=0;E>E;for(let w=0;w<6;w++){let M=A[E][w];C&&(M=u9e(M,P,P,n)),d.texImage2D(w,E,b,P,P,0,x,v,M)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,y,i,n,h);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(r,m=>{g(m)},void 0,e==null?void 0:e.offlineProvider,!0,p),f};function u9e(r,e,t,i){let n,s=1;i===1?n=new Float32Array(e*t*4):i===2?(n=new Uint16Array(e*t*4),s=15360):i===7?n=new Uint32Array(e*t*4):n=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 n in this._ranges)i&&(t+=", ",i=!1),t+=n;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 n=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),n=!0),!!n){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const s of this.bones)s.getParent()||(s.getBindMatrix().multiplyToRef(i,oe.Matrix[1]),s._updateAbsoluteBindMatrices(oe.Matrix[1]));if(this.isUsingTextureForMatrices){const s=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==s)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=Vs.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=Vs.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=n.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 Ig(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=O.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let n;for(n=0;n-1&&(o=i.bones[s.parentBoneIndex]);const l=s.rest?pe.FromArray(s.rest):null,c=new ys(s.name,i,o,pe.FromArray(s.matrix),l,null,a);s.id!==void 0&&s.id!==null&&(c.id=s.id),s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(dt.Parse(s.animation)),s.linkedTransformNodeId!==void 0&&s.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=s.linkedTransformNodeId)}if(e.ranges)for(n=0;n0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class Uvt{constructor(e,t){this._scene=e,t instanceof Ig?(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 n=0;const s=(t+1)*4*4*i,a=new Float32Array(s);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,n++);return a}async _executeAnimationFrame(e,t,i){return new Promise((n,s)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,()=>{const a=this._skeleton.getTransformMatrices(this._mesh);e.set(a,i*a.length),n()})})}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=Vs.CreateRGBATexture(e,(t+1)*4,e.length/((t+1)*4*4),this._scene,!1,!1,be.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,n=e.length/((t+1)*4*4);return{vertexData:Sz(e),width:i,height:n}}loadBakedVertexDataFromObject(e){return new Float32Array(Ez(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class f9e{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===Wt.POINTERDOWN){this._isPointerDown=!0;return}i.type===Wt.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=hn.Now;let n=0;this._lastFrameTime!=null&&(n=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const s=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(n/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??hn.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const n=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=n*.05,this.upperRadiusTransitionRange=n*.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||(vx.EasingFunction.setEasingMode(vx.EasingMode),this._radiusBounceTransition=dt.CreateAnimation("radius",dt.ANIMATIONTYPE_FLOAT,60,vx.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=dt.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()}}vx.EasingFunction=new XBe(.3);vx.EasingMode=Ja.EASINGMODE_EASEOUT;class Vh{constructor(){this.onTargetFramingAnimationEndObservable=new Ce,this._mode=Vh.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();Vh.EasingFunction.setEasingMode(Vh.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Wt.POINTERDOWN){this._isPointerDown=!0;return}i.type===Wt.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 n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const n=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a{this.stopAllAnimations(),n&&n(),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 n=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===Vh.IgnoreBoundsSizeMode&&(n=ni.upperRadiusLimit?i.upperRadiusLimit:n),n}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=hn.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=dt.CreateAnimation("beta",dt.ANIMATIONTYPE_FLOAT,60,Vh.EasingFunction));const n=dt.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});n&&this._animatables.push(n)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=hn.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}}Vh.EasingFunction=new YBe;Vh.EasingMode=Ja.EASINGMODE_EASEINOUT;Vh.IgnoreBoundsSizeMode=0;Vh.FitFrustumSidesMode=1;class II{constructor(e,t=new O,i=0,n=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=n}}class zvt{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new II(O.Up()),new II(O.Down()),new II(O.Left()),new II(O.Right()),new II(O.Forward()),new II(O.Forward().scaleInPlace(-1))],this._tmpMatrix=new pe,this._tmpVector=new O,this._zeroVector=O.Zero(),this._lookAtTmpMatrix=new pe}init(){}_closestFace(e){return this._faceVectors.forEach(t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=Oe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),O.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=O.GetAngleBetweenVectors(t.rotatedDirection,e,O.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),O.TransformCoordinatesToRef(O.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach(s=>{i.direction.x&&s.direction.x&&(s.ignore=!0),i.direction.y&&s.direction.y&&(s.ignore=!0),i.direction.z&&s.direction.z&&(s.ignore=!0)});const n=this._closestFace(this._tmpVector);this._faceVectors.forEach(s=>{s.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=Oe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,n.rotatedDirection,this._ui.rotationQuaternion),n.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),n.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),n.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 Vvt{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 wr{constructor(e,t,i=Number.MAX_VALUE,n=Ki){this.origin=e,this.direction=t,this.length=i,this.epsilon=n}clone(){return new wr(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const n=wr._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=wr._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.xs.x)return!1}else if(l=1/this.direction.x,c=(n.x-this.origin.x)*l,u=(s.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.ys.y)return!1}else if(l=1/this.direction.y,c=(n.y-this.origin.y)*l,u=(s.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.zs.z)return!1}else if(l=1/this.direction.z,c=(n.z-this.origin.z)*l,u=(s.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,n=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+n*n+s*s,o=e.radius+t,l=o*o;if(a<=l)return!0;const c=i*this.direction.x+n*this.direction.y+s*this.direction.z;return c<0?!1:a-c*c<=l}intersectsTriangle(e,t,i){const n=wr._TmpVector3[0],s=wr._TmpVector3[1],a=wr._TmpVector3[2],o=wr._TmpVector3[3],l=wr._TmpVector3[4];t.subtractToRef(e,n),i.subtractToRef(e,s),O.CrossToRef(this.direction,s,a);const c=O.Dot(n,a);if(c===0)return null;const u=1/c;this.origin.subtractToRef(e,o);const h=O.Dot(o,a)*u;if(h<-this.epsilon||h>1+this.epsilon)return null;O.CrossToRef(o,n,l);const d=O.Dot(this.direction,l)*u;if(d<-this.epsilon||h+d>1+this.epsilon)return null;const f=O.Dot(s,l)*u;return f>this.length?null:new mZ(1-h-d,h,f)}intersectsPlane(e){let t;const i=O.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const n=O.Dot(e.normal,this.origin);return t=(-e.d-n)/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 O(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 O(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 O(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,n=!1,s,a=!1){const o=oe.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?wr.TransformToRef(this,o,this._tmpRay):this._tmpRay=wr.Transform(this,o),e.intersects(this._tmpRay,t,i,n,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let n=0;nt.distance?1:0}intersectionSegment(e,t,i){const n=this.origin,s=oe.Vector3[0],a=oe.Vector3[1],o=oe.Vector3[2],l=oe.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(wr._Rayl,o),n.addToRef(o,a),e.subtractToRef(n,l);const c=O.Dot(s,s),u=O.Dot(s,o),h=O.Dot(o,o),d=O.Dot(s,l),f=O.Dot(o,l),p=c*h-u*u;let g,m=p,_,y=p;pm&&(g=m,_=f+u,y=h)),_<0?(_=0,-d<0?g=0:-d>c?g=m:(g=-d,m=c)):_>y&&(_=y,-d+u<0?g=0:-d+u>c?g=m:(g=-d+u,m=c));const v=Math.abs(g)0&&x<=this.length&&A.lengthSquared()=r.distance?null:c};Ut.prototype._internalPick=function(r,e,t,i,n){let s=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),s=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=wr.Zero()),this.createPickingRayToRef(r,e,a,this._tempPickingRay,n||null),this._tempPickingRay),t,i,!0);return s&&(s.ray=this.createPickingRay(r,e,pe.Identity(),n||null)),s};Object.defineProperty(Ut.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Ut.prototype.pick=function(r,e,t,i,n,s,a=!1){const o=this._internalPick((l,c)=>(this._tempPickingRay||(this._tempPickingRay=wr.Zero()),this.createPickingRayToRef(r,e,l,this._tempPickingRay,n||null,!1,c),this._tempPickingRay),t,i,!1,s);return o&&(o.ray=this.createPickingRay(r,e,pe.Identity(),n||null)),o};Ut.prototype.pickWithRay=function(r,e,t,i){const n=this._internalPick(s=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=pe.Identity()),s.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=wr.Zero()),wr.TransformToRef(r,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return n&&(n.ray=r),n};Ut.prototype.multiPick=function(r,e,t,i,n){return this._internalMultiPick(s=>this.createPickingRay(r,e,s,i||null),t,n)};Ut.prototype.multiPickWithRay=function(r,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=pe.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=wr.Zero()),wr.TransformToRef(r,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};di.prototype.getForwardRay=function(r=100,e,t){return this.getForwardRayToRef(new wr(O.Zero(),O.Zero(),r),r,e,t)};di.prototype.getForwardRayToRef=function(r,e=100,t,i){t||(t=this.getWorldMatrix()),r.length=e,i?r.origin.copyFrom(i):r.origin.copyFrom(this.position);const n=oe.Vector3[2];n.set(0,0,this._scene.useRightHandedSystem?-1:1);const s=oe.Vector3[3];return O.TransformNormalToRef(n,t,s),O.NormalizeToRef(s,r.direction),r};class Bn{static _RemoveAndStorePivotPoint(e){e&&Bn._PivotCached===0&&(e.getPivotPointToRef(Bn._OldPivotPoint),Bn._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Bn._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(pe.IdentityReadOnly),Bn._OldPivotPoint.subtractToRef(e.getPivotPoint(),Bn._PivotTranslation),Bn._PivotTmpVector.copyFromFloats(1,1,1),Bn._PivotTmpVector.subtractInPlace(e.scaling),Bn._PivotTmpVector.multiplyInPlace(Bn._PivotTranslation),e.position.addInPlace(Bn._PivotTmpVector))),Bn._PivotCached++}static _RestorePivotPoint(e){e&&!Bn._OldPivotPoint.equalsToFloats(0,0,0)&&Bn._PivotCached===1&&(e.setPivotPoint(Bn._OldPivotPoint),e._postMultiplyPivotMatrix=Bn._PivotPostMultiplyPivotMatrix,Bn._PivotTmpVector.copyFromFloats(1,1,1),Bn._PivotTmpVector.subtractInPlace(e.scaling),Bn._PivotTmpVector.multiplyInPlace(Bn._PivotTranslation),e.position.subtractInPlace(Bn._PivotTmpVector)),this._PivotCached--}}Bn._PivotCached=0;Bn._OldPivotPoint=new O;Bn._PivotTranslation=new O;Bn._PivotTmpVector=new O;Bn._PivotPostMultiplyPivotMatrix=!1;function Nz(r){const e=[],t=[],i=[],n=[],s=r.width||r.size||1,a=r.height||r.size||1,o=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,l=s/2,c=a/2;t.push(-l,-c,0),i.push(0,0,-1),n.push(0,bn?1:0),t.push(l,-c,0),i.push(0,0,-1),n.push(1,bn?1:0),t.push(l,c,0),i.push(0,0,-1),n.push(1,bn?0:1),t.push(-l,c,0),i.push(0,0,-1),n.push(0,bn?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),vt._ComputeSides(o,t,e,i,n,r.frontUVs,r.backUVs);const u=new vt;return u.indices=e,u.positions=t,u.normals=i,u.uvs=n,u}function U_(r,e={},t=null){const i=new Re(r,t);return e.sideOrientation=Re._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Nz(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}const Gvt={CreatePlane:U_};vt.CreatePlane=Nz;Re.CreatePlane=(r,e,t,i,n)=>U_(r,{size:e,width:e,height:e,sideOrientation:n,updatable:i},t);class Kl{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 Ce,this.onDragStartObservable=new Ce,this.onDragEndObservable=new Ce,this.onEnabledObservable=new Ce,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=i=>!0,this._tmpVector=new O(0,0,0),this._alternatePickedPoint=new O(0,0,0),this._worldDragAxis=new O(0,0,0),this._targetPosition=new O(0,0,0),this._attachedToElement=!1,this._startDragRay=new wr(new O,new O),this._lastPointerRay={},this._dragDelta=new O,this._pointA=new O(0,0,0),this._pointC=new O(0,0,0),this._localAxis=new O(0,0,0),this._lookAt=new O(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,Kl._PlaneScene||(this._debugMode?Kl._PlaneScene=this._scene:(Kl._PlaneScene=new Ut(this._scene.getEngine(),{virtual:!0}),Kl._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{Kl._PlaneScene.dispose(),Kl._PlaneScene=null}))),this._dragPlane=U_("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Re.DOUBLESIDE},Kl._PlaneScene),this.lastDragPosition=new O(0,0,0);const i=t||(n=>this.attachedNode==n||n.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(n=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(n.type==Wt.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&n.pickInfo&&n.pickInfo.hit&&n.pickInfo.pickedMesh&&n.pickInfo.pickedPoint&&n.pickInfo.ray&&i(n.pickInfo.pickedMesh)&&this._activeDragButton===-1&&this.dragButtons.indexOf(n.event.button)!==-1&&(this._activeDragButton=n.event.button,this._activePointerInfo=n,this._startDrag(n.event.pointerId,n.pickInfo.ray,n.pickInfo.pickedPoint));else if(n.type==Wt.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==n.event.pointerId&&(this._activeDragButton===n.event.button||this._activeDragButton===-1)&&this.releaseDrag();else if(n.type==Wt.POINTERMOVE){const s=n.event.pointerId;if(this.currentDraggingPointerId===Kl._AnyMouseId&&s!==Kl._AnyMouseId){const a=n.event;(a.pointerType==="mouse"||!this._scene.getEngine().hostInformation.isMobile&&a instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[s]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=s)}this._lastPointerRay[s]||(this._lastPointerRay[s]=new wr(new O,new O)),n.pickInfo&&n.pickInfo.ray&&(this._lastPointerRay[s].origin.copyFrom(n.pickInfo.ray.origin),this._lastPointerRay[s].direction.copyFrom(n.pickInfo.ray.direction),this.currentDraggingPointerId==s&&this.dragging&&this._moveDrag(n.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let n=!1;Bn._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),n=!0),Bn._RestorePivotPoint(this.attachedNode),n&&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=Kl._AnyMouseId,t,i){this._startDrag(e,t,i);let n=this._lastPointerRay[e];e===Kl._AnyMouseId&&(n=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),n&&this._moveDrag(n)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Bn._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 n=this._pickWithRayOnDragPlane(this._startDragRay);n?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,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(),Bn._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Bn._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?O.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=O.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),Bn._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(O.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*O.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const l=O.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,n=this._dragPlane.position,s=e.direction.dot(i);if(Math.abs(s).999?Math.abs(O.Dot(O.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(O.Right()):this._lookAt.copyFrom(O.UpReadOnly):(O.CrossToRef(this._localAxis,this._pointC,this._lookAt),O.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?O.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()}}Kl._AnyMouseId=-2;class Wvt{constructor(){this._startDistance=0,this._initialScale=new O(0,0,0),this._targetScale=new O(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Kl({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Kl({}),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 Z1{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new O,this._tmpQuaternion=new Oe,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 Ce,this.onDragObservable=new Ce,this.onDragEndObservable=new Ce,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 Yt("",Z1._virtualScene);e.rotationQuaternion=new Oe;const t=new Yt("",Z1._virtualScene);t.rotationQuaternion=new Oe;const i=new Yt("",Z1._virtualScene);return i.rotationQuaternion=new Oe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new O,startingPivotOrientation:new Oe,startingPosition:new O,startingOrientation:new Oe,lastOriginPosition:new O,lastDragPosition:new O}}_resetVirtualMeshesPosition(){for(let e=0;ef&&(f=Math.min(p-h,0)),u.scaleInPlace(f),u.addToRef(s.pivotMesh.absolutePosition,this._tmpVector),s.pivotMesh.setAbsolutePosition(this._tmpVector),u.addToRef(s.dragMesh.absolutePosition,this._tmpVector),s.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),Z1._virtualScene||(Z1._virtualScene=new Ut(this._scene.getEngine(),{virtual:!0}),Z1._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 n=i.event.pointerId;this._virtualMeshesInfo[n]||(this._virtualMeshesInfo[n]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[n],a=i.event.pointerType==="xr-near"||i.event.pointerType==="xr";if(i.type==Wt.POINTERDOWN){if(!s.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===di.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[n];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(n)===-1&&this.currentDraggingPointerIds.push(n),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,n),this.onDragStartObservable.notifyObservers({position:o.pivotMesh.position})}}else if(i.type==Wt.POINTERUP||i.type==Wt.POINTERDOUBLETAP){const o=this.currentDraggingPointerIds.indexOf(n);s.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)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(n),this.onDragEndObservable.notifyObservers({}))}else if(i.type==Wt.POINTERMOVE&&this.currentDraggingPointerIds.indexOf(n)!==-1&&s.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,n,l):this._pointerUpdate2D(i.pickInfo.ray,n,l),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:i.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,n),s.lastDragPosition.copyFrom(s.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 p9e extends Z1{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new O(0,0,0),this._targetOrientation=new Oe,this._targetScaling=new O(1,1,1),this._startingPosition=new O(0,0,0),this._startingOrientation=new Oe,this._startingScaling=new O(1,1,1),this.onPositionChangedObservable=new Ce,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 Yt("virtual_sixDof",Z1._virtualScene),this._virtualTransformNode.rotationQuaternion=Oe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(()=>{if(this.currentDraggingPointerIds.length===1&&this._moving&&!this.disableMovement){const t=oe.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=oe.Vector3[1];if(i.copyFrom(t),e.parent){const n=oe.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(n),n.invert(),O.TransformNormalToRef(t,n,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const n=oe.Quaternion[0];if(n.copyFrom(this._targetOrientation),e.parent){const s=oe.Quaternion[0];s.copyFrom(e.parent.absoluteRotationQuaternion),s.invertInPlace(),s.multiplyToRef(this._targetOrientation,n)}Oe.SlerpToRef(e.rotationQuaternion,n,this.dragDeltaRatio,e.rotationQuaternion)}}})}_getPositionOffsetAround(e,t,i){const n=oe.Matrix[0],s=oe.Matrix[1],a=oe.Matrix[2],o=oe.Matrix[3],l=oe.Matrix[4];return pe.TranslationToRef(e.x,e.y,e.z,n),pe.TranslationToRef(-e.x,-e.y,-e.z,s),pe.FromQuaternionToRef(i,a),pe.ScalingToRef(t,t,t,o),s.multiplyToRef(a,l),l.multiplyToRef(o,l),l.multiplyToRef(n,l),l.getTranslation()}_onePointerPositionUpdated(e,t){oe.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?Oe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,oe.Quaternion[0]):oe.Quaternion[0].copyFrom(t),oe.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=oe.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const n=oe.Vector3[1];t.subtractToRef(e,n);const s=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,a=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=oe.Vector3[2];s.addToRef(a,o),o.scaleInPlace(.5);const l=oe.Vector3[3];a.subtractToRef(s,l);const c=l.length()/n.length(),u=o.subtract(i),h=Oe.FromEulerAngles(0,O.GetAngleBetweenVectorsOnPlane(n.normalize(),l.normalize(),O.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=Oe.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=oe.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,i),i.normalize();const n=oe.Quaternion[0];this._scene.useRightHandedSystem?Oe.FromLookDirectionRHToRef(i,new O(0,1,0),n):Oe.FromLookDirectionLHToRef(i,new O(0,1,0),n),n.normalize(),Oe.RotationYawPitchRollToRef(n.toEulerAngles().y,0,0,oe.Quaternion[0]),this._targetOrientation.copyFrom(oe.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else e===2&&(this._virtualTransformNode.setPivotPoint(new O(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 Kvt{constructor(){this._attachPointLocalOffset=new O,this._workingPosition=new O,this._workingQuaternion=new Oe,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=Oe.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 n=oe.Vector3[0];return n.copyFrom(t),n.scaleInPlace(this.hitNormalOffset),n.addInPlace(i),this._attachedMesh.parent&&(oe.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),O.TransformNormalToRef(n,oe.Matrix[0],n)),{position:n,quaternion:Oe.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&&O.Distance(this._attachedMesh.position,i.position){this.enabled&&e.type==Wt.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 Hvt{constructor(){this._tmpQuaternion=new Oe,this._tmpVectors=[new O,new O,new O,new O,new O,new O,new O],this._tmpMatrix=new pe,this._tmpInvertView=new pe,this._tmpForward=new O,this._tmpNodeForward=new O,this._tmpPosition=new O,this._workingPosition=new O,this._workingQuaternion=new Oe,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(O.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,n=this.maximumDistance;const s=this.defaultDistance,a=this._tmpVectors[0];a.copyFrom(e);let o=a.length();if(a.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(a)*i,n=this._length2D(a)*n;const c=this._length2D(e);a.scaleInPlace(o/c),o=c}let l=o;return t?l=s:l=Xt.Clamp(o,i,n),e.copyFrom(a).scaleInPlace(l),o!==l}_applyVerticalClamp(e){this.verticalMaxDistance!==0&&(e.y=Xt.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){Oe.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),O.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),O.TransformNormalToRef(i,e,i),Oe.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 n=this._tmpVectors[6];n.copyFromFloats(1,0,0),O.TransformNormalToRef(i,e,i),O.TransformNormalToRef(n,e,n);const s=O.UpReadOnly;if(t.length()d&&(Oe.RotationAxisToRef(n,-h+d,l),t.rotateByQuaternionToRef(l,t),o=!0)}const c=this._angleBetweenVectorAndPlane(t,n)*(this._scene.useRightHandedSystem?-1:1),u=this.maxViewHorizontalDegrees*Math.PI/180*.5;return c<-u?(Oe.RotationAxisToRef(s,-c-u,l),t.rotateByQuaternionToRef(l,t),o=!0):c>u&&(Oe.RotationAxisToRef(s,-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 n=this._tmpVectors[1],s=this._tmpVectors[2];n.copyFromFloats(0,1,0),O.CrossToRef(i,n,s);const a=s.length();athis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),n=this._workingPosition,s=this._workingQuaternion,a=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),O.TransformCoordinatesToRef(a,i,n);const l=this._tmpPosition;l.copyFromFloats(0,0,0),O.TransformCoordinatesToRef(l,i,l),l.scaleInPlace(-1).subtractInPlace(a),n.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let c=!1;const u=this._tmpForward;u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),O.TransformNormalToRef(u,o,u);const h=this._tmpNodeForward;if(h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),O.TransformNormalToRef(h,i,h),this._recenterNextUpdate)n.copyFrom(u).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const f=n.length();n.copyFrom(u).scaleInPlace(f)}else c=this._angularClamp(o,n);let d=!1;this.ignoreDistanceClamp||(d=this._distanceClamp(n,c),this._applyVerticalClamp(n)),this.useFixedVerticalOffset&&(n.y=l.y-e.globalPosition.y+this.fixedVerticalOffset),(c||d||this._passedOrientationDeadzone(n,h)||this._recenterNextUpdate)&&this._orientationClamp(n,s),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=Oe.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 O;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),O.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const n=new Oe;n.copyFrom(this.attachedNode.rotationQuaternion),Oe.SmoothToRef(n,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 ln{}ln.ANCHOR_SYSTEM="xr-anchor-system";ln.BACKGROUND_REMOVER="xr-background-remover";ln.HIT_TEST="xr-hit-test";ln.MESH_DETECTION="xr-mesh-detection";ln.PHYSICS_CONTROLLERS="xr-physics-controller";ln.PLANE_DETECTION="xr-plane-detection";ln.POINTER_SELECTION="xr-controller-pointer-selection";ln.TELEPORTATION="xr-controller-teleportation";ln.FEATURE_POINTS="xr-feature-points";ln.HAND_TRACKING="xr-hand-tracking";ln.IMAGE_TRACKING="xr-image-tracking";ln.NEAR_INTERACTION="xr-near-interaction";ln.DOM_OVERLAY="xr-dom-overlay";ln.MOVEMENT="xr-controller-movement";ln.LIGHT_ESTIMATION="xr-light-estimation";ln.EYE_TRACKING="xr-eye-tracking";ln.WALKING_LOCOMOTION="xr-walking-locomotion";ln.LAYERS="xr-layers";ln.DEPTH_SENSING="xr-depth-sensing";ln.SPACE_WARP="xr-space-warp";ln.RAW_CAMERA_ACCESS="xr-raw-camera-access";class Ea{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,n=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,n){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,n)}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()||Ie.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ie.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={},n=!0,s=!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=Ea.GetStableVersionOfFeature(a):t==="latest"?o=Ea.GetLatestVersionOfFeature(a):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${a} (${t})`)}else o=t;const l=Ea._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=Ea.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:s},n?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(s)throw new Error("required feature not compatible");return Ie.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 n=this._features[i],s=n.featureImplementation.xrNativeFeatureName;if(s&&(n.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(s)===-1&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(s)===-1&&e.optionalFeatures.push(s))),n.featureImplementation.getXRSessionInitExtension){const a=await n.featureImplementation.getXRSessionInitExtension();e={...e,...a}}}return e}}Ea._AvailableFeatures={};Ea._ConflictingFeatures={[ln.TELEPORTATION]:ln.MOVEMENT,[ln.MOVEMENT]:ln.TELEPORTATION};var que;(function(r){r[r.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",r[r.RADIAL_SIDE=1]="RADIAL_SIDE",r[r.ULNAR_SIDE=2]="ULNAR_SIDE",r[r.BELOW_WRIST=3]="BELOW_WRIST"})(que||(que={}));var Jue;(function(r){r[r.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",r[r.HAND_ROTATION=1]="HAND_ROTATION"})(Jue||(Jue={}));var ehe;(function(r){r[r.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",r[r.PALM_UP=1]="PALM_UP",r[r.GAZE_FOCUS=2]="GAZE_FOCUS",r[r.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(ehe||(ehe={}));class jvt{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 O(0,1,0),this._zoneAxis[1]=new O(-1,0,0),this._zoneAxis[2]=new O(1,0,0),this._zoneAxis[3]=new O(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"),n=e.getJointMesh("wrist");if(n&&i&&t){const s={position:i.absolutePosition,quaternion:new Oe,id:e.xrController.uniqueId},a=oe.Vector3[0],o=oe.Vector3[1],l=oe.Vector3[2];return a.copyFrom(i.absolutePosition).subtractInPlace(n.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),O.CrossToRef(a,o,o),O.CrossToRef(o,a,l),Oe.FromLookDirectionLHToRef(o,a,s.quaternion),s}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=Oe.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 n=oe.Vector3[0],s=this._scene.activeCamera;n.copyFrom(this._zoneAxis[this.targetZone]);const a=oe.Quaternion[0];if(s&&(this.zoneOrientationMode===0||this.nodeOrientationMode===0)){const u=oe.Vector3[1];u.copyFrom(s.position).subtractInPlace(i.position).normalize(),this._scene.useRightHandedSystem?Oe.FromLookDirectionRHToRef(u,O.UpReadOnly,a):Oe.FromLookDirectionLHToRef(u,O.UpReadOnly,a)}this.zoneOrientationMode===1?i.quaternion.toRotationMatrix(oe.Matrix[0]):a.toRotationMatrix(oe.Matrix[0]),O.TransformNormalToRef(n,oe.Matrix[0],n),n.scaleInPlace(this.targetOffset);const o=oe.Vector3[2],l=oe.Quaternion[1];o.copyFrom(i.position).addInPlace(n),this.nodeOrientationMode===1?l.copyFrom(i.quaternion):l.copyFrom(a);const c=Date.now()-t;O.SmoothToRef(this._node.position,o,c,this.lerpTime,this._node.position),Oe.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 n=this._scene.activeCamera;if(n){const s=n.getForwardRay();if(this.handConstraintVisibility===2||this.handConstraintVisibility===3){i=!1;let a;this._eyeTracking&&(a=this._eyeTracking.getEyeGaze()),a=a||s;const o=oe.Vector3[0];e?e.position.subtractToRef(a.origin,o):this._node.getAbsolutePosition().subtractToRef(a.origin,o);const l=O.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)Ie.Error("XR features manager must be available or provided directly for the Hand Menu to work");else{try{this._eyeTracking=t.getEnabledFeature(ln.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(ln.HAND_TRACKING)}catch{Ie.Error("Hand tracking must be enabled for the Hand Menu to work")}}}}class af{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=O.Zero(),this.poleTargetPosition=O.Zero(),this.poleTargetLocalOffset=O.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=Oe.Identity(),this._bone1Mat=pe.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=O.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const n=t.getParent();if(!n){this._notEnoughInformation=!0,ge.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=n,this._bone2.children.length===0&&!this._bone2.length){this._notEnoughInformation=!0,ge.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 s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.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=O.Distance(a,o),this._bone1Length=O.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=O.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=af._TmpMats[0],n=af._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&O.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=af._TmpVecs[0],a=af._TmpVecs[1],o=af._TmpVecs[2],l=af._TmpVecs[3],c=af._TmpVecs[4],u=af._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,c),c.x==0&&c.y==0&&c.z==0?c.y=1:c.normalize(),e.subtractToRef(s,l),l.normalize(),O.CrossToRef(l,c,a),a.normalize(),O.CrossToRef(l,a,o),o.normalize(),pe.FromXYZAxesToRef(o,l,a,i);const h=this._bone1Length,d=this._bone2Length;let f=O.Distance(s,e);this._maxReach>0&&(f=Math.min(this._maxReach,f));let p=(d*d+f*f-h*h)/(2*d*f),g=(f*f+h*h-d*d)/(2*f*h);p>1&&(p=1),g>1&&(g=1),p<-1&&(p=-1),g<-1&&(g=-1);const m=Math.acos(p),_=Math.acos(g);let y=-m-_;if(this._rightHandedSystem)pe.RotationYawPitchRollToRef(0,0,this._adjustRoll,n),n.multiplyToRef(i,i),pe.RotationAxisToRef(this._bendAxis,_,n),n.multiplyToRef(i,i);else{const v=af._TmpVecs[5];v.copyFrom(this._bendAxis),v.x*=-1,pe.RotationAxisToRef(v,-_,n),n.multiplyToRef(i,i)}this.poleAngle&&(pe.RotationAxisToRef(l,this.poleAngle,n),i.multiplyToRef(n,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||Oe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),Oe.FromRotationMatrixToRef(i,u),Oe.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 Oe),e.getRotationQuaternionToRef(0,null,e._linkedTransformNode.rotationQuaternion))}}af._TmpVecs=[O.Zero(),O.Zero(),O.Zero(),O.Zero(),O.Zero(),O.Zero()];af._TmpQuat=Oe.Identity();af._TmpMats=[pe.Identity(),pe.Identity()];class Tc{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,n){if(this.upAxis=O.Up(),this.upAxisSpace=0,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=Oe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=O.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,n){if(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),n.maxYaw!=null?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,n.minYaw!=null?this.minYaw=n.minYaw:this.minYaw=-Math.PI,n.maxPitch!=null?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,n.minPitch!=null?this.minPitch=n.minPitch:this.minPitch=-Math.PI,n.slerpAmount!=null&&(this.slerpAmount=n.slerpAmount),n.upAxis!=null&&(this.upAxis=n.upAxis),n.upAxisSpace!=null&&(this.upAxisSpace=n.upAxisSpace),n.yawAxis!=null||n.pitchAxis!=null){let s=go.Y,a=go.X;n.yawAxis!=null&&(s=n.yawAxis.clone(),s.normalize()),n.pitchAxis!=null&&(a=n.pitchAxis.clone(),a.normalize());const o=O.Cross(a,s);this._transformYawPitch=pe.Identity(),pe.FromXYZAxesToRef(a,s,o,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}n.useAbsoluteValueForYaw!==void 0&&(this.useAbsoluteValueForYaw=n.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=Tc._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const n=Tc._TmpMats[0],s=Tc._TmpMats[1],a=this.mesh,o=e.getParent(),l=Tc._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==2&&o?(this._transformYawPitch&&O.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 m=Tc._TmpMats[2],_=Tc._TmpMats[3];if(this.upAxisSpace==2&&l.y==1&&o)o.getRotationMatrixToRef(1,this.mesh,m);else if(this.upAxisSpace==0&&l.y==1&&!o)m.copyFrom(a.getWorldMatrix());else{let v=Tc._TmpVecs[2];v.copyFrom(this._fowardAxis),this._transformYawPitch&&O.TransformCoordinatesToRef(v,this._transformYawPitchInv,v),o?o.getDirectionToRef(v,this.mesh,v):a.getDirectionToRef(v,v);const x=O.Cross(l,v);x.normalize(),v=O.Cross(x,l),pe.FromXYZAxesToRef(x,l,v,m)}m.invertToRef(_);let y=null;if(u){const v=Tc._TmpVecs[3];i.subtractToRef(t,v),O.TransformCoordinatesToRef(v,_,v),y=Math.sqrt(v.x*v.x+v.z*v.z);const x=Math.atan2(v.y,y);let b=x;x>this._maxPitch?(v.y=this._maxPitchTan*y,b=this._maxPitch):xthis._maxYaw||bMath.PI?this._isAngleBetween(x,this._maxYaw,this._midYawConstraint)?(v.z=this._maxYawCos*y,v.x=this._maxYawSin*y,C=this._maxYaw):this._isAngleBetween(x,this._midYawConstraint,this._minYaw)&&(v.z=this._minYawCos*y,v.x=this._minYawSin*y,C=this._minYaw):b>this._maxYaw?(v.z=this._maxYawCos*y,v.x=this._maxYawSin*y,x<0&&this.useAbsoluteValueForYaw&&(v.x*=-1),C=this._maxYaw):bMath.PI){const A=Tc._TmpVecs[8];A.copyFrom(go.Z),this._transformYawPitch&&O.TransformCoordinatesToRef(A,this._transformYawPitchInv,A);const E=Tc._TmpMats[4];this._boneQuat.toRotationMatrix(E),this.mesh.getWorldMatrix().multiplyToRef(E,E),O.TransformCoordinatesToRef(A,E,A),O.TransformCoordinatesToRef(A,_,A);const P=Math.atan2(A.x,A.z),w=this._getAngleBetween(P,x),M=this._getAngleBetween(P,this._midYawConstraint);if(w>M){y==null&&(y=Math.sqrt(v.x*v.x+v.z*v.z));const R=this._getAngleBetween(P,this._maxYaw);this._getAngleBetween(P,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 r=new Uint8Array(4),e=new Uint32Array(r.buffer);return!!((e[0]=1)&r[0])})();Object.defineProperty(ee.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(ee.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(ee.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});ee.prototype._rebuild=function(){var r,e;(r=this._buffer)==null||r._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};ee.prototype.dispose=function(){var r;this._ownsBuffer&&this._buffer.dispose(),(r=this._alignedBuffer)==null||r.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};ee.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};ee.prototype._alignBuffer=function(){var h;const r=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!r)return;const e=ee.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,n=this._maxVerticesCount,a=n*t/e;let o;if(Array.isArray(r)){const d=new Float32Array(r);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else r instanceof ArrayBuffer?o=new DataView(r,0,r.byteLength):o=new DataView(r.buffer,r.byteOffset,r.byteLength);let l;this.type===ee.BYTE?l=new Int8Array(a):this.type===ee.UNSIGNED_BYTE?l=new Uint8Array(a):this.type===ee.SHORT?l=new Int16Array(a):this.type===ee.UNSIGNED_SHORT?l=new Uint16Array(a):this.type===ee.INT?l=new Int32Array(a):this.type===ee.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!==Wt.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===rT.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*n*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*n*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*n*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Wt.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"}}V([Q()],Fz.prototype,"wheelPrecisionX",void 0);V([Q()],Fz.prototype,"wheelPrecisionY",void 0);V([Q()],Fz.prototype,"wheelPrecisionZ",void 0);class YJ{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ie.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,s=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!==Wt.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!==Wt.POINTERDOWN&&o.type!==Wt.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===Wt.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===Wt.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===Wt.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,(n!==0||s)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,s,null),n=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===Wt.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,g=this._pointA.y-this._pointB.y,m=p*p+g*g,_={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,n,m,s,_),s=_,n=m}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Wt.POINTERDOWN|Wt.POINTERUP|Wt.POINTERMOVE|Wt.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,s=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const a=this.camera.getScene().getEngine().getHostWindow();a&&Ie.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ie.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,n,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}V([Q()],YJ.prototype,"buttons",void 0);var eu={};class Bz{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){ge.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=di.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 n=this.attached[i],s=ot.Serialize(n);t[n.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const n=eu[i];if(n){const s=t[i],a=ot.Parse(()=>new n,s,null);this.add(a)}}}else for(const i in this.attached){const n=eu[this.attached[i].getClassName()];if(n){const s=ot.Parse(()=>new n,e,null);this.remove(this.attached[i]),this.add(s)}}}}class $vt{constructor(e,t){this.x=e,this.y=t}}class Zl{get isConnected(){return this._isConnected}constructor(e,t,i,n=0,s=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=Zl.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=s,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(){}}Zl.GAMEPAD=0;Zl.GENERIC=1;Zl.XBOX=2;Zl.POSE_ENABLED=3;Zl.DUALSHOCK=4;class m9e extends Zl{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new Ce,this.onButtonUpObservable=new Ce,this.type=Zl.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!==Zl.POSE_ENABLED&&(!this.gamepad||t.type===Zl.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Zl.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 n=t.x/this.gamepadRotationSensibility;n!=0&&Math.abs(n)>.005&&(e.inertialAlphaOffset+=n)}if(t.y!=0){const n=t.y/this.gamepadRotationSensibility*this._yAxisScale;n!=0&&Math.abs(n)>.005&&(e.inertialBetaOffset+=n)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const n=i.y/this.gamepadMoveSensibility;n!=0&&Math.abs(n)>.005&&(this.camera.inertialRadiusOffset-=n)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}V([Q()],kz.prototype,"gamepadRotationSensibility",void 0);V([Q()],kz.prototype,"gamepadMoveSensibility",void 0);eu.ArcRotateCameraGamepadInput=kz;class Z0{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=Ie.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===Rg.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 n=this._keys.indexOf(i.keyCode);n>=0&&this._keys.splice(n,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=n/(1+this.wheelDeltaPercentage):i=n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ie.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Wt.POINTERWHEEL)return;const i=t.event;let n=0;const s=i.deltaMode===rT.DOM_DELTA_LINE?Xvt:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),n>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+n;for(let c=0;c<20&&Math.abs(l)>.001;c++)o-=l,l*=this.camera.inertia;o=Xt.Clamp(o,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else n=a/(this.wheelPrecision*40);n&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(n)):this.camera.inertialRadiusOffset+=n),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Wt.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=Dc.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,pe.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=O.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let n=0;return this._hitPlane&&(n=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(n))}_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 s=e/i/t.radius,a=this._getPosition(),o=oe.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(s),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,n))}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}}nd.MinimumRadiusForPinch=.001;V([Q()],nd.prototype,"buttons",void 0);V([Q()],nd.prototype,"angularSensibilityX",void 0);V([Q()],nd.prototype,"angularSensibilityY",void 0);V([Q()],nd.prototype,"pinchPrecision",void 0);V([Q()],nd.prototype,"pinchDeltaPercentage",void 0);V([Q()],nd.prototype,"useNaturalPinchZoom",void 0);V([Q()],nd.prototype,"pinchZoom",void 0);V([Q()],nd.prototype,"panningSensibility",void 0);V([Q()],nd.prototype,"multiTouchPanning",void 0);V([Q()],nd.prototype,"multiTouchPanAndZoom",void 0);eu.ArcRotateCameraPointersInput=nd;class QJ extends Bz{constructor(e){super(e)}addMouseWheel(){return this.add(new nD),this}addPointers(){return this.add(new nd),this}addKeyboard(){return this.add(new Z0),this}}QJ.prototype.addVRDeviceOrientation=function(){return this.add(new A1e),this};class A1e{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=Ie.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):Ie.Warn("Permission not granted.")}).catch(i=>{Ie.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"}}eu.ArcRotateCameraVRDeviceOrientationInput=A1e;class b3{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=Ie.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===Rg.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 n=this._keys.indexOf(i.keyCode);n>=0&&this._keys.splice(n,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)},Wt.POINTERDOWN|Wt.POINTERUP|Wt.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,n=this.camera.getEngine();if(!this.touchEnabled&&t.pointerType==="touch"||e.type!==Wt.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const s=t.target;if(e.type===Wt.POINTERDOWN){try{s==null||s.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||t.preventDefault(),n.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Wt.POINTERUP){try{s==null||s.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Wt.POINTERMOVE){if(!this._previousPosition){n.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 n=e.movementX,s=e.movementY;this._rotateCamera(n,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,n=i._calculateHandednessMultiplier();e*=n;const s=e/this.angularSensibility,a=t/this.angularSensibility,o=Oe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(c=>c===this.activeButton)&&(l=Oe.RotationAxis(go.X,a),o.multiplyInPlace(l)),this.buttonsYaw.some(c=>c===this.activeButton)){l=Oe.RotationAxis(go.Y,s),o.multiplyInPlace(l);const c=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-cc===this.activeButton)&&(l=Oe.RotationAxis(go.Z,-s),i._trackRoll-=s,o.multiplyInPlace(l)),o.toEulerAnglesToRef(i.rotation)}}V([Q()],Uz.prototype,"buttons",void 0);V([Q()],Uz.prototype,"angularSensibility",void 0);eu.FlyCameraMouseInput=Uz;class kc{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=Ie.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===Rg.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 n=this._keys.indexOf(i.keyCode);n>=0&&this._keys.splice(n,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}}V([Q()],kc.prototype,"keysHeightOffsetIncr",void 0);V([Q()],kc.prototype,"keysHeightOffsetDecr",void 0);V([Q()],kc.prototype,"keysHeightOffsetModifierAlt",void 0);V([Q()],kc.prototype,"keysHeightOffsetModifierCtrl",void 0);V([Q()],kc.prototype,"keysHeightOffsetModifierShift",void 0);V([Q()],kc.prototype,"keysRotationOffsetIncr",void 0);V([Q()],kc.prototype,"keysRotationOffsetDecr",void 0);V([Q()],kc.prototype,"keysRotationOffsetModifierAlt",void 0);V([Q()],kc.prototype,"keysRotationOffsetModifierCtrl",void 0);V([Q()],kc.prototype,"keysRotationOffsetModifierShift",void 0);V([Q()],kc.prototype,"keysRadiusIncr",void 0);V([Q()],kc.prototype,"keysRadiusDecr",void 0);V([Q()],kc.prototype,"keysRadiusModifierAlt",void 0);V([Q()],kc.prototype,"keysRadiusModifierCtrl",void 0);V([Q()],kc.prototype,"keysRadiusModifierShift",void 0);V([Q()],kc.prototype,"heightSensibility",void 0);V([Q()],kc.prototype,"rotationSensibility",void 0);V([Q()],kc.prototype,"radiusSensibility",void 0);eu.FollowCameraKeyboardMoveInput=kc;class ib{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ie.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Wt.POINTERWHEEL)return;const i=t.event;let n=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&ge.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?n=s*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?n=s*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(n=s*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):n=s*this.wheelPrecision,n&&(this.axisControlRadius?this.camera.radius+=n:this.axisControlHeight?this.camera.heightOffset-=n:this.axisControlRotation&&(this.camera.rotationOffset-=n)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Wt.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}V([Q()],ib.prototype,"axisControlRadius",void 0);V([Q()],ib.prototype,"axisControlHeight",void 0);V([Q()],ib.prototype,"axisControlRotation",void 0);V([Q()],ib.prototype,"wheelPrecision",void 0);V([Q()],ib.prototype,"wheelDeltaPercentage",void 0);eu.FollowCameraMouseWheelInput=ib;class sd extends YJ{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,n,s,a){if(i===0&&s===null||n===0&&a===null)return;let o=(n-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&&ge.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&ge.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&ge.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}V([Q()],sd.prototype,"angularSensibilityX",void 0);V([Q()],sd.prototype,"angularSensibilityY",void 0);V([Q()],sd.prototype,"pinchPrecision",void 0);V([Q()],sd.prototype,"pinchDeltaPercentage",void 0);V([Q()],sd.prototype,"axisXControlRadius",void 0);V([Q()],sd.prototype,"axisXControlHeight",void 0);V([Q()],sd.prototype,"axisXControlRotation",void 0);V([Q()],sd.prototype,"axisYControlRadius",void 0);V([Q()],sd.prototype,"axisYControlHeight",void 0);V([Q()],sd.prototype,"axisYControlRotation",void 0);V([Q()],sd.prototype,"axisPinchControlRadius",void 0);V([Q()],sd.prototype,"axisPinchControlHeight",void 0);V([Q()],sd.prototype,"axisPinchControlRotation",void 0);eu.FollowCameraPointersInput=sd;class Pf{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=Ie.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===Rg.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 n=this._keys.indexOf(i.keyCode);n>=0&&this._keys.splice(n,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 s=n.event,a=s.pointerType==="touch";if(!this.touchEnabled&&a||n.type!==Wt.POINTERMOVE&&this.buttons.indexOf(s.button)===-1)return;const o=s.target;if(n.type===Wt.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=s.pointerId;try{o==null||o.setPointerCapture(s.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===Wt.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{o==null||o.releasePointerCapture(s.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(n.type===Wt.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){const l=this.camera._calculateHandednessMultiplier(),c=(s.clientX-this._previousPosition.x)*l,u=s.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:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=n=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),a=n.movementX*s;this.camera.cameraRotation.y+=a/this.angularSensibility;const o=n.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||n.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Wt.POINTERDOWN|Wt.POINTERUP|Wt.POINTERMOVE),i&&(this._contextMenuBind=n=>this.onContextMenu(n),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"}}V([Q()],zz.prototype,"buttons",void 0);V([Q()],zz.prototype,"angularSensibility",void 0);eu.FreeCameraMouseInput=zz;var Hs;(function(r){r[r.MoveRelative=0]="MoveRelative",r[r.RotateRelative=1]="RotateRelative",r[r.MoveScene=2]="MoveScene"})(Hs||(Hs={}));class q0 extends Fz{constructor(){super(...arguments),this._moveRelative=O.Zero(),this._rotateRelative=O.Zero(),this._moveScene=O.Zero(),this._wheelXAction=Hs.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Hs.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Hs.MoveRelative||(this._wheelXAction=Hs.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Hs.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Hs.MoveRelative||(this._wheelYAction=Hs.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Hs.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Hs.MoveRelative||(this._wheelZAction=Hs.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Hs.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Hs.RotateRelative||(this._wheelXAction=Hs.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Hs.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Hs.RotateRelative||(this._wheelYAction=Hs.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Hs.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Hs.RotateRelative||(this._wheelZAction=Hs.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Hs.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Hs.MoveScene||(this._wheelXAction=Hs.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Hs.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Hs.MoveScene||(this._wheelYAction=Hs.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Hs.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Hs.MoveScene||(this._wheelZAction=Hs.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Hs.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=pe.Zero();this.camera.getViewMatrix().invertToRef(e);const t=O.Zero();O.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 n=null;switch(t){case Hs.MoveRelative:n=this._moveRelative;break;case Hs.RotateRelative:n=this._rotateRelative;break;case Hs.MoveScene:n=this._moveScene;break}switch(i){case 0:n.set(e,0,0);break;case 1:n.set(0,e,0);break;case 2:n.set(0,0,e);break}}}V([Q()],q0.prototype,"wheelXMoveRelative",null);V([Q()],q0.prototype,"wheelYMoveRelative",null);V([Q()],q0.prototype,"wheelZMoveRelative",null);V([Q()],q0.prototype,"wheelXRotateRelative",null);V([Q()],q0.prototype,"wheelYRotateRelative",null);V([Q()],q0.prototype,"wheelZRotateRelative",null);V([Q()],q0.prototype,"wheelXMoveScene",null);V([Q()],q0.prototype,"wheelYMoveScene",null);V([Q()],q0.prototype,"wheelZMoveScene",null);eu.FreeCameraMouseWheelInput=q0;class Vz{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=Ie.IsSafari()}attachControl(e){e=Ie.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const n=i.event,s=n.pointerType==="mouse"||this._isSafari&&typeof n.pointerType>"u";if(!(!this.allowMouse&&s)){if(i.type===Wt.POINTERDOWN){if(e||n.preventDefault(),this._pointerPressed.push(n.pointerId),this._pointerPressed.length!==1)return;t={x:n.clientX,y:n.clientY}}else if(i.type===Wt.POINTERUP){e||n.preventDefault();const a=this._pointerPressed.indexOf(n.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Wt.POINTERMOVE){if(e||n.preventDefault(),!t||this._pointerPressed.indexOf(n.pointerId)!=0)return;this._offsetX=n.clientX-t.x,this._offsetY=-(n.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Wt.POINTERDOWN|Wt.POINTERUP|Wt.POINTERMOVE),this._onLostFocus){const n=this.camera.getEngine().getInputElement();n&&n.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 n=e._computeLocalCameraSpeed(),s=new O(0,0,this.touchMoveSensibility!==0?n*this._offsetY/this.touchMoveSensibility:0);pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(O.TransformCoordinates(s,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}V([Q()],Vz.prototype,"touchAngularSensibility",void 0);V([Q()],Vz.prototype,"touchMoveSensibility",void 0);eu.FreeCameraTouchInput=Vz;class Gz extends Bz{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Pf),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new zz(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new q0,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Vz),this}clear(){super.clear(),this._mouseInput=null}}Gz.prototype.addDeviceOrientation=function(r){return this._deviceOrientationInput||(this._deviceOrientationInput=new S1e,r&&(this._deviceOrientationInput.smoothFactor=r),this.add(this._deviceOrientationInput)),this};class S1e{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let n=!1;const s=()=>{window.removeEventListener("deviceorientation",s),n=!0,t()};e&&setTimeout(()=>{n||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(a=>{a=="granted"?window.addEventListener("deviceorientation",s):Ie.Warn("Permission not granted.")}).catch(a=>{Ie.Error(a)}):window.addEventListener("deviceorientation",s)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new Oe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new Ce,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ie.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?Ie.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?Ie.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?Ie.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 Oe(-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 Oe),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():Ie.Warn("Permission not granted.")}).catch(i=>{Ie.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(Oe.RotationYawPitchRollToRef(Ie.ToRadians(this._alpha),Ie.ToRadians(this._beta),-Ie.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"}}eu.FreeCameraDeviceOrientationInput=S1e;class Wz{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=pe.Identity(),this._deltaTransform=O.Zero(),this._vector3=O.Zero(),this._vector2=Ne.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!==Zl.POSE_ENABLED&&(!this.gamepad||t.type===Zl.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Zl.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):pe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const n=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*n,0,-t.y*n),O.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"}}V([Q()],Wz.prototype,"gamepadAngularSensibility",void 0);V([Q()],Wz.prototype,"gamepadMoveSensibility",void 0);eu.FreeCameraGamepadInput=Wz;var the;(function(r){r[r.X=0]="X",r[r.Y=1]="Y",r[r.Z=2]="Z"})(the||(the={}));class Ui{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={...Ui._GetDefaultOptions(),...t};if(e?this._leftJoystick=!0:this._leftJoystick=!1,Ui._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=0,this._axisTargetedByUpAndDown=1,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new fZ,this.deltaPosition=O.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Ui._VJCanvasWidth=window.innerWidth,Ui._VJCanvasHeight=window.innerHeight,Ui.Canvas&&(Ui.Canvas.width=Ui._VJCanvasWidth,Ui.Canvas.height=Ui._VJCanvasHeight),Ui._HalfWidth=Ui._VJCanvasWidth/2},!Ui.Canvas){window.addEventListener("resize",this._onResize,!1),Ui.Canvas=document.createElement("canvas"),Ui._VJCanvasWidth=window.innerWidth,Ui._VJCanvasHeight=window.innerHeight,Ui.Canvas.width=window.innerWidth,Ui.Canvas.height=window.innerHeight,Ui.Canvas.style.width="100%",Ui.Canvas.style.height="100%",Ui.Canvas.style.position="absolute",Ui.Canvas.style.backgroundColor="transparent",Ui.Canvas.style.top="0px",Ui.Canvas.style.left="0px",Ui.Canvas.style.zIndex="5",Ui.Canvas.style.touchAction="none",Ui.Canvas.setAttribute("touch-action","none");const n=Ui.Canvas.getContext("2d");if(!n)throw new Error("Unable to create canvas for virtual joystick");Ui._VJCanvasContext=n,Ui._VJCanvasContext.strokeStyle="#ffffff",Ui._VJCanvasContext.lineWidth=2,document.body.appendChild(Ui.Canvas)}Ui._HalfWidth=Ui.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&&Ui._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new Ne(0,0),this._joystickPreviousPointerPos=new Ne(0,0),this._joystickPointerStartPos=new Ne(0,0),this._deltaJoystickVector=new Ne(0,0),this._onPointerDownHandlerRef=n=>{this._onPointerDown(n)},this._onPointerMoveHandlerRef=n=>{this._onPointerMove(n)},this._onPointerUpHandlerRef=n=>{this._onPointerUp(n)},Ui.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Ui.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Ui.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Ui.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Ui.Canvas.addEventListener("contextmenu",n=>{n.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.clientXUi._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)):Ui._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 Ne(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?Ui._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(Ui._VJCanvasContext.beginPath(),Ui._VJCanvasContext.strokeStyle=this._joystickColor,Ui._VJCanvasContext.lineWidth=2,Ui._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),Ui._VJCanvasContext.stroke(),Ui._VJCanvasContext.closePath(),Ui._VJCanvasContext.beginPath(),Ui._VJCanvasContext.lineWidth=6,Ui._VJCanvasContext.strokeStyle=this._joystickColor,Ui._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),Ui._VJCanvasContext.stroke(),Ui._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Ui._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(Ui._VJCanvasContext.beginPath(),Ui._VJCanvasContext.strokeStyle=this._joystickColor,Ui._VJCanvasContext.lineWidth=2,Ui._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),Ui._VJCanvasContext.stroke(),Ui._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()):(Ui._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Ui._VJCanvasContext.beginPath(),Ui._VJCanvasContext.fillStyle="white",Ui._VJCanvasContext.beginPath(),Ui._VJCanvasContext.strokeStyle="red",Ui._VJCanvasContext.lineWidth=6,Ui._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),Ui._VJCanvasContext.stroke(),Ui._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){Ui.Canvas&&(Ui.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Ui.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Ui.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Ui.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Ui.Canvas),Ui.Canvas=null),this._released=!0}}Ui._GlobalJoystickIndex=0;Ui._AlwaysVisibleSticks=0;Gz.prototype.addVirtualJoystick=function(){return this.add(new E1e),this};class E1e{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=pe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=O.TransformCoordinates(new O(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),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 Ui(!0),this._leftjoystick.setAxisForUpDown(2),this._leftjoystick.setAxisForLeftRight(0),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Ui(!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"}}eu.FreeCameraVirtualJoystickInput=E1e;Dn.AddNodeConstructor("TargetCamera",(r,e)=>()=>new $a(r,O.Zero(),e));class $a extends di{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=O.Zero(),this._tmpTargetVector=O.Zero(),this.cameraDirection=new O(0,0,0),this.cameraRotation=new Ne(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new Oe,this.rotation=new O(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=O.Zero(),this._initialFocalDistance=1,this._viewMatrix=pe.Zero(),this._camMatrix=pe.Zero(),this._cameraTransformMatrix=pe.Zero(),this._cameraRotationMatrix=pe.Zero(),this._referencePoint=new O(0,0,1),this._transformedReferencePoint=O.Zero(),this._deferredPositionUpdate=new O,this._deferredRotationQuaternionUpdate=new Oe,this._deferredRotationUpdate=new O,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=O.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 O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Oe(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+=Ki),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),pe.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&&Oe.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(oe.Matrix[0]),O.TransformNormalToRef(this.cameraDirection,oe.Matrix[0],oe.Vector3[0]),this._deferredPositionUpdate.addInPlace(oe.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()&&(Oe.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()>Qe.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 Gz(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ie.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new O(0,0,0),this.cameraRotation=new Ne(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=O.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 n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=O.Zero(),this._transformedDirection=O.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"}}V([ta()],ql.prototype,"ellipsoid",void 0);V([ta()],ql.prototype,"ellipsoidOffset",void 0);V([Q()],ql.prototype,"checkCollisions",void 0);V([Q()],ql.prototype,"applyGravity",void 0);xe("BABYLON.FreeCamera",ql);Dn.AddNodeConstructor("TouchCamera",(r,e)=>()=>new T1e(r,O.Zero(),e));class T1e extends ql{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}}Dn.AddNodeConstructor("ArcRotateCamera",(r,e)=>()=>new mn(r,0,0,1,O.Zero(),e));class mn extends $a{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 pe,this._upToYMatrix=new pe,this._upVector=O.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){pe.RotationAlignToRef(O.UpReadOnly,this._upVector,this._yToUpMatrix),pe.RotationAlignToRef(this._upVector,O.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 vx,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 Vh,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 f9e,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,n,s,a,o=!0){super(e,O.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=O.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=Ne.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new pe,this.panningAxis=new O(1,1,0),this._transformedDirection=new O,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new Ce,this.checkCollisions=!1,this.collisionRadius=new O(.5,.5,.5),this._previousPosition=O.Zero(),this._collisionVelocity=O.Zero(),this._newPosition=O.Zero(),this._computationVector=O.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 g=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*h*p,this.radius*f,this.radius*d*p),g.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let m=this.upVector;this.allowUpsideDown&&this.beta<0&&(m=m.clone(),m=m.negate()),this._computeViewMatrix(this._position,g,m),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=O.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=n,this.getViewMatrix(),this.inputs=new QJ(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new O(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=Ne.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>Ki&&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,n=2){const s=arguments;t=Ie.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=n,typeof s[0]=="boolean"&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[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(O.Lerp(this.getTarget(),this._storedTarget,t)),Oe.RotationAlphaBetaGammaToRef(this._storedAlpha,this._storedBeta,0,oe.Quaternion[0]),Oe.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,oe.Quaternion[1]),Oe.SlerpToRef(oe.Quaternion[1],oe.Quaternion[0],t,oe.Quaternion[2]),oe.Quaternion[2].normalize(),oe.Quaternion[2].toAlphaBetaGammaToRef(oe.Vector3[0]),this.alpha=oe.Vector3[0].x,this.beta=oe.Vector3[0].y,this.radius+=(this._storedRadius-this.radius)*t,Ne.LerpToRef(this.targetScreenOffset,this._storedTargetScreenOffset,t,this.targetScreenOffset),(O.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)&&O.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,n=!1){if(n=this.overrideCloneAlphaBetaRadius??n,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 s=e,a=this._getTargetPosition();if(a&&!i&&a.equals(s))return;this._targetHost=null,this._target=s,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}n||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let n=Math.sin(this.beta);n===0&&(n=1e-4),this.radius===0&&(this.radius=1e-4);const s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&O.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.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&&n<0&&(a=a.negate()),this._computeViewMatrix(this._position,s,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Re.MinMax(e);let n=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);n=Math.max(Math.min(n,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)}focusOn(e,t=!1){let i,n;if(e.min===void 0){const s=e||this.getScene().meshes;i=Re.MinMax(s),n=O.Distance(i.min,i.max)}else{const s=e;i=s,n=s.distance}this._target=Re.Center(i),t||(this.maxZ=n*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case di.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case di.RIG_MODE_STEREOSCOPIC_OVERUNDER:case di.RIG_MODE_STEREOSCOPIC_INTERLACED:case di.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const n=new mn(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return n._cameraRigParams={},n.isRigCamera=!0,n.rigParent=this,n.upVector=this.upVector,n.mode=this.mode,n.orthoLeft=this.orthoLeft,n.orthoRight=this.orthoRight,n.orthoBottom=this.orthoBottom,n.orthoTop=this.orthoTop,n}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case di.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case di.RIG_MODE_STEREOSCOPIC_OVERUNDER:case di.RIG_MODE_STEREOSCOPIC_INTERLACED:case di.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case di.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 n=O.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*a,u=n*.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"}}V([Q()],mn.prototype,"alpha",void 0);V([Q()],mn.prototype,"beta",void 0);V([Q()],mn.prototype,"radius",void 0);V([Q()],mn.prototype,"overrideCloneAlphaBetaRadius",void 0);V([ta("target")],mn.prototype,"_target",void 0);V([Qw("targetHost")],mn.prototype,"_targetHost",void 0);V([Q()],mn.prototype,"inertialAlphaOffset",void 0);V([Q()],mn.prototype,"inertialBetaOffset",void 0);V([Q()],mn.prototype,"inertialRadiusOffset",void 0);V([Q()],mn.prototype,"lowerAlphaLimit",void 0);V([Q()],mn.prototype,"upperAlphaLimit",void 0);V([Q()],mn.prototype,"lowerBetaLimit",void 0);V([Q()],mn.prototype,"upperBetaLimit",void 0);V([Q()],mn.prototype,"lowerRadiusLimit",void 0);V([Q()],mn.prototype,"upperRadiusLimit",void 0);V([Q()],mn.prototype,"inertialPanningX",void 0);V([Q()],mn.prototype,"inertialPanningY",void 0);V([Q()],mn.prototype,"pinchToPanMaxDistance",void 0);V([Q()],mn.prototype,"panningDistanceLimit",void 0);V([ta()],mn.prototype,"panningOriginTarget",void 0);V([Q()],mn.prototype,"panningInertia",void 0);V([Q()],mn.prototype,"zoomToMouseLocation",null);V([Q()],mn.prototype,"zoomOnFactor",void 0);V([Cz()],mn.prototype,"targetScreenOffset",void 0);V([Q()],mn.prototype,"allowUpsideDown",void 0);V([Q()],mn.prototype,"useInputToRestoreState",void 0);V([Q()],mn.prototype,"restoreStateInterpolationFactor",void 0);xe("BABYLON.ArcRotateCamera",mn);Dn.AddNodeConstructor("DeviceOrientationCamera",(r,e)=>()=>new ZJ(r,O.Zero(),e));class ZJ extends ql{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new Oe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new Oe,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(n=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new Oe),Oe.FromEulerAnglesToRef(0,n.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=go.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new Oe),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 g9e extends Bz{constructor(e){super(e)}addKeyboard(){return this.add(new b3),this}addMouse(){return this.add(new Uz),this}}class sD extends $a{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,n=!0){super(e,t,i,n),this.ellipsoid=new O(1,1,1),this.ellipsoidOffset=new O(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=O.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=O.Zero(),this._diffPosition=O.Zero(),this._newPosition=O.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(s,a,o=null)=>{(c=>{this._newPosition.copyFrom(c),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Qe.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(a)},this.inputs=new g9e(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ie.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new O(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=O.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 n=e;this.applyGravity&&(n=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,n,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=O.Zero(),this._transformedDirection=O.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,n=t-i,s=.001;Math.abs(n)>=s&&(this.rotation.z+=n/e,Math.abs(t-this.rotation.z)<=s&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}V([ta()],sD.prototype,"ellipsoid",void 0);V([ta()],sD.prototype,"ellipsoidOffset",void 0);V([Q()],sD.prototype,"checkCollisions",void 0);V([Q()],sD.prototype,"applyGravity",void 0);xe("BABYLON.FlyCamera",sD);class _9e extends Bz{constructor(e){super(e)}addKeyboard(){return this.add(new kc),this}addMouseWheel(){return this.add(new ib),this}addPointers(){return this.add(new sd),this}addVRDeviceOrientation(){return ge.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Dn.AddNodeConstructor("FollowCamera",(r,e)=>()=>new Uu(r,O.Zero(),e));Dn.AddNodeConstructor("ArcFollowCamera",(r,e)=>()=>new M1e(r,0,0,1,null,e));class Uu extends $a{constructor(e,t,i,n=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=n,this.inputs=new _9e(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=oe.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),n=Ie.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),a=s.x+Math.sin(n)*this.radius,o=s.z+Math.cos(n)*this.radius,l=a-this.position.x,c=s.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 O(this.position.x+h,this.position.y+d,this.position.z+f),this.setTarget(s)}attachControl(e,t){t=Ie.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"}}V([Q()],Uu.prototype,"radius",void 0);V([Q()],Uu.prototype,"lowerRadiusLimit",void 0);V([Q()],Uu.prototype,"upperRadiusLimit",void 0);V([Q()],Uu.prototype,"rotationOffset",void 0);V([Q()],Uu.prototype,"lowerRotationOffsetLimit",void 0);V([Q()],Uu.prototype,"upperRotationOffsetLimit",void 0);V([Q()],Uu.prototype,"heightOffset",void 0);V([Q()],Uu.prototype,"lowerHeightOffsetLimit",void 0);V([Q()],Uu.prototype,"upperHeightOffsetLimit",void 0);V([Q()],Uu.prototype,"cameraAcceleration",void 0);V([Q()],Uu.prototype,"maxCameraSpeed",void 0);V([Qw("lockedTargetId")],Uu.prototype,"lockedTarget",void 0);class M1e extends $a{constructor(e,t,i,n,s,a){super(e,O.Zero(),a),this.alpha=t,this.beta=i,this.radius=n,this._cartesianCoordinates=O.Zero(),this.setMeshTarget(s)}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"}}xe("BABYLON.FollowCamera",Uu);xe("BABYLON.ArcFollowCamera",M1e);var ihe;(function(r){r[r.A=0]="A",r[r.B=1]="B",r[r.X=2]="X",r[r.Y=3]="Y",r[r.LB=4]="LB",r[r.RB=5]="RB",r[r.Back=8]="Back",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick"})(ihe||(ihe={}));var rhe;(function(r){r[r.Up=12]="Up",r[r.Down=13]="Down",r[r.Left=14]="Left",r[r.Right=15]="Right"})(rhe||(rhe={}));class v9e extends Zl{constructor(e,t,i,n=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new Ce,this.onButtonUpObservable=new Ce,this.onPadDownObservable=new Ce,this.onPadUpObservable=new Ce,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=Zl.XBOX,this._isXboxOnePad=n}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 nhe;(function(r){r[r.Cross=0]="Cross",r[r.Circle=1]="Circle",r[r.Square=2]="Square",r[r.Triangle=3]="Triangle",r[r.L1=4]="L1",r[r.R1=5]="R1",r[r.Share=8]="Share",r[r.Options=9]="Options",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick"})(nhe||(nhe={}));var she;(function(r){r[r.Up=12]="Up",r[r.Down=13]="Down",r[r.Left=14]="Left",r[r.Right=15]="Right"})(she||(she={}));class y9e extends Zl{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 Ce,this.onButtonUpObservable=new Ce,this.onPadDownObservable=new Ce,this.onPadUpObservable=new Ce,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=Zl.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 Ce,dl()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new Ce(t=>{for(const i in this._babylonGamepads){const n=this._babylonGamepads[i];n&&n._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,n)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let n;this._babylonGamepads[i.index]?(n=this._babylonGamepads[i.index],n.browserGamepad=i,n._isConnected=!0):n=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(n),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const n in this._babylonGamepads)if(this._babylonGamepads[n].index===i.index){const s=this._babylonGamepads[n];s._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(s),s.dispose&&s.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=Zl.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,n=e.id.search("Xbox One")!==-1;return n||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new v9e(e.id,e.index,e,n):i?t=new y9e(e.id,e.index,e):t=new m9e(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&&(Ie.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Qe.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new rb(r,O.Zero(),e));class rb extends T1e{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"}}di._CreateDefaultParsedCamera=(r,e)=>new rb(r,O.Zero(),e);Dn.AddNodeConstructor("GamepadCamera",(r,e)=>()=>new qJ(r,O.Zero(),e));class qJ extends rb{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const C9e="postprocessVertexShader",A9e=`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 }`;me.ShadersStore[C9e]=A9e;const S9e={name:C9e,shader:A9e},Yvt=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShader:S9e},Symbol.toStringTag,{value:"Module"}));class Kz{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 n=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,n}constructor(e,t,i,n,s){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=n,this._depthStencilTexture=null,this.label=s}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,n=1,s=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:n,depthTextureFormat:s,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,n,s,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=[],g=[],m=[],_=[],y=[],v={};for(let C=0;C1&&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 Qvt extends Kz{constructor(e,t,i,n,s){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_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,n=1,s=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,n,s,a)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer,s=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;s._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),s._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,n=0){var l,c;if(!e._hardwareTexture)return;const s=this._framebuffer,a=this._engine,o=a._currentFramebuffer;if(a._bindUnboundFramebuffer(s),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,n,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,n)):u.framebufferTexture2D(u.FRAMEBUFFER,h,u.TEXTURE_2D,e._hardwareTexture.underlyingResource,n)}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,n)}a._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=((n=this._attachments)==null?void 0:n.length)??this.textures.length;for(let s=0;s1&&(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(s,0,h,a.width,a.height,i,0,u,c,null):a.is3D?t.texImage3D(s,0,h,a.width,a.height,n,0,u,c,null):t.texImage2D(s,0,h,a.width,a.height,0,u,c,null),this._bindTextureDirectly(s,null),this._internalTexturesCache.push(a),a};ir.prototype.updateRenderTargetTextureSampleCount=function(r,e){if(this.webGLVersion<2||!r||!r.texture)return 1;if(r.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),r._depthStencilBuffer&&(t.deleteRenderbuffer(r._depthStencilBuffer),r._depthStencilBuffer=null),r._MSAAFramebuffer&&(t.deleteFramebuffer(r._MSAAFramebuffer),r._MSAAFramebuffer=null);const i=r.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const n=t.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");r._MSAAFramebuffer=n,this._bindUnboundFramebuffer(r._MSAAFramebuffer);const s=this._createRenderBuffer(r.texture.width,r.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(r.texture.type,r.texture.format,r.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!s)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(s)}else this._bindUnboundFramebuffer(r._framebuffer);return r.texture.samples=e,r._samples=e,r._depthStencilBuffer=this._setupFramebufferDepthAttachments(r._generateStencilBuffer,r._generateDepthBuffer,r.texture.width,r.texture.height,e),this._bindUnboundFramebuffer(null),e};ir.prototype._setupDepthStencilTexture=function(r,e,t,i,n,s=1){const a=e.width||e,o=e.height||e,l=e.layers||0,c=e.depth||0;r.baseWidth=a,r.baseHeight=o,r.width=a,r.height=o,r.is2DArray=l>0,r.depth=l||c,r.isReady=!0,r.samples=s,r.generateMipMaps=!1,r.samplingMode=i?2:1,r.type=0,r._comparisonFunction=n;const u=this._gl,h=this._getTextureTarget(r),d=this._getSamplingParameters(r.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&&(n===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,n),u.texParameteri(h,u.TEXTURE_COMPARE_MODE,u.COMPARE_REF_TO_TEXTURE)))};Qe.prototype.setTextureFromPostProcess=function(r,e,t){let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(r,(i==null?void 0:i.texture)??null,t)};Qe.prototype.setTextureFromPostProcessOutput=function(r,e,t){var i;this._bindTexture(r,((i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)??null,t)};Sr.prototype.setTextureFromPostProcess=function(r,e){this._engine.setTextureFromPostProcess(this._samplers[r],e,r)};Sr.prototype.setTextureFromPostProcessOutput=function(r,e){this._engine.setTextureFromPostProcessOutput(this._samplers[r],e,r)};class ii{static RegisterShaderCodeProcessing(e,t){if(!t){delete ii._CustomShaderCodeProcessing[e??""];return}ii._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return ii._CustomShaderCodeProcessing[e]??ii._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,n,s,a,o=1,l,c,u=null,h=0,d="postprocess",f,p=!1,g=5,m,_){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 Go(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new Ne(1,1),this._texelSize=Ne.Zero(),this.onEffectCreatedObservable=new Ce(void 0,!0),this.onActivateObservable=new Ce,this.onSizeChangedObservable=new Ce,this.onApplyObservable=new Ce,this.onBeforeRenderObservable=new Ce,this.onAfterRenderObservable=new Ce,this._importPromises=[],this.name=e;let y=1,v=null;if(i&&!Array.isArray(i)){const x=i;i=x.uniforms??null,n=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,g=x.textureFormat??5,m=x.shaderLanguage??0,v=x.uniformBuffers??null}else s&&(typeof s=="number"?y=s:y={width:s.width,height:s.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=g,this._shaderLanguage=m||0,this._samplers=n||[],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 pl(this._engine),this._webGPUReady=this._shaderLanguage===1,this._postConstructor(p,u,_)}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([je(()=>Promise.resolve().then(()=>WIt),void 0)])):t.push(Promise.all([je(()=>Promise.resolve().then(()=>Yvt),void 0)]))}_postConstructor(e,t=null,i){const s=this.getEngine().isWebGPU&&!ii.ForceGLSL;this._gatherImports(s,this._importPromises),i&&i(s,this._importPromises),s&&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 Go(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,s,a,o,l){const c=ii._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:s??null,onError:a??null,indexParameters:n||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 s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let n=0;n0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let c=0;c{g.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(g,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:n.clearColor,n._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,n;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),(n=(i=ii._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||n.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=ot.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=ii.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 n=Sa(e.customType);if(!n||!n._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return n._Parse(e,s,t,i)}static _Parse(e,t,i,n){return ot.Parse(()=>new ii(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,n)}}ii.ForceGLSL=!1;ii._CustomShaderCodeProcessing={};V([Q()],ii.prototype,"uniqueId",void 0);V([Q()],ii.prototype,"name",void 0);V([Q()],ii.prototype,"width",void 0);V([Q()],ii.prototype,"height",void 0);V([Q()],ii.prototype,"renderTargetSamplingMode",void 0);V([Zw()],ii.prototype,"clearColor",void 0);V([Q()],ii.prototype,"autoClear",void 0);V([Q()],ii.prototype,"forceAutoClearInAlphaMode",void 0);V([Q()],ii.prototype,"alphaMode",void 0);V([Q()],ii.prototype,"alphaConstants",void 0);V([Q()],ii.prototype,"enablePixelPerfectMode",void 0);V([Q()],ii.prototype,"forceFullscreenViewport",void 0);V([Q()],ii.prototype,"scaleMode",void 0);V([Q()],ii.prototype,"alwaysForcePOT",void 0);V([Q("samples")],ii.prototype,"_samples",void 0);V([Q()],ii.prototype,"adaptScaleToCurrentViewport",void 0);xe("BABYLON.PostProcess",ii);class J0 extends ii{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,s,a,o=0,l=!1){super(e,"pass",null,null,t,i,n,s,a,void 0,o,void 0,null,l)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>hPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>n3t),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new J0(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,n)}}xe("BABYLON.PassPostProcess",J0);class R1e extends ii{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,n,s,a,o=0,l=!1){super(e,"passCube",null,null,t,i,n,s,a,"#define POSITIVEX",o,void 0,null,l),this._face=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>dPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>uPt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new R1e(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,n)}}Qe._RescalePostProcessFactory=r=>new J0("rescale",1,null,2,r,!1,0);class I1e extends ii{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,n,s,a){super(e,"anaglyph",null,["leftSampler"],t,i[1],n,s,a),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(je(()=>Promise.resolve().then(()=>FPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>NPt),void 0)),super._gatherImports(e,t)}}xe("BABYLON.AnaglyphPostProcess",I1e);function Hz(r){r._rigCameras[0]._rigPostProcess=new J0(r.name+"_passthru",1,r._rigCameras[0]),r._rigCameras[1]._rigPostProcess=new I1e(r.name+"_anaglyph",1,r._rigCameras)}Dn.AddNodeConstructor("AnaglyphArcRotateCamera",(r,e,t)=>()=>new E9e(r,0,0,1,O.Zero(),t.interaxial_distance,e));class E9e extends mn{constructor(e,t,i,n,s,a,o){super(e,t,i,n,s,o),this._setRigMode=()=>Hz(this),this.interaxialDistance=a,this.setCameraRigMode(di.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}getClassName(){return"AnaglyphArcRotateCamera"}}Dn.AddNodeConstructor("AnaglyphFreeCamera",(r,e,t)=>()=>new T9e(r,O.Zero(),t.interaxial_distance,e));class T9e extends ql{constructor(e,t,i,n){super(e,t,n),this._setRigMode=()=>Hz(this),this.interaxialDistance=i,this.setCameraRigMode(di.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Dn.AddNodeConstructor("AnaglyphGamepadCamera",(r,e,t)=>()=>new M9e(r,O.Zero(),t.interaxial_distance,e));class M9e extends qJ{constructor(e,t,i,n){super(e,t,n),this._setRigMode=()=>Hz(this),this.interaxialDistance=i,this.setCameraRigMode(di.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Dn.AddNodeConstructor("AnaglyphUniversalCamera",(r,e,t)=>()=>new R9e(r,O.Zero(),t.interaxial_distance,e));class R9e extends rb{constructor(e,t,i,n){super(e,t,n),this._setRigMode=()=>Hz(this),this.interaxialDistance=i,this.setCameraRigMode(di.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const Zvt="stereoscopicInterlacePixelShader",qvt=`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);} `;me.ShadersStore[Zvt]=qvt;class I9e extends ii{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,n,s,a,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,a,o,n?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Ne(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Ne(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 Jvt extends ii{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,n,s,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],n,s,a,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new Ne(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new Ne(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 jz(r){const e=r.cameraRigMode===di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||r.cameraRigMode===di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=r.cameraRigMode===di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;r.cameraRigMode===di.RIG_MODE_STEREOSCOPIC_INTERLACED?(r._rigCameras[0]._rigPostProcess=new J0(r.name+"_passthru",1,r._rigCameras[0]),r._rigCameras[1]._rigPostProcess=new I9e(r.name+"_stereoInterlace",r._rigCameras,!1,!0)):(r._rigCameras[t?1:0].viewport=new Yc(0,0,e?.5:1,e?1:.5),r._rigCameras[t?0:1].viewport=new Yc(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Dn.AddNodeConstructor("StereoscopicArcRotateCamera",(r,e,t)=>()=>new P9e(r,0,0,1,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class P9e extends mn{constructor(e,t,i,n,s,a,o,l){super(e,t,i,n,s,l),this._setRigMode=()=>jz(this),this.interaxialDistance=a,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:di.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}getClassName(){return"StereoscopicArcRotateCamera"}}Dn.AddNodeConstructor("StereoscopicFreeCamera",(r,e,t)=>()=>new w9e(r,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class w9e extends ql{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=()=>jz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:di.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Dn.AddNodeConstructor("StereoscopicGamepadCamera",(r,e,t)=>()=>new D9e(r,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class D9e extends qJ{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=()=>jz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:di.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Dn.AddNodeConstructor("StereoscopicFreeCamera",(r,e,t)=>()=>new O9e(r,O.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class O9e extends rb{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=()=>jz(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:di.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class e3t extends rb{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,n=1,s=.065){super(e,t,i),this._distanceBetweenEyes=s,this._distanceToProjectionPlane=n,this.setCameraRigMode(di.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=s}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new $a(e,O.Zero(),this.getScene()),i=new Yt("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(pe.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new L9e(r,O.Zero(),e));class L9e extends ql{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class sT{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 pe.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return pe.Translation(-t,0,0)}get leftPreViewMatrix(){return pe.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return pe.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new sT;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 ahe extends ii{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,n){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,t,be.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=n.distortionK,this._postProcessScaleFactor=n.postProcessScaleFactor,this._lensCenterOffset=n.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new Ne(2,2/this.aspectRatio),this._scaleFactor=new Ne(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new Ne(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(s=>{s.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),s.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),s.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),s.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(je(()=>Promise.resolve().then(()=>pPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>fPt),void 0)),super._gatherImports(e,t)}}const t3t="vrMultiviewToSingleviewPixelShader",i3t=`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));}`;me.ShadersStore[t3t]=i3t;class P1e{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new N9e(e)}sampleFrame(e=hn.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 N9e{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}}ir.prototype.setAlphaMode=function(r,e=!1){if(this._alphaMode===r){if(!e){const t=r===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(r){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=r===0),this._alphaMode=r};ir.prototype.updateDynamicIndexBuffer=function(r,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(r);let i;r.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()};ir.prototype.updateDynamicVertexBuffer=function(r,e,t,i){this.bindArrayBuffer(r),t===void 0&&(t=0);const n=e.byteLength||e.length;i===void 0||i>=n&&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()};Qe.prototype.displayLoadingUI=function(){if(!dl())return;const r=this.loadingScreen;r&&r.displayLoadingUI()};Qe.prototype.hideLoadingUI=function(){if(!dl())return;const r=this._loadingScreen;r&&r.hideLoadingUI()};Object.defineProperty(Qe.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Qe.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(r){this._loadingScreen=r},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"loadingUIText",{set:function(r){this.loadingScreen.loadingUIText=r},enumerable:!0,configurable:!0});Object.defineProperty(Qe.prototype,"loadingUIBackgroundColor",{set:function(r){this.loadingScreen.loadingUIBackgroundColor=r},enumerable:!0,configurable:!0});Qe.prototype.getInputElement=function(){return this._renderingCanvas};Qe.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};Qe.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};Qe.prototype.getAspectRatio=function(r,e=!1){const t=r.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};Qe.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};Qe.prototype._verifyPointerLock=function(){var r;(r=this._onPointerLockChange)==null||r.call(this)};Qe.prototype.setAlphaEquation=function(r){if(this._alphaEquation!==r){switch(r){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=r}};Qe.prototype.getInputElement=function(){return this._renderingCanvas};Qe.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};Qe.prototype.setDepthFunction=function(r){this._depthCullingState.depthFunc=r};Qe.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};Qe.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};Qe.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};Qe.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};Qe.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};Qe.prototype.setDepthWrite=function(r){this._depthCullingState.depthMask=r};Qe.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};Qe.prototype.setStencilBuffer=function(r){this._stencilState.stencilTest=r};Qe.prototype.getStencilMask=function(){return this._stencilState.stencilMask};Qe.prototype.setStencilMask=function(r){this._stencilState.stencilMask=r};Qe.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};Qe.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};Qe.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};Qe.prototype.setStencilFunction=function(r){this._stencilState.stencilFunc=r};Qe.prototype.setStencilFunctionReference=function(r){this._stencilState.stencilFuncRef=r};Qe.prototype.setStencilFunctionMask=function(r){this._stencilState.stencilFuncMask=r};Qe.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};Qe.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};Qe.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};Qe.prototype.setStencilOperationFail=function(r){this._stencilState.stencilOpStencilFail=r};Qe.prototype.setStencilOperationDepthFail=function(r){this._stencilState.stencilOpDepthFail=r};Qe.prototype.setStencilOperationPass=function(r){this._stencilState.stencilOpStencilDepthPass=r};Qe.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()};Qe.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)};Qe.prototype.setAlphaConstants=function(r,e,t,i){this._alphaState.setAlphaBlendConstants(r,e,t,i)};Qe.prototype.getAlphaMode=function(){return this._alphaMode};Qe.prototype.getAlphaEquation=function(){return this._alphaEquation};Qe.prototype.getRenderPassNames=function(){return this._renderPassNames};Qe.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};Qe.prototype.createRenderPassId=function(r){const e=++Qe._RenderPassIdCounter;return this._renderPassNames[e]=r??"NONAME",e};Qe.prototype.releaseRenderPassId=function(r){this._renderPassNames[r]=void 0;for(let e=0;e{r.onCanvasFocusObservable.notifyObservers(r)},r._onCanvasBlur=()=>{r.onCanvasBlurObservable.notifyObservers(r)},r._onCanvasContextMenu=n=>{r.disableContextMenu&&n.preventDefault()},e.addEventListener("focus",r._onCanvasFocus),e.addEventListener("blur",r._onCanvasBlur),e.addEventListener("contextmenu",r._onCanvasContextMenu),r._onBlur=()=>{r.disablePerformanceMonitorInBackground&&r.performanceMonitor.disable(),r._windowIsBackground=!0},r._onFocus=()=>{r.disablePerformanceMonitorInBackground&&r.performanceMonitor.enable(),r._windowIsBackground=!1},r._onCanvasPointerOut=n=>{document.elementFromPoint(n.clientX,n.clientY)!==e&&r.onCanvasPointerOutObservable.notifyObservers(n)};const i=r.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",r._onBlur),i.addEventListener("focus",r._onFocus)),e.addEventListener("pointerout",r._onCanvasPointerOut),t.doNotHandleTouchAction||r3t(e),!Qe.audioEngine&&t.audioEngine&&Qe.AudioEngineFactory&&(Qe.audioEngine=Qe.AudioEngineFactory(r.getRenderingCanvas(),r.getAudioContext(),r.getAudioDestination())),OS()&&(r._onFullscreenChange=()=>{r.isFullscreen=!!document.fullscreenElement,r.isFullscreen&&r._pointerLockRequested&&e&&JJ(e)},document.addEventListener("fullscreenchange",r._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",r._onFullscreenChange,!1),r._onPointerLockChange=()=>{r.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",r._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",r._onPointerLockChange,!1)),r.enableOfflineSupport=Qe.OfflineProviderFactory!==void 0,r._deterministicLockstep=!!t.deterministicLockstep,r._lockstepMaxSteps=t.lockstepMaxSteps||0,r._timeStep=t.timeStep||1/60}function D1e(r,e){ei.Instances.length===1&&Qe.audioEngine&&(Qe.audioEngine.dispose(),Qe.audioEngine=null);const t=r.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",r._onBlur),t.removeEventListener("focus",r._onFocus)),e&&(e.removeEventListener("focus",r._onCanvasFocus),e.removeEventListener("blur",r._onCanvasBlur),e.removeEventListener("pointerout",r._onCanvasPointerOut),e.removeEventListener("contextmenu",r._onCanvasContextMenu)),OS()&&(document.removeEventListener("fullscreenchange",r._onFullscreenChange),document.removeEventListener("mozfullscreenchange",r._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",r._onFullscreenChange),document.removeEventListener("msfullscreenchange",r._onFullscreenChange),document.removeEventListener("pointerlockchange",r._onPointerLockChange),document.removeEventListener("mspointerlockchange",r._onPointerLockChange),document.removeEventListener("mozpointerlockchange",r._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",r._onPointerLockChange))}function O1e(r){const e=document.createElement("span");e.textContent="Hg",e.style.font=r;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 n=0,s=0;try{s=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",n=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:n,height:s,descent:s-n}}function L1e(r,e,t){return new Promise((n,s)=>{const a=new Image;a.onload=()=>{a.decode().then(()=>{r.createImageBitmap(a,t).then(o=>{n(o)})})},a.onerror=()=>{s(`Error loading image ${a.src}`)},a.src=e})}function N1e(r,e,t,i){const s=r.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}function F1e(r){const e=r.requestFullscreen||r.webkitRequestFullscreen;e&&e.call(r)}function B1e(){const r=document;document.exitFullscreen?document.exitFullscreen():r.webkitCancelFullScreen&&r.webkitCancelFullScreen()}function JJ(r){if(r.requestPointerLock){const e=r.requestPointerLock();e instanceof Promise?e.then(()=>{r.focus()}).catch(()=>{}):r.focus()}}function k1e(){document.exitPointerLock&&document.exitPointerLock()}class Vt extends ir{static get NpmPackage(){return Qe.NpmPackage}static get Version(){return Qe.Version}static get Instances(){return ei.Instances}static get LastCreatedEngine(){return ei.LastCreatedEngine}static get LastCreatedScene(){return ei.LastCreatedScene}static DefaultLoadingScreenFactory(e){return Qe.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,n=!1){if(super(e,t,i,n),this.customAnimationFrameRequester=null,this._performanceMonitor=new P1e,this._drawCalls=new zo,!!e&&(this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext)){const s=e;this._sharedInit(s)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),w1e(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return N1e(this,e,t,i)}_createImageBitmapFromSource(e,t){return L1e(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&F1e(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&B1e()}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,n){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),s}scissorClear(e,t,i,n,s){this.enableScissor(e,t,i,n),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise((n,s)=>{this._loadFile(e,a=>{n(a)},void 0,t,i,(a,o)=>{s(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 O1e(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&&JJ(this._renderingCanvas)}exitPointerlock(){k1e()}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,n,s,a=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,n,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,n,s=null){const a=n.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");if(n.attachShader(a,t),n.attachShader(a,i),this.webGLVersion>1&&s){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=o}return n.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=n,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(n=>{n&&n._outputTexture===e&&(n._outputTexture=null)})})})}_rescaleTexture(e,t,i,n,s){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,n,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()},l=this._rescalePostProcess.getEffect();l?l.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(c=>{c.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,n=0,s=0){const a=new iT(e,this._gl),o=new _n(this,0,!0);return o._hardwareTexture=a,o.baseWidth=n,o.baseHeight=s,o.width=n,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,n=0){const s=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let u=s.TEXTURE_2D;e.isCube&&(u=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(u,n,l,o,a,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){ge.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 ow(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 n=this._gl;return new Promise((s,a)=>{const o=()=>{const l=n.clientWaitSync(e,t,0);if(l==n.WAIT_FAILED){a();return}if(l==n.TIMEOUT_EXPIRED){setTimeout(o,i);return}s()};o()})}_readPixelsAsync(e,t,i,n,s,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,n,s,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(),D1e(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;ir.prototype.createRenderTargetCubeTexture=function(r,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,r),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 n=this._gl,s=new _n(this,5);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,s,!0);const a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,ge.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,a.min),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);for(let l=0;l<6;l++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),r,r,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=n.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,r,r),i.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,s.width=r,s.height=r,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),t};ir.prototype.setDepthStencilTexture=function(r,e,t,i){r!==void 0&&(e&&(this._boundUniforms[r]=e),!t||!t.depthStencilTexture?this._setTexture(r,null,void 0,void 0,i):this._setTexture(r,t,!1,!0,i))};const hae={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class aD{constructor(e,t=hae){this._fullscreenViewport=new Yc(0,0,1,1);const i=t.positions??hae.positions,n=t.indices??hae.indices;this.engine=e,this._vertexBuffers={[ee.PositionKind]:new ee(e,i,ee.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(n);for(const s in this._vertexBuffers)this._vertexBuffers[s]._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[ee.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ee.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class _g{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new Ce;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 n=e.defines?e.defines.join(` `):"";this._drawWrapper=new pl(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,n,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage,e.extraInitializationsAsync)):(this.effect=new Sr(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,n,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage,e.extraInitializationsAsync),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 F9e="passPixelShader",B9e=`varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);}`;me.ShadersStore[F9e]=B9e;const _Z={name:F9e,shader:B9e},n3t=Object.freeze(Object.defineProperty({__proto__:null,passPixelShader:_Z},Symbol.toStringTag,{value:"Module"}));let Qy;function s3t(){if(!Qy){let r,e=null;const t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{r=new OffscreenCanvas(100,100),e=new ir(r,!1,t)}catch{r=document.createElement("canvas"),e=new ir(r,!1,t)}ei.Instances.pop(),ei.OnEnginesDisposedObservable.add(s=>{e&&s!==e&&!e.isDisposed&&ei.Instances.length===0&&k9e()}),e.getCaps().parallelShaderCompile=void 0;const i=new aD(e),n=new _g({engine:e,name:_Z.name,fragmentShader:_Z.shader,samplerNames:["textureSampler"]});Qy={canvas:r,engine:e,renderer:i,wrapper:n}}return Qy}async function U1e(r,e,t,i,n="image/png",s,a){const o=await t.readPixels(0,0,r,e),l=new Uint8Array(o.buffer);eE(r,e,l,i,n,s,!0,void 0,a)}function z1e(r,e,t,i="image/png",n,s=!1,a=!1,o){return new Promise(l=>{eE(r,e,t,c=>l(c),i,n,s,a,o)})}function eE(r,e,t,i,n="image/png",s,a=!1,o=!1,l){const c=s3t();if(c.engine.setSize(r,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(Xt.Clamp(f)*255)}t=h}const u=c.engine.createRawTexture(t,r,e,5,!1,!a,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),o?Ie.ToBlob(c.canvas,h=>{const d=new FileReader;d.onload=f=>{const p=f.target.result;i&&i(p)},d.readAsArrayBuffer(h)},n,l):Ie.EncodeScreenshotCanvasData(c.canvas,i,n,s,l),u.dispose()}function k9e(){Qy&&(Qy.wrapper.dispose(),Qy.renderer.dispose(),Qy.engine.dispose()),Qy=null}const a3t={DumpData:eE,DumpDataAsync:z1e,DumpFramebuffer:U1e,Dispose:k9e},o3t=()=>{Ie.DumpData=eE,Ie.DumpDataAsync=z1e,Ie.DumpFramebuffer=U1e};o3t();Sr.prototype.setDepthStencilTexture=function(r,e){this._engine.setDepthStencilTexture(this._samplers[r],this._uniforms[r],e,r)};class vn extends be{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=JFe(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 n=0;n{var E;const A=this._renderList?this._renderList.length:0;(C===0&&A>0||A===0)&&((E=this.getScene())==null||E.meshes.forEach(P=>{P._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new Ce,this.onAfterUnbindObservable=new Ce,this.onBeforeRenderObservable=new Ce,this.onAfterRenderObservable=new Ce,this.onClearObservable=new Ce,this.onResizeObservable=new Ce,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=O.Zero(),i=this.getScene(),!i)return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=be.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=!!n,this._doNotChangeAspectRatio=s,this._renderingManager=new Rc(i),this._renderingManager._useSceneAutoClearSetup=!0,!h&&(this._renderTargetOptions={generateMipMaps:n,type:a,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:u,samples:p,creationFlags:g,noColorAttachment:m,useSRGBBuffer:_,colorAttachment:y,label:this.name},this.samplingMode===be.NEAREST_SAMPLINGMODE&&(this.wrapU=be.CLAMP_ADDRESSMODE,this.wrapV=be.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=be.INVCUBIC_MODE,this._textureMatrix=pe.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,n=1,s=14,a){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,n,s,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 n;const t=this.isCube;(n=this._renderTarget)==null||n.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 n=this.getScene();if(!n)return i;const s=n.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,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!n||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,s=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 #${n}`,1),this._prepareFrame(a,e,n,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(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?n:e,f,p)),d?this._prepareRenderingManager(d,d.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(f,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),d=f);for(const m of a._beforeRenderTargetClearStage)m.action(this,e,n);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 m of a._beforeRenderTargetDrawStage)m.action(this,e,n);this._renderingManager.render(this.customRenderFunction,d,this.renderParticles,this.renderSprites);for(const m of a._afterRenderTargetDrawStage)m.action(this,e,n);const g=((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 m of a._afterRenderTargetPostProcessStage)m.action(this,e,n);this._texture&&(this._texture.generateMipMaps=g),this._doNotChangeAspectRatio||a.updateTransformMatrix(!0),i&&U1e(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,n=null){this._renderingManager.setRenderingOrder(e,t,i,n)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new vn(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 n of e.cameras)t=n.customRenderTargets.indexOf(this),t>=0&&n.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===vn.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=vn.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}vn.REFRESHRATE_RENDER_ONCE=0;vn.REFRESHRATE_RENDER_ONEVERYFRAME=1;vn.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;be._CreateRenderTargetTexture=(r,e,t,i,n)=>new vn(r,e,t,i);class ohe extends vn{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(r,e,t,i){const n=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const s=this._createHardwareRenderTargetWrapper(!1,!1,{width:r,height:e});s._framebuffer=n.createFramebuffer();const a=new _n(this,0,!0);return a.width=r,a.height=e,a.isMultiview=!0,t||(t=n.createTexture(),n.bindTexture(n.TEXTURE_2D_ARRAY,t),n.texStorage3D(n.TEXTURE_2D_ARRAY,1,n.RGBA8,r,e,2)),s._colorTextureArray=t,i||(i=n.createTexture(),n.bindTexture(n.TEXTURE_2D_ARRAY,i),n.texStorage3D(n.TEXTURE_2D_ARRAY,1,n.DEPTH24_STENCIL8,r,e,2)),s._depthStencilTextureArray=i,a.isReady=!0,s.setTextures(a),s._depthStencilTexture=a,s};Vt.prototype.bindMultiviewFramebuffer=function(r){const e=r,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(r){const e=r,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")};di.prototype._useMultiviewToSingleView=!1;di.prototype._multiviewTexture=null;di.prototype._resizeOrCreateMultiviewTexture=function(r,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=r||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new ohe(this.getScene(),{width:r,height:e})):this._multiviewTexture=new ohe(this.getScene(),{width:r,height:e})};function U9e(r,e){const t=new Ci(r,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 l3t=Ut.prototype.createSceneUniformBuffer;Ut.prototype._transformMatrixR=pe.Zero();Ut.prototype._multiviewSceneUbo=null;Ut.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=U9e(this.getEngine(),"scene_multiview")};Ut.prototype.createSceneUniformBuffer=function(r){return this._multiviewSceneUbo?U9e(this.getEngine(),r):l3t.bind(this)(r)};Ut.prototype._updateMultiviewUbo=function(r,e){r&&e&&r.multiplyToRef(e,this._transformMatrixR),r&&e&&(r.multiplyToRef(e,oe.Matrix[0]),lf.GetRightPlaneToRef(oe.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))};Ut.prototype._renderMultiviewToSingleView=function(r){r._resizeOrCreateMultiviewTexture(r._rigPostProcess&&r._rigPostProcess&&r._rigPostProcess.width>0?r._rigPostProcess.width:this.getEngine().getRenderWidth(!0),r._rigPostProcess&&r._rigPostProcess&&r._rigPostProcess.height>0?r._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),r.outputRenderTarget=r._multiviewTexture,this._renderForCamera(r),r.outputRenderTarget=null;for(let e=0;e{}),this.onApplyObservable.add(s=>{n._scene.activeCamera&&n._scene.activeCamera.isLeftCamera?s.setInt("imageIndex",0):s.setInt("imageIndex",1),s.setTexture("multiviewSampler",n._multiviewTexture)})}}function eee(r,e){const t=e.vrCameraMetrics||sT.GetDefault();r._rigCameras[0]._cameraRigParams.vrMetrics=t,r._rigCameras[0].viewport=new Yc(0,0,.5,1),r._rigCameras[0]._cameraRigParams.vrWorkMatrix=new pe,r._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,r._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,r._rigCameras[0].getProjectionMatrix=r._rigCameras[0]._getVRProjectionMatrix,r._rigCameras[1]._cameraRigParams.vrMetrics=t,r._rigCameras[1].viewport=new Yc(.5,0,.5,1),r._rigCameras[1]._cameraRigParams.vrWorkMatrix=new pe,r._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,r._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,r._rigCameras[1].getProjectionMatrix=r._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(r.getScene().getEngine().getCaps().multiview?(r._useMultiviewToSingleView=!0,r._rigPostProcess=new z9e("VRMultiviewToSingleview",r,t.postProcessScaleFactor)):(ge.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(r._rigCameras[0]._rigPostProcess=new ahe("VR_Distort_Compensation_Left",r._rigCameras[0],!1,t),r._rigCameras[1]._rigPostProcess=new ahe("VR_Distort_Compensation_Right",r._rigCameras[1],!0,t))}Dn.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(r,e)=>()=>new V9e(r,0,0,1,O.Zero(),e));class V9e extends mn{constructor(e,t,i,n,s,a,o=!0,l=sT.GetDefault()){super(e,t,i,n,s,a),this._setRigMode=c=>eee(this,c),l.compensateDistortion=o,this.setCameraRigMode(di.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Dn.AddNodeConstructor("VRDeviceOrientationFreeCamera",(r,e)=>()=>new tee(r,O.Zero(),e));class tee extends ZJ{constructor(e,t,i,n=!0,s=sT.GetDefault()){super(e,t,i),this._setRigMode=a=>eee(this,a),s.compensateDistortion=n,this.setCameraRigMode(di.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Dn.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(r,e)=>()=>new G9e(r,O.Zero(),e));class G9e extends tee{constructor(e,t,i,n=!0,s=sT.GetDefault()){super(e,t,i,n,s),this._setRigMode=a=>eee(this,a),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class vZ{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,n,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(t.prePassRenderer.getIndex(2)!==-1||t.prePassRenderer.getIndex(11)!==-1)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=n.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]=n.clone()}}}class Kn{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 n,s,a,o;const t=((s=(n=this._externalProperties)==null?void 0:n[e])==null?void 0:s.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 n=0;n0&&(s.computeBonesUsingShaders=!1);continue}if(!(!s.computeBonesUsingShaders||s.numBoneInfluencers===0)){if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes){for(const a of s.subMeshes)if(a.effect===t){s.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let n=0;nthis._handlePluginEvent(n,s),this._plugins.push(e),this._plugins.sort((n,s)=>n.priority-s.priority),this._codeInjectionPoints={};const i={};i[Pv._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const n of this._plugins)n.collectDefines(i),this._collectPointNames("vertex",n.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",n.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 n=this._material.shaderLanguage===1;for(const s of this._plugins){const a=s.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),n){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+` `)}s.getSamplers(this._samplerList),s.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,n)=>{var o,l;t&&(n=t(i,n)),this._uboDeclaration&&(n=n.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(n=n.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(n=n.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!s)return n;let a=null;for(let c in s){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:me.GetShadersRepository(0),includesShadersStore:me.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",Hk(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 g=c3t.exec(c);g&&g.length>=2&&(h=g[1],c=c.substring(h.length+1))}h.indexOf("g")<0&&(h+="g");const d=n,f=new RegExp(c,h);let p=f.exec(d);for(;p!==null;){let g=u;for(let m=0;m{V1e()});const tx=[];let lhe=!1,che=null;function u3t(r,e){lhe||(che=tt.OnEventObservable.add(i=>{for(const[,n]of tx)n(i)},1),lhe=!0);const t=tx.filter(([i,n])=>i===r);t.length>0?t[0][1]=e:tx.push([r,e])}function h3t(r){for(let e=0;e{e.pluginManager=void 0})),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}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){ot.Clone(()=>e,this)}serialize(){return ot.Serialize(this)}parse(e,t,i){ot.Parse(()=>this,e,t,i)}}V([Q()],Yu.prototype,"name",void 0);V([Q()],Yu.prototype,"priority",void 0);V([Q()],Yu.prototype,"resolveIncludes",void 0);V([Q()],Yu.prototype,"registerForExtraEvents",void 0);xe("BABYLON.MaterialPluginBase",Yu);class W9e extends Kn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class z_ extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new W9e,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=tt.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&<.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&<.DetailTextureEnabled&&this._isEnabled?(Is(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&<.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Ps(this._texture,e,"detail")),t.texturesEnabled&&this._texture&<.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"}]}}}V([ki("detailTexture"),Ke("_markAllSubMeshesAsTexturesDirty")],z_.prototype,"texture",void 0);V([Q()],z_.prototype,"diffuseBlendLevel",void 0);V([Q()],z_.prototype,"roughnessBlendLevel",void 0);V([Q()],z_.prototype,"bumpLevel",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],z_.prototype,"normalBlendMethod",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],z_.prototype,"isEnabled",void 0);const dae={effect:null,subMesh:null};class K9e extends Kn{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_NDC_DEPTH=!1,this.PREPASS_NDC_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_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 ct extends Va{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 Pe(0,0,0),this.diffuseColor=new Pe(1,1,1),this.specularColor=new Pe(1,1,1),this.emissiveColor=new Pe(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 Go(16),this._worldViewProjectionMatrix=pe.Zero(),this._globalAmbientColor=new Pe(0,0,0),this._cacheHasRenderTargetTextures=!1;const n=this.getScene().getEngine();n.isWebGPU&&!i&&!ct.ForceGLSL&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new Ci(n,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.detailMap=new z_(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new vZ,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ct.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),ct.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 ct.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||ct.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===tt.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==tt.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 n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new K9e(this._eventInfo.defineNames));const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();a._needNormals=Xu(s,e,a,!0,this._maxSimultaneousLights,this._disableLighting),rD(s,a);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Dz(s,a,this.canRenderToMRT&&!l),jJ(s,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(s.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&&ct.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())Is(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&ct.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())Is(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&ct.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())Is(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&ct.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===be.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 be.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case be.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case be.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case be.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case be.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case be.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case be.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case be.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case be.CUBIC_MODE:case be.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&&ct.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())Is(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&ct.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())Is(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&ct.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())Is(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&ct.BumpTextureEnabled){if(this._bumpTexture.isReady())Is(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=s.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&&ct.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&&(ct.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),Tu(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,a,this._applyDecalMapAfterDetailMap),Mu(s,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=a,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),xo(e,a,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let c=!1;if(a.isDirty){const u=a._areLightsDisposed;a.markAsProcessed();const h=new ha;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"),Bl(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=[ee.PositionKind];a.NORMAL&&d.push(ee.NormalKind),a.TANGENT&&d.push(ee.TangentKind);for(let C=1;C<=6;++C)a["UV"+C]&&d.push(`uv${C===1?"":C}`);a.VERTEXCOLOR&&d.push(ee.ColorKind),Ch(d,e,a,h),Do(d,a),Iz(d,e,a),iD(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"],g=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],m=["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=g,this._eventInfo.uniformBuffersNames=m,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),vZ.AddUniforms(p),Gr&&(Gr.PrepareUniforms(p,a),Gr.PrepareSamplers(g,a)),Qo({uniformsNames:p,uniformBuffersNames:m,samplers:g,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),Yo(p);const y={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,m,g,a,d,y));const v=a.toString(),x=t.effect;let b=s.getEngine().createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:m,samplers:g,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([je(()=>Promise.resolve().then(()=>ORt),void 0),je(()=>Promise.resolve().then(()=>PRt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>MRt),void 0),je(()=>Promise.resolve().then(()=>SRt),void 0)]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,b)if(this._onEffectCreatedObservable&&(dae.effect=b,dae.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dae)),this.allowShaderHotSwapping&&x&&!b.isReady()){if(b=x,a.markAsUnprocessed(),c=this.isFrozen,u)return a._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(b,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),n._wasPreviouslyReady=!c,n._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 n=this.getScene(),s=i.materialDefines;if(!s)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,n,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(n,a,i,t.visibility);rc(t,a);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(ct.FresnelEnabled&&s.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 Pe(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))),n.texturesEnabled){if(this._diffuseTexture&&ct.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Ps(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&ct.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Ps(this._ambientTexture,l,"ambient")),this._opacityTexture&&ct.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Ps(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&ct.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&&ct.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Ps(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&ct.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Ps(this._lightmapTexture,l,"lightmap")),this._specularTexture&&ct.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Ps(this._specularTexture,l,"specular")),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&ct.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Ps(this._bumpTexture,l,"bump"),n._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&&ct.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),s.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",ct.EmissiveTextureEnabled?this.emissiveColor:Pe.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),n.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}n.texturesEnabled&&(this._diffuseTexture&&ct.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&ct.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ct.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&ct.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&ct.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ct.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&ct.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&n.getEngine().getCaps().standardDerivatives&&ct.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&ct.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),wo(a,this,n),this.bindEyePosition(a)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(n.lightsEnabled&&!this._disableLighting&&$u(n,t,a,s,this._maxSimultaneousLights),(n.fogEnabled&&t.applyFog&&n.fogMode!==Ut.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(a),ic(n,t,a),s.NUM_MORPH_INFLUENCERS&&Np(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((c=t.bakedVertexAnimationManager)==null||c.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&Xo(s,a,n),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,n,s,a,o,l,c,u,h;t&&((i=this._diffuseTexture)==null||i.dispose(),(n=this._ambientTexture)==null||n.dispose(),(s=this._opacityTexture)==null||s.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 n=ot.Clone(()=>new ct(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return n.name=e,n.id=e,this.stencil.copyTo(n.stencil),this._clonePlugins(n,i),n}static Parse(e,t,i){const n=ot.Parse(()=>new ct(e.name,t),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),tt._ParsePlugins(e,n,t,i),n}static get DiffuseTextureEnabled(){return lt.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){lt.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return lt.DetailTextureEnabled}static set DetailTextureEnabled(e){lt.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return lt.AmbientTextureEnabled}static set AmbientTextureEnabled(e){lt.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return lt.OpacityTextureEnabled}static set OpacityTextureEnabled(e){lt.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return lt.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){lt.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return lt.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){lt.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return lt.SpecularTextureEnabled}static set SpecularTextureEnabled(e){lt.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return lt.BumpTextureEnabled}static set BumpTextureEnabled(e){lt.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return lt.LightmapTextureEnabled}static set LightmapTextureEnabled(e){lt.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return lt.RefractionTextureEnabled}static set RefractionTextureEnabled(e){lt.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return lt.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){lt.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return lt.FresnelEnabled}static set FresnelEnabled(e){lt.FresnelEnabled=e}}ct.ForceGLSL=!1;V([ki("diffuseTexture")],ct.prototype,"_diffuseTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ct.prototype,"diffuseTexture",void 0);V([ki("ambientTexture")],ct.prototype,"_ambientTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"ambientTexture",void 0);V([ki("opacityTexture")],ct.prototype,"_opacityTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ct.prototype,"opacityTexture",void 0);V([ki("reflectionTexture")],ct.prototype,"_reflectionTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"reflectionTexture",void 0);V([ki("emissiveTexture")],ct.prototype,"_emissiveTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"emissiveTexture",void 0);V([ki("specularTexture")],ct.prototype,"_specularTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"specularTexture",void 0);V([ki("bumpTexture")],ct.prototype,"_bumpTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"bumpTexture",void 0);V([ki("lightmapTexture")],ct.prototype,"_lightmapTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"lightmapTexture",void 0);V([ki("refractionTexture")],ct.prototype,"_refractionTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"refractionTexture",void 0);V([qr("ambient")],ct.prototype,"ambientColor",void 0);V([qr("diffuse")],ct.prototype,"diffuseColor",void 0);V([qr("specular")],ct.prototype,"specularColor",void 0);V([qr("emissive")],ct.prototype,"emissiveColor",void 0);V([Q()],ct.prototype,"specularPower",void 0);V([Q("useAlphaFromDiffuseTexture")],ct.prototype,"_useAlphaFromDiffuseTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ct.prototype,"useAlphaFromDiffuseTexture",void 0);V([Q("useEmissiveAsIllumination")],ct.prototype,"_useEmissiveAsIllumination",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useEmissiveAsIllumination",void 0);V([Q("linkEmissiveWithDiffuse")],ct.prototype,"_linkEmissiveWithDiffuse",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"linkEmissiveWithDiffuse",void 0);V([Q("useSpecularOverAlpha")],ct.prototype,"_useSpecularOverAlpha",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useSpecularOverAlpha",void 0);V([Q("useReflectionOverAlpha")],ct.prototype,"_useReflectionOverAlpha",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useReflectionOverAlpha",void 0);V([Q("disableLighting")],ct.prototype,"_disableLighting",void 0);V([Ke("_markAllSubMeshesAsLightsDirty")],ct.prototype,"disableLighting",void 0);V([Q("useObjectSpaceNormalMap")],ct.prototype,"_useObjectSpaceNormalMap",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useObjectSpaceNormalMap",void 0);V([Q("useParallax")],ct.prototype,"_useParallax",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useParallax",void 0);V([Q("useParallaxOcclusion")],ct.prototype,"_useParallaxOcclusion",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useParallaxOcclusion",void 0);V([Q()],ct.prototype,"parallaxScaleBias",void 0);V([Q("roughness")],ct.prototype,"_roughness",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"roughness",void 0);V([Q()],ct.prototype,"indexOfRefraction",void 0);V([Q()],ct.prototype,"invertRefractionY",void 0);V([Q()],ct.prototype,"alphaCutOff",void 0);V([Q("useLightmapAsShadowmap")],ct.prototype,"_useLightmapAsShadowmap",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useLightmapAsShadowmap",void 0);V([Yw("diffuseFresnelParameters")],ct.prototype,"_diffuseFresnelParameters",void 0);V([Ke("_markAllSubMeshesAsFresnelDirty")],ct.prototype,"diffuseFresnelParameters",void 0);V([Yw("opacityFresnelParameters")],ct.prototype,"_opacityFresnelParameters",void 0);V([Ke("_markAllSubMeshesAsFresnelAndMiscDirty")],ct.prototype,"opacityFresnelParameters",void 0);V([Yw("reflectionFresnelParameters")],ct.prototype,"_reflectionFresnelParameters",void 0);V([Ke("_markAllSubMeshesAsFresnelDirty")],ct.prototype,"reflectionFresnelParameters",void 0);V([Yw("refractionFresnelParameters")],ct.prototype,"_refractionFresnelParameters",void 0);V([Ke("_markAllSubMeshesAsFresnelDirty")],ct.prototype,"refractionFresnelParameters",void 0);V([Yw("emissiveFresnelParameters")],ct.prototype,"_emissiveFresnelParameters",void 0);V([Ke("_markAllSubMeshesAsFresnelDirty")],ct.prototype,"emissiveFresnelParameters",void 0);V([Q("useReflectionFresnelFromSpecular")],ct.prototype,"_useReflectionFresnelFromSpecular",void 0);V([Ke("_markAllSubMeshesAsFresnelDirty")],ct.prototype,"useReflectionFresnelFromSpecular",void 0);V([Q("useGlossinessFromSpecularMapAlpha")],ct.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"useGlossinessFromSpecularMapAlpha",void 0);V([Q("maxSimultaneousLights")],ct.prototype,"_maxSimultaneousLights",void 0);V([Ke("_markAllSubMeshesAsLightsDirty")],ct.prototype,"maxSimultaneousLights",void 0);V([Q("invertNormalMapX")],ct.prototype,"_invertNormalMapX",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"invertNormalMapX",void 0);V([Q("invertNormalMapY")],ct.prototype,"_invertNormalMapY",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"invertNormalMapY",void 0);V([Q("twoSidedLighting")],ct.prototype,"_twoSidedLighting",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ct.prototype,"twoSidedLighting",void 0);V([Q("applyDecalMapAfterDetailMap")],ct.prototype,"_applyDecalMapAfterDetailMap",void 0);V([Ke("_markAllSubMeshesAsMiscDirty")],ct.prototype,"applyDecalMapAfterDetailMap",void 0);xe("BABYLON.StandardMaterial",ct);Ut.DefaultMaterialFactory=r=>new ct("default material",r);ir.prototype.createDynamicTexture=function(r,e,t,i){const n=new _n(this,4);return n.baseWidth=r,n.baseHeight=e,t&&(r=this.needPOTTextures?Ld(r,this._caps.maxTextureSize):r,e=this.needPOTTextures?Ld(e,this._caps.maxTextureSize):e),n.width=r,n.height=e,n.isReady=!1,n.generateMipMaps=t,n.samplingMode=i,this.updateTextureSamplingMode(i,n),this._internalTexturesCache.push(n),n};ir.prototype.updateDynamicTexture=function(r,e,t,i=!1,n,s=!1,a=!1){if(!r)return;const o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,r,!0,s);this._unpackFlipY(t===void 0?r.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const u=this._getWebGLTextureType(r.type),h=this._getInternalFormat(n||r.format),d=this._getRGBABufferInternalSizedFormat(r.type,h);o.texImage2D(l,0,d,h,u,e),r.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),n&&(r.format=n),r._dynamicTextureSource=e,r._premulAlpha=i,r.invertY=t||!1,r.isReady=!0};class Ep extends be{constructor(e,t,i=null,n=!1,s=3,a=5,o){super(null,i,!n,o,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=be.CLAMP_ADDRESSMODE,this.wrapV=be.CLAMP_ADDRESSMODE,this._generateMipMaps=n;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(t.width,t.height,n,s)):(this._canvas=l.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,n,s):this._texture=l.createDynamicTexture(t,t,n,s));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,n,s,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=n,t==null){const u=this._context.measureText(e);t=(c.width-u.width)/2}if(i==null){const u=parseInt(n.replace(/\D/g,""));i=c.height/2+u/3.65}this._context.fillStyle=s||"",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 Ep(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()&&ge.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Ep._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 G1e{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,n,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this._createRenderTargetTextureProvider=s,this._rttWrapper=null}}class iee{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new _n(this._engine,0,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new iT(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,n,s,a){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},l=a?new ohe(this._scene,o):new vn("XR renderTargetTexture",o,this._scene),c=l.renderTarget;if(c._samples=l.samples,(i||!n)&&(c._framebuffer=i),n)if(a)c._colorTextureArray=n;else{const u=this._createInternalTexture(o,n);c.setTexture(u,0),l._texture=u}return s&&(a?c._depthStencilTextureArray=s:c._depthStencilTexture=this._createInternalTexture(o,s)),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 W1e extends G1e{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new d3t(t.scene,this)),this.layer=e}}class d3t extends iee{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 n=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/n,e.y=i.y/s,e.width=i.width/n,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,n=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||n!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,n),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=n),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class $z{static GetDefaults(e){const t=new $z;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 H9e{constructor(e,t=$z.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new Ce,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()},()=>{Ie.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 W1e(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 j9e extends G1e{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new $9e(t,this)),this.layer=e}}class $9e extends iee{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 X9e{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 Xz{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 Ce,this.onXRReferenceSpaceChanged=new Ce,this.onXRSessionEnded=new Ce,this.onXRSessionInit=new Ce,this.onXRReferenceSpaceInitialized=new Ce,this.onXRReady=new Ce,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new Ce(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{ge.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 X9e(this):(e=e||$z.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new H9e(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 n;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&&((n=this._baseLayerRTTProvider)==null||n.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return Xz.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 n;if(!(!this.inXRSession||!this._engine)&&(this.currentFrame=i,this.currentTimestamp=t,i)){this.inXRFrameLoop=!0;const s=((n=this._baseLayerRTTProvider)==null?void 0:n.getFramebufferDimensions())||null;this._engine.framebufferDimensionsObject!==s&&(this._engine.framebufferDimensionsObject=s),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=>(ge.Error("XR.requestReferenceSpace failed for the following reason: "),ge.Error(t),ge.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const n=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(n)},i=>{throw ge.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 j9e(e.baseLayer):new W1e(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 n=typeof i>"u"?!0:i;return Promise.resolve(n)}).catch(i=>(ge.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}}Re._GroundMeshParser=(r,e)=>oD.Parse(r,e);class oD extends Re{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(),n=oe.Matrix[5];i.invertToRef(n);const s=oe.Vector3[8];if(O.TransformCoordinatesFromFloatsToRef(e,0,t,n,s),e=s.x,t=s.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 O.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new O(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const n=this.getWorldMatrix(),s=oe.Matrix[5];n.invertToRef(s);const a=oe.Vector3[8];if(O.TransformCoordinatesFromFloatsToRef(e,0,t,s,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 O.TransformNormalFromFloatsToRef(o.x,o.y,o.z,n,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),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[n*this._subdivisionsX+i];let a;return tr.maxHeight){c=!0;const h=r.maxHeight;r.maxHeight=r.minHeight,r.minHeight=h}for(s=0;s<=r.subdivisions;s++)for(a=0;a<=r.subdivisions;a++){const h=new O(a*r.width/r.subdivisions-r.width/2,0,(r.subdivisions-s)*r.height/r.subdivisions-r.height/2),d=(h.x+r.width/2)/r.width*(r.bufferWidth-1)|0,f=(1-(h.z+r.height/2)/r.height)*(r.bufferHeight-1)|0,p=(d+f*r.bufferWidth)*4;let g=r.buffer[p]/255,m=r.buffer[p+1]/255,_=r.buffer[p+2]/255;const y=r.buffer[p+3]/255;c&&(g=1-g,m=1-m,_=1-_);const v=g*o.r+m*o.g+_*o.b;y>=l?h.y=r.minHeight+(r.maxHeight-r.minHeight)*v:h.y=r.minHeight-Ki,r.heightBuffer&&(r.heightBuffer[s*(r.subdivisions+1)+a]=h.y),t.push(h.x,h.y,h.z),i.push(0,0,0),n.push(a/r.subdivisions,1-s/r.subdivisions)}for(s=0;s=r.minHeight,m=t[d*3+1]>=r.minHeight,_=t[f*3+1]>=r.minHeight;g&&m&&_&&(e.push(h),e.push(d),e.push(f)),t[p*3+1]>=r.minHeight&&g&&_&&(e.push(p),e.push(h),e.push(f))}vt.ComputeNormals(t,e,i);const u=new vt;return u.indices=e,u.positions=t,u.normals=i,u.uvs=n,u}function aT(r,e={},t){const i=new oD(r,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,q1(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function ree(r,e,t=null){const i=new Re(r,t);return K1e(e).applyToMesh(i,e.updatable),i}function nee(r,e,t={},i=null){const n=t.width||10,s=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new Pe(.3,.59,.11),u=t.alphaFilter||0,h=t.updatable,d=t.onReady;i=i||ei.LastCreatedScene;const f=new oD(r,i);f._subdivisionsX=a,f._subdivisionsY=a,f._width=n,f._height=s,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 g=(m,_,y)=>{H1e({width:n,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:m,bufferWidth:_,bufferHeight:y,alphaFilter:u,heightBuffer:p}).applyToMesh(f,h),d&&d(f,p),f._setReady(!0)};if(typeof e=="string"){const m=_=>{const y=_.width,v=_.height;if(i.isDisposed)return;const x=i==null?void 0:i.getEngine().resizeImageBitmap(_,y,v);g(x,y,v)};Ie.LoadImage(e,m,t.onError?t.onError:()=>{},i.offlineProvider)}else g(e.data,e.width,e.height);return f}const f3t={CreateGround:aT,CreateGroundFromHeightMap:nee,CreateTiledGround:ree};vt.CreateGround=q1;vt.CreateTiledGround=K1e;vt.CreateGroundFromHeightMap=H1e;Re.CreateGround=(r,e,t,i,n,s)=>aT(r,{width:e,height:t,subdivisions:i,updatable:s},n);Re.CreateTiledGround=(r,e,t,i,n,s,a,o,l)=>ree(r,{xmin:e,zmin:t,xmax:i,zmax:n,subdivisions:s,precision:a,updatable:l},o);Re.CreateGroundFromHeightMap=(r,e,t,i,n,s,a,o,l,c,u)=>nee(r,e,{width:t,height:i,subdivisions:n,minHeight:s,maxHeight:a,updatable:l,onReady:c,alphaFilter:u},o);function see(r){const e=[],t=[],i=[],n=[],s=r.diameter||1,a=r.thickness||.5,o=(r.tessellation||16)|0,l=r.sideOrientation===0?0:r.sideOrientation||vt.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=pe.Translation(s/2,0,0).multiply(pe.RotationY(f));for(let g=0;g<=o;g++){const m=1-g/o,_=g*Math.PI*2/o+Math.PI,y=Math.cos(_),v=Math.sin(_);let x=new O(y,v,0),b=x.scale(a/2);const C=new Ne(d,m);b=O.TransformCoordinates(b,p),x=O.TransformNormal(x,p),t.push(b.x,b.y,b.z),i.push(x.x,x.y,x.z),n.push(C.x,bn?1-C.y:C.y);const A=(h+1)%c,E=(g+1)%c;e.push(h*c+g),e.push(h*c+E),e.push(A*c+g),e.push(h*c+E),e.push(A*c+E),e.push(A*c+g)}}vt._ComputeSides(l,t,e,i,n,r.frontUVs,r.backUVs);const u=new vt;return u.indices=e,u.positions=t,u.normals=i,u.uvs=n,u}function Pg(r,e={},t){const i=new Re(r,t);return e.sideOrientation=Re._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,see(e).applyToMesh(i,e.updatable),i}const p3t={CreateTorus:Pg};vt.CreateTorus=see;Re.CreateTorus=(r,e,t,i,n,s,a)=>Pg(r,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:s},n);class aee{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=aee._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Pg("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new ct("targetMat",e);i.specularColor=Pe.Black(),i.emissiveColor=new Pe(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new wr(O.Zero(),new O(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()}}aee._IdCounter=0;class TMe extends aee{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new wr(O.Zero(),O.Forward())}}class m3t{}class tE{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 Ce,this.onAfterEnteringVRObservable=new Ce,this.onExitingVRObservable=new Ce,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=tE.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new O(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new O(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Pe(.2,.2,1),this._pickedGazeColor=new Pe(0,0,1),this.onNewMeshSelected=new Ce,this.onNewMeshPicked=new Ce,this.onBeforeCameraTeleport=new Ce,this.onAfterCameraTeleport=new Ce,this.onSelectedMeshUnselected=new Ce,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=n=>{n.type!==Zl.POSE_ENABLED&&(n.leftStick&&n.onleftstickchanged(s=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(s,this._cameraGazer),this._checkTeleportBackwards(s,this._cameraGazer))}),n.rightStick&&n.onrightstickchanged(s=>{this._teleportationInitialized&&this._checkRotate(s,this._cameraGazer)}),n.type===Zl.XBOX&&(n.onbuttondown(s=>{this._interactionsEnabled&&s===0&&this._cameraGazer._selectionPointerDown()}),n.onbuttonup(s=>{this._interactionsEnabled&&s===0&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=O.Zero(),this._workingQuaternion=Oe.Identity(),this._workingMatrix=pe.Identity(),ge.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 O(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new ZJ("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 $a&&this._scene.activeCamera.rotation)){const n=this._scene.activeCamera;n.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(n.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(Oe.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z)),this._deviceOrientationCamera.rotation=n.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Xz.IsSessionSupportedAsync("immersive-vr").then(n=>{n?(ge.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(s=>{this.xr=s,this.xrTestDone=!0,this._cameraGazer=new TMe(()=>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 tee("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new TMe(()=>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 s=".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) }";s+=".babylonVRicon.vrdisplaypresenting { display: none; }";const a=document.createElement("style");a.appendChild(document.createTextNode(s)),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=n=>{n.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())},Wt.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new $Be,this._circleEase.setEasingMode(Ja.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(n=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&n.event.pointerType==="mouse"&&(n.type===Wt.POINTERDOWN?this._cameraGazer._selectionPointerDown():n.type===Wt.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){ge.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=Oe.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){ge.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 n=this._scene.getMeshByName(e.floorMeshName);n&&i.push(n)}if(this.xr){i.forEach(n=>{this.xr.teleportation.addFloorMesh(n)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const n=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(n),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(n);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 Gr;t.vignetteColor=new at(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=Oe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,Oe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),O.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new wr(n,this._workingVector),a=this._scene.pickWithRay(s,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 Ep("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),n=e/2,s=e/2,a=200;i.beginPath(),i.arc(n,s,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 ct("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const l=Pg("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const c=new dt("animationInnerCircle","position.y",30,dt.ANIMATIONTYPE_FLOAT,dt.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 _1e;h.setEasingMode(Ja.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 ql))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=Oe.FromRotationMatrix(pe.RotationY(Math.PI/4*this._rotationAngle)),i=new dt("animationRotation","rotationQuaternion",90,dt.ANIMATIONTYPE_QUATERNION,dt.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),n.push({frame:6,value:t}),i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new dt("animationPP","vignetteWeight",90,dt.ANIMATIONTYPE_FLOAT,dt.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const o=new dt("animationPP2","vignetteStretch",90,dt.ANIMATIONTYPE_FLOAT,dt.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 ql))return;this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,n;if(this._teleportationMode==tE.TELEPORTATIONMODE_CONSTANTSPEED){n=t;const d=O.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/d}else n=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const s=new dt("animationCameraTeleportation","position",t,dt.ANIMATIONTYPE_VECTOR3,dt.ANIMATIONLOOPMODE_CONSTANT),a=[{frame:0,value:this.currentVRCamera.position},{frame:n,value:this._workingVector}];s.setKeys(a),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const o=Math.round(n/2),l=new dt("animationPP","vignetteWeight",t,dt.ANIMATIONTYPE_FLOAT,dt.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:o,value:8}),c.push({frame:n,value:0}),l.setKeys(c),this._postProcessMove.animations.push(l);const u=new dt("animationPP2","vignetteStretch",t,dt.ANIMATIONTYPE_FLOAT,dt.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:o,value:10}),h.push({frame:n,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,n,!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"}}tE.TELEPORTATIONMODE_CONSTANTTIME=0;tE.TELEPORTATIONMODE_CONSTANTSPEED=1;const g3t=(r,e,t,i)=>!(r.x>t.x+i||t.x-i>e.x||r.y>t.y+i||t.y-i>e.y||r.z>t.z+i||t.z-i>e.z),PI=function(){const r={root:0,found:!1};return function(e,t,i,n){r.root=0,r.found=!1;const s=t*t-4*e*i;if(s<0)return r;const a=Math.sqrt(s);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,n){const s=O.Distance(this._basePointWorld,e),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+t||!g3t(i,n,this._basePointWorld,this._velocityWorldLength+a))}_testTriangle(e,t,i,n,s,a,o){let l,c=!1;t||(t=[]),t[e]||(t[e]=new Dc(0,0,0,0),t[e].copyFromPoints(i,n,s));const u=t[e];if(!a&&!u.isFrontFacingTo(this._normalizedVelocity,0))return;const h=u.signedDistanceTo(this._basePoint),d=O.Dot(u.normal,this._velocity);if(Yz.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(h)>=1)return;c=!0,l=0}else{l=(-1-h)/d;let g=(1-h)/d;if(l>g){const m=g;g=l,l=m}if(l>1||g<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,n,s,u.normal)&&(f=!0,p=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let g=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let m=2*O.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=PI(g,m,_,p);y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),m=2*O.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=PI(g,m,_,p),y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(s,this._tempVector),m=2*O.Dot(this._velocity,this._tempVector),_=this._tempVector.lengthSquared()-1,y=PI(g,m,_,p),y.found&&(p=y.root,f=!0,this._collisionPoint.copyFrom(s)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let v=this._edge.lengthSquared(),x=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex);if(g=v*-this._velocitySquaredLength+x*x,m=2*(v*O.Dot(this._velocity,this._baseToVertex)-x*b),_=v*(1-this._baseToVertex.lengthSquared())+b*b,y=PI(g,m,_,p),y.found){const C=(x*y.root-b)/v;C>=0&&C<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(C),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),v=this._edge.lengthSquared(),x=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex),g=v*-this._velocitySquaredLength+x*x,m=2*(v*O.Dot(this._velocity,this._baseToVertex)-x*b),_=v*(1-this._baseToVertex.lengthSquared())+b*b,y=PI(g,m,_,p),y.found){const C=(x*y.root-b)/v;C>=0&&C<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(C),n.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),v=this._edge.lengthSquared(),x=O.Dot(this._edge,this._velocity),b=O.Dot(this._edge,this._baseToVertex),g=v*-this._velocitySquaredLength+x*x,m=2*(v*O.Dot(this._velocity,this._baseToVertex)-x*b),_=v*(1-this._baseToVertex.lengthSquared())+b*b,y=PI(g,m,_,p),y.found){const C=(x*y.root-b)/v;C>=0&&C<=1&&(p=y.root,f=!0,this._edge.scaleInPlace(C),s.addToRef(this._edge,this._collisionPoint))}}if(f){const g=p*p*this._velocitySquaredLength;(!this.collisionFound||g=n){s.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 Y9e;const fae={effect:null,subMesh:null};class ua extends Va{constructor(e,t,i,n={},s=!0){super(e,t,s),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 pe,this._cachedWorldViewProjectionMatrix=new pe,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,...n}}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,n)=>(n.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,n)=>(n.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,n)=>(n.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 n=0;ns===e||s.startsWith(i));return n>=0&&this.options.defines.splice(n,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 n=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const b=n?i._drawWrapper:this._drawWrapper;if(b.effect&&b._wasPreviouslyReady&&b._wasPreviouslyUsingInstances===t)return!0}const s=this.getScene(),a=s.getEngine(),o=[],l=[],c=new ha;let u=this._shaderPath,h=this._options.uniforms,d=this._options.uniformBuffers,f=this._options.samplers;a.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),h.indexOf("viewProjection")!==-1&&h.indexOf("viewProjectionR")===-1&&h.push("viewProjectionR"));for(let b=0;b4&&(l.push(ee.MatricesIndicesExtraKind),l.push(ee.MatricesWeightsExtraKind));const b=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),b.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 "+(b.bones.length+1)),h.indexOf("mBones")===-1&&h.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const g=e?e.morphTargetManager:null;if(g){const b=g.supportsUVs&&o.indexOf("#define UV1")!==-1,C=g.supportsTangents&&o.indexOf("#define TANGENT")!==-1,A=g.supportsNormals&&o.indexOf("#define NORMAL")!==-1;p=g.numMaxInfluencers||g.numInfluencers,b&&o.push("#define MORPHTARGETS_UV"),C&&o.push("#define MORPHTARGETS_TANGENT"),A&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),g.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 E=0;E0&&(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 b=e.bakedVertexAnimationManager;b&&b.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")),iD(l,e,o)}for(const b in this._textures)if(!this._textures[b].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Yo(h),x3(this,s,o)),s.fogEnabled&&(e!=null&&e.applyFog)&&s.fogMode!==Ut.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 m=n?i._getDrawWrapper(void 0,!0):this._drawWrapper,_=(m==null?void 0:m.effect)??null,y=(m==null?void 0:m.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),n?i.setEffect(x,v,this._materialContext):m&&m.setEffect(x,v),this._onEffectCreatedObservable&&(fae.effect=x,fae.subMesh=i??(e==null?void 0:e.subMeshes[0])??null,this._onEffectCreatedObservable.notifyObservers(fae))),m._wasPreviouslyUsingInstances=!!t,x!=null&&x.isReady()?(_!==x&&s.resetCachedMaterial(),m._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=this.getScene(),n=t??this.getEffect();n&&(this._options.uniforms.indexOf("world")!==-1&&n.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),n.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),n.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),this._options.uniforms.indexOf("view")!==-1&&n.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var n;this.bind(e,t,(n=i._drawWrapperOverride)==null?void 0:n.effect,i)}bind(e,t,i,n){var h;const s=n&&this._storeEffectOnSubMeshes,a=i??(s?n.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&&Np(t,a);const f=t.bakedVertexAnimationManager;if(f&&f.isEnabled){const p=s?n._drawWrapper:this._drawWrapper;(h=t.bakedVertexAnimationManager)==null||h.bind(a,!!p._wasPreviouslyUsingInstances)}}this._afterBind(t,a,n)}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 n=0;nnew ua(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 n=this._options[i];Array.isArray(n)&&(this._options[i]=n.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 n;for(n in this._textures)this._textures[n].dispose();for(n in this._textureArrays){const s=this._textureArrays[n];for(let a=0;anew ua(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let s;e.stencil&&n.stencil.parse(e.stencil,t,i);for(s in e.textures)n.setTexture(s,be.Parse(e.textures[s],t,i));for(s in e.textureArrays){const a=e.textureArrays[s],o=[];for(let l=0;l(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Pe.FromArray(o));n.setColor3Array(s,a)}for(s in e.colors4)n.setColor4(s,at.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const a=e.colors4Arrays[s].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>at.FromArray(o));n.setColor4Array(s,a)}for(s in e.vectors2)n.setVector2(s,Ne.FromArray(e.vectors2[s]));for(s in e.vectors3)n.setVector3(s,O.FromArray(e.vectors3[s]));for(s in e.vectors4)n.setVector4(s,It.FromArray(e.vectors4[s]));for(s in e.quaternions)n.setQuaternion(s,Oe.FromArray(e.quaternions[s]));for(s in e.matrices)n.setMatrix(s,pe.FromArray(e.matrices[s]));for(s in e.matrixArray)n._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)n.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)n.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)n.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)n.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)n.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)n.setArray4(s,e.quaternionsArrays[s]);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise((s,a)=>{const o=new oa;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=this.Parse(l,i||ei.LastCreatedScene,n);e&&(c.name=e),s(c)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((n,s)=>{const a=new oa;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||ei.LastCreatedScene,i);c.snippetId=e,n(c)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}ua.SnippetUrl="https://snippet.babylonjs.com";ua.CreateFromSnippetAsync=ua.ParseFromSnippetAsync;xe("BABYLON.ShaderMaterial",ua);class _3t{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 vn("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=[],n={attributes:[ee.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([je(()=>Promise.resolve().then(()=>L3t),void 0),je(()=>Promise.resolve().then(()=>Y3t),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>v3t),void 0),je(()=>Promise.resolve().then(()=>O3t),void 0)])}};this._defaultRenderMaterial=new ua("pickingShader",e,"picking",n,!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,n,s,a,o){const l=new Float32Array(4*(e+1));l[0]=n/255,l[1]=s/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 n=new Float32Array(4*e);for(let s=0;s>16,o=(t&65280)>>8,l=(t&255)>>0;i(s,t),n[s*4]=a/255,n[s*4+1]=o/255,n[s*4+2]=l/255,n[s*4+3]=1,t++}return n}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,g)=>{this._thinIdMap[g]={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 g=l.getEngine(),m=new ee(g,p,this._attributeName,!1,!1,4,!0);l.setVerticesBuffer(m,!0)}else this._idColors[l.uniqueId]=Pe.FromInts(u,h,d)}}async pickAsync(e,t,i=!1){if(!this._pickableMeshes||this._pickableMeshes.length===0)return Promise.resolve(null);const n=this._cachedScene,s=n.getEngine(),a=s.getRenderWidth(),o=s.getRenderHeight(),l=1/s._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(s.isWebGPU?256:4)),t=o-t,this._pickingTexture.clearColor=new at(0,0,0,0),this._pickingTexture.onBeforeRender=()=>{s.enableScissor&&s.enableScissor(e,t,1,1)},n.customRenderTargets.push(this._pickingTexture);const c=this._pickingTexture.getSize();if(c.width!==a||c.height!==o){this._createRenderTarget(n,a,o),this._pickingTexture.renderList=[];for(let u=0;u{this._pickingTexture.onAfterRender=async()=>{s.disableScissor&&s.disableScissor(),this._pickingTexture||h();let d=null,f;const p=this._meshRenderingCount>0;if(p){const g=n.customRenderTargets.indexOf(this._pickingTexture);if(g>-1&&n.customRenderTargets.splice(g,1),await this._readTexturePixelsAsync(e,t)){const m=this._readbuffer[0],_=this._readbuffer[1],y=this._readbuffer[2],v=(m<<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 n;return!this._cachedScene||!((n=this._pickingTexture)!=null&&n._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 Q9e="pickingPixelShader",Z9e=`#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 }`;me.ShadersStore[Q9e]=Z9e;const q9e={name:Q9e,shader:Z9e},v3t=Object.freeze(Object.defineProperty({__proto__:null,pickingPixelShader:q9e},Symbol.toStringTag,{value:"Module"})),J9e="bonesDeclaration",eke=`#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 `;me.IncludesShadersStore[J9e]=eke;const tke={name:J9e,shader:eke},y3t=Object.freeze(Object.defineProperty({__proto__:null,bonesDeclaration:tke},Symbol.toStringTag,{value:"Module"})),x3t="bakedVertexAnimationDeclaration",b3t=`#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 `;me.IncludesShadersStore[x3t]=b3t;const ike="morphTargetsVertexGlobalDeclaration",rke=`#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 `;me.IncludesShadersStore[ike]=rke;const nke={name:ike,shader:rke},C3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalDeclaration:nke},Symbol.toStringTag,{value:"Module"})),ske="morphTargetsVertexDeclaration",ake=`#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 `;me.IncludesShadersStore[ske]=ake;const oke={name:ske,shader:ake},A3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexDeclaration:oke},Symbol.toStringTag,{value:"Module"})),S3t="instancesDeclaration",E3t=`#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) || defined(PREPASS_VELOCITY_LINEAR) 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) || defined(PREPASS_VELOCITY_LINEAR) uniform mat4 previousWorld; #endif #endif `;me.IncludesShadersStore[S3t]=E3t;const lke="morphTargetsVertexGlobal",cke=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif `;me.IncludesShadersStore[lke]=cke;const uke={name:lke,shader:cke},T3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobal:uke},Symbol.toStringTag,{value:"Module"})),hke="morphTargetsVertex",dke=`#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 `;me.IncludesShadersStore[hke]=dke;const fke={name:hke,shader:dke},M3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertex:fke},Symbol.toStringTag,{value:"Module"})),R3t="instancesVertex",I3t=`#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1, previousWorld2,previousWorld3); #endif #ifdef THIN_INSTANCES finalWorld=world*finalWorld; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) finalPreviousWorld=previousWorld*finalPreviousWorld; #endif #endif #else mat4 finalWorld=world; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) mat4 finalPreviousWorld=previousWorld; #endif #endif `;me.IncludesShadersStore[R3t]=I3t;const pke="bonesVertex",mke=`#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 `;me.IncludesShadersStore[pke]=mke;const gke={name:pke,shader:mke},P3t=Object.freeze(Object.defineProperty({__proto__:null,bonesVertex:gke},Symbol.toStringTag,{value:"Module"})),w3t="bakedVertexAnimation",D3t=`#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 `;me.IncludesShadersStore[w3t]=D3t;const _ke="pickingVertexShader",vke=`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 }`;me.ShadersStore[_ke]=vke;const yke={name:_ke,shader:vke},O3t=Object.freeze(Object.defineProperty({__proto__:null,pickingVertexShader:yke},Symbol.toStringTag,{value:"Module"})),xke="pickingPixelShader",bke=`#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 }`;me.ShadersStoreWGSL[xke]=bke;const Cke={name:xke,shader:bke},L3t=Object.freeze(Object.defineProperty({__proto__:null,pickingPixelShaderWGSL:Cke},Symbol.toStringTag,{value:"Module"})),Ake="bonesDeclaration",Ske=`#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 `;me.IncludesShadersStoreWGSL[Ake]=Ske;const Eke={name:Ake,shader:Ske},N3t=Object.freeze(Object.defineProperty({__proto__:null,bonesDeclarationWGSL:Eke},Symbol.toStringTag,{value:"Module"})),F3t="bakedVertexAnimationDeclaration",B3t=`#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 `;me.IncludesShadersStoreWGSL[F3t]=B3t;const Tke="morphTargetsVertexGlobalDeclaration",Mke=`#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 `;me.IncludesShadersStoreWGSL[Tke]=Mke;const Rke={name:Tke,shader:Mke},k3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalDeclarationWGSL:Rke},Symbol.toStringTag,{value:"Module"})),Ike="morphTargetsVertexDeclaration",Pke=`#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 `;me.IncludesShadersStoreWGSL[Ike]=Pke;const wke={name:Ike,shader:Pke},U3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexDeclarationWGSL:wke},Symbol.toStringTag,{value:"Module"})),z3t="instancesDeclaration",V3t=`#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) || defined(PREPASS_VELOCITY_LINEAR) 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) || defined(PREPASS_VELOCITY_LINEAR) uniform previousWorld : mat4x4; #endif #endif `;me.IncludesShadersStoreWGSL[z3t]=V3t;const Dke="morphTargetsVertexGlobal",Oke=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif `;me.IncludesShadersStoreWGSL[Dke]=Oke;const Lke={name:Dke,shader:Oke},G3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexGlobalWGSL:Lke},Symbol.toStringTag,{value:"Module"})),Nke="morphTargetsVertex",Fke=`#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 `;me.IncludesShadersStoreWGSL[Nke]=Fke;const Bke={name:Nke,shader:Fke},W3t=Object.freeze(Object.defineProperty({__proto__:null,morphTargetsVertexWGSL:Bke},Symbol.toStringTag,{value:"Module"})),K3t="instancesVertex",H3t=`#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) 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) || defined(PREPASS_VELOCITY_LINEAR) 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) || defined(PREPASS_VELOCITY_LINEAR) var finalPreviousWorld=uniforms.previousWorld; #endif #endif `;me.IncludesShadersStoreWGSL[K3t]=H3t;const kke="bonesVertex",Uke=`#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 `;me.IncludesShadersStoreWGSL[kke]=Uke;const zke={name:kke,shader:Uke},j3t=Object.freeze(Object.defineProperty({__proto__:null,bonesVertexWGSL:zke},Symbol.toStringTag,{value:"Module"})),$3t="bakedVertexAnimation",X3t=`#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 `;me.IncludesShadersStoreWGSL[$3t]=X3t;const Vke="pickingVertexShader",Gke=`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 }`;me.ShadersStoreWGSL[Vke]=Gke;const Wke={name:Vke,shader:Gke},Y3t=Object.freeze(Object.defineProperty({__proto__:null,pickingVertexShaderWGSL:Wke},Symbol.toStringTag,{value:"Module"}));class iE{constructor(e,t,i,n=""){this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new Ce,this.onErrorObservable=new Ce,this.onBindObservable=new Ce,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=n,this._engine=i,this.uniqueId=iE._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=me.GetShadersStore(this._shaderLanguage),this._shaderRepository=me.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=me.GetIncludesShadersStore(this._shaderLanguage);let s;const a=dl()?this._engine.getHostDocument():null;typeof e=="string"?s=e:e.computeSource?s="source:"+e.computeSource:e.computeElement?s=(a==null?void 0:a.getElementById(e.computeElement))||e.computeElement:s=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],g=f[1];(!isNaN(parseInt(g))||!isNaN(parseFloat(g)))&&(c=`const ${p} = ${g}; `+c)}}return c}};this._loadShader(s,"Compute","",l=>{r1e(o),G2t(l,o,c=>{this._rawComputeSourceCode=l,t.processFinalCode&&(c=t.processFinalCode(c));const u=n1e(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,n){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const a=Az(e);n(a);return}if(e.substr(0,7)==="source:"){n(e.substr(7));return}if(e.substr(0,7)==="base64:"){const a=window.atob(e.substr(7));n(a);return}if(this._shaderStore[e+t+"Shader"]){n(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){n(this._shaderStore[e+i+"Shader"]);return}let s;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?s=e:s=this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",n)}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,n=>{if(n&&n.numErrors>0){this._processCompilationErrors(n,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="",ge.Error("Unable to compile compute effect:"),this.defines&&ge.Error(`Defines: `+this.defines),iE.LogShaderCodeOnCompilationError){const n=(i=this._pipelineContext)==null?void 0:i._getComputeShaderCode();n&&(ge.Error("Compute code:"),ge.Error(n))}if(typeof e=="string")this._compilationError=e,ge.Error("Error: "+this._compilationError);else for(const n of e.messages){let s="";n.line!==void 0&&(s+="Line "+n.line+", "),n.offset!==void 0&&(s+="Offset "+n.offset+", "),n.length!==void 0&&(s+="Length "+n.length+", "),s+=n.type+": "+n.text,this._compilationError&&(this._compilationError+=` `),this._compilationError+=s,ge.Error(s)}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){me.GetShadersStore(1)[`${e}ComputeShader`]=t}}iE._UniqueIdSeed=0;iE.LogShaderCodeOnCompilationError=!0;class j1e{constructor(){this._gpuTimeInFrameId=-1,this.counter=new zo}_addDuration(e,t){e{const a=()=>{this.dispatch(e,t,i)?s():setTimeout(a,n)};a()})}serialize(){const e=ot.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],n=i.object;switch(i.type){case 0:case 4:case 1:{const s=n.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}}}return e}static Parse(e,t,i){const n=ot.Parse(()=>new cg(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const s in e.textures){const a=e.bindings[s],o=be.Parse(e.textures[s],t,i);a.type===0?n.setTexture(s,o):a.type===4?n.setTexture(s,o,!1):n.setStorageTexture(s,o)}return n}static _BufferIsDataBuffer(e){return e.underlyingResource!==void 0}}V([Q()],cg.prototype,"name",void 0);V([Q()],cg.prototype,"fastMode",void 0);xe("BABYLON.ComputeShader",cg);class Q3t{constructor(e){this._engine=e}async _initializePlatform(){if(!this._platform)if(this._engine.getCaps().supportComputeShaders){const e=await je(()=>Promise.resolve().then(()=>n4t),void 0);this._platform=new e.ComputeShaderBoundingHelper(this._engine)}else if(this._engine.getCaps().supportTransformFeedbacks){const e=await je(()=>Promise.resolve().then(()=>t4t),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 Z3t="gpuTransformVertexShader",q3t=`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;}`;me.ShadersStore[Z3t]=q3t;const J3t="gpuTransformPixelShader",e4t=`#version 300 es void main() {discard;} `;me.ShadersStore[J3t]=e4t;class wv{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(ee.MatricesIndicesExtraKind),u.push(ee.MatricesWeightsExtraKind));const g=n.skeleton;l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),g.isUsingTextureForMatrices?(l.push("#define BONETEXTURE"),c.indexOf("boneTextureWidth")===-1&&c.push("boneTextureWidth"),h.indexOf("boneSampler")===-1&&h.push("boneSampler")):(l.push("#define BonesPerMesh "+(g.bones.length+1)),c.indexOf("mBones")===-1&&c.push("mBones"))}else l.push("#define NUM_BONE_INFLUENCERS 0");const d=n?n.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 g=0;g0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}const f=n.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"),iD(u,n,l));const p=l.join(` `);if(this._effects[p])a=this._effects[p];else{const g={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",g,this._engine),this._effects[p]=a}this._compute(n,a)}this._engine.getCaps().parallelShaderCompile=t}_compute(e,t){var c;const i=this._engine;let n;const s=e.getTotalVertices();if(this._buffers[e.uniqueId])n=this._buffers[e.uniqueId];else{const u=new Float32Array(s*3);n=new fl(e.getEngine(),u,!0,3),this._buffers[e.uniqueId]=n}t.getEngine().enableEffect(t),e._bindDirect(t,null,!0),rc(e,t);const a=e.morphTargetManager;a&&a.numInfluencers>0&&Np(e,t);const o=e.bakedVertexAnimationManager;o&&o.isEnabled&&((c=e.bakedVertexAnimationManager)==null||c.bind(t,!1));const l=n.getData();if(i.bindTransformFeedbackBuffer(n.getBuffer()),i.setRasterizerState(!1),i.beginTransformFeedback(!0),i.drawArraysType(2,0,s),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,s);wv._Min.copyFrom(u.minimum).minimizeInPlace(h.minimum),wv._Max.copyFrom(u.maximum).maximizeInPlace(h.maximum),e._refreshBoundingInfoDirect({minimum:wv._Min,maximum:wv._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}}wv._Min=new O;wv._Max=new O;const t4t=Object.freeze(Object.defineProperty({__proto__:null,TransformFeedbackBoundingHelper:wv},Symbol.toStringTag,{value:"Module"})),i4t="boundingInfoComputeShader",r4t=`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);} `;me.ShadersStoreWGSL[i4t]=r4t;class Kke{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 n;const s=e.join(` `);if(this._computeShadersCache[s])n=this._computeShadersCache[s];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}),n=new cg(`boundingInfoCompute${t?"_bones":""}${i?"_morphs":""}`,this._engine,"boundingInfo",{bindingsMapping:a,defines:e}),this._computeShadersCache[s]=n}return n}_getUBO(){if(this._uboIndex>=this._ubos.length){const e=new Ci(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,n,s,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 Q9(this._engine,Float32Array.BYTES_PER_ELEMENT*l*n),o.update(u),a[t.uniqueId]=o}e.setStorageBuffer(s,o)}_prepareStorage(e,t,i,n,s,a){let o;n[i]?o=n[i]:(o=new Q9(this._engine,Float32Array.BYTES_PER_ELEMENT*s),n[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 n=()=>{const s=this._uniqueComputeShaders.keys();for(let a=s.next();a.done!==!0;a=s.next())if(!a.value.isReady()){setTimeout(n,10);return}i()};n()})}processMeshList(){if(this._processedMeshes.length===0)return;this._uboIndex=0;const e=8*this._processedMeshes.length,t=new Float32Array(e),i=new Q9(this._engine,Float32Array.BYTES_PER_ELEMENT*e);this._resultBuffers.push(i);for(let n=0;n0,h=u?l:o;if(this._extractDataAndLink(h,s,ee.PositionKind,3,"positionBuffer",this._positionBuffers),s&&s.useBones&&s.computeBonesUsingShaders&&s.skeleton&&s.skeleton.useTextureToStoreBoneMatrices){this._extractDataAndLink(h,s,ee.MatricesIndicesKind,4,"indexBuffer",this._indexBuffers),this._extractDataAndLink(h,s,ee.MatricesWeightsKind,4,"weightBuffer",this._weightBuffers);const f=s.skeleton.getTransformMatrixTexture(s);h.setTexture("boneSampler",f,!1),s.numBoneInfluencers>4&&(this._extractDataAndLink(h,s,ee.MatricesIndicesExtraKind,4,"indexExtraBuffer",this._indexExtraBuffers),this._extractDataAndLink(h,s,ee.MatricesWeightsExtraKind,4,"weightExtraBuffer",this._weightExtraBuffers))}const d=this._getUBO();if(u){const f=c._targetStoreTexture;h.setTexture("morphTargets",f,!1),this._prepareStorage(h,"morphTargetInfluences",s.uniqueId,this._morphTargetInfluenceBuffers,c.numInfluencers,c.influences),this._prepareStorage(h,"morphTargetTextureIndices",s.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&&(s.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 n4t=Object.freeze(Object.defineProperty({__proto__:null,ComputeShaderBoundingHelper:Kke},Symbol.toStringTag,{value:"Module"}));class Qk{constructor(e,t,i,n,s,a){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=n,this._maxDepth=s,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=r.getBoundingInfo();!r.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(r)};rE.CreationFuncForSubMeshes=(r,e)=>{r.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(r)};Ut.prototype.createOrUpdateSelectionOctree=function(r=64,e=2){let t=this._getComponent(bt.NAME_OCTREE);t||(t=new $1e(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new rE(rE.CreationFuncForMeshes,r,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(Ut.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});vr.prototype.createOrUpdateSubmeshesOctree=function(r=64,e=2){const t=this.getScene();let i=t._getComponent(bt.NAME_OCTREE);i||(i=new $1e(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new rE(rE.CreationFuncForSubMeshes,r,e)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class $1e{constructor(e){this.name=bt.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new wr(O.Zero(),new O(1,1,1)),e=e||ei.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?(wr.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 oee(r){const e=r.height||2;let t=r.diameterTop===0?0:r.diameterTop||r.diameter||1,i=r.diameterBottom===0?0:r.diameterBottom||r.diameter||1;t=t||1e-5,i=i||1e-5;const n=(r.tessellation||24)|0,s=(r.subdivisions||1)|0,a=!!r.hasRings,o=!!r.enclose,l=r.cap===0?0:r.cap||Re.CAP_ALL,c=r.arc&&(r.arc<=0||r.arc>1)?1:r.arc||1,u=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,h=r.faceUV||new Array(3),d=r.faceColors,f=c!==1&&o?2:0,p=a?s:1,g=2+(1+f)*p;let m;for(m=0;m{const ue=ce?t/2:i/2;if(ue===0)return;let N,F,X;const J=ce?h[g-1]:h[0];let ae=null;d&&(ae=ce?d[g-1]:d[0]);const ne=y.length/3,he=ce?e/2:-e/2,fe=new O(0,he,0);y.push(fe.x,fe.y,fe.z),v.push(0,ce?1:-1,0);const ye=J.y+(J.w-J.y)*.5;x.push(J.x+(J.z-J.x)*.5,bn?1-ye:ye),ae&&b.push(ae.r,ae.g,ae.b,ae.a);const Se=new Ne(.5,.5);for(X=0;X<=n;X++){N=Math.PI*2*X*c/n;const De=Math.cos(-N),ze=Math.sin(-N);F=new O(De*ue,he,ze*ue);const Le=new Ne(De*Se.x+.5,ze*Se.y+.5);y.push(F.x,F.y,F.z),v.push(0,ce?1:-1,0);const Je=J.y+(J.w-J.y)*Le.y;x.push(J.x+(J.z-J.x)*Le.x,bn?1-Je:Je),ae&&b.push(ae.r,ae.g,ae.b,ae.a)}for(X=0;X((a===void 0||!(a instanceof Ut))&&(a!==void 0&&(l=o||Re.DEFAULTSIDE,o=a),a=s,s=1),zu(r,{height:e,diameterTop:t,diameterBottom:i,tessellation:n,subdivisions:s,sideOrientation:l,updatable:o},a));Dn.AddNodeConstructor("Light_Type_3",(r,e)=>()=>new Tp(r,O.Zero(),e));class Tp extends Dr{constructor(e,t,i){super(e,i),this.groundColor=new Pe(0,0,0),this.direction=t||O.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=O.Normalize(e.subtract(O.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=O.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=O.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=pe.Identity()),this._worldMatrix}getTypeID(){return Dr.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}V([qr()],Tp.prototype,"groundColor",void 0);V([ta()],Tp.prototype,"direction",void 0);xe("BABYLON.HemisphericLight",Tp);class Tn{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 Tp("shared gizmo light",new O(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Pe.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return Tn._DefaultUtilityLayer==null?Tn._CreateDefaultUtilityLayerFromScene(ei.LastCreatedScene):Tn._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Tn._DefaultUtilityLayer=new Tn(e),Tn._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Tn._DefaultUtilityLayer=null}),Tn._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return Tn._DefaultKeepDepthUtilityLayer==null&&(Tn._DefaultKeepDepthUtilityLayer=new Tn(ei.LastCreatedScene),Tn._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Tn._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Tn._DefaultKeepDepthUtilityLayer=null})),Tn._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 Ce,this.utilityLayerScene=new Ut(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!==Wt.POINTERMOVE&&i.type!==Wt.POINTERUP&&i.type!==Wt.POINTERDOWN&&i.type!==Wt.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const n=i.event;if(e.isPointerCaptured(n.pointerId)){this._pointerCaptures[n.pointerId]=!1;return}const s=o=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?l=i.nearInteractionPickingInfo:l=new wl;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=s(this.utilityLayerScene);if(!i.ray&&a&&(i.ray=a.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=Wt.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ap(i.type,i.event,a),i.type),i.type===Wt.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)a&&a.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ap(i.type,i.event,a),i.type),i.skipOnPointerObservable=!0);else{const o=s(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===Wt.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===Wt.POINTERMOVE||i.type===Wt.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===Wt.POINTERMOVE||i.type===Wt.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,a,l))),i.type===Wt.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 ap(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()}}Tn._DefaultUtilityLayer=null;Tn._DefaultKeepDepthUtilityLayer=null;var uhe;(function(r){r[r.Origin=0]="Origin",r[r.Pivot=1]="Pivot"})(uhe||(uhe={}));var hhe;(function(r){r[r.World=0]="World",r[r.Local=1]="Local"})(hhe||(hhe={}));class Aa{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=Tn.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=pe.RotationY(Math.PI),this._rootMesh=new Re("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=Oe.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 O(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,Aa.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,oe.Vector3[0]);let n=this.scaleRatio;if(t.mode==di.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){const s=t.orthoTop-t.orthoBottom;n*=s}}else{const s=t.getScene().useRightHandedSystem?O.RightHandedForwardReadOnly:O.LeftHandedForwardReadOnly,a=t.getDirection(s);n*=O.Dot(oe.Vector3[0],a)}this._rootMesh.scaling.setAll(n),e._getWorldMatrixDeterminant()<0&&!Aa.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(),oe.Matrix[0]),oe.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix()){e.getPivotMatrix().invertToRef(oe.Matrix[5]),oe.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 s=oe.Matrix[1];e.parent._worldMatrix.invertToRef(s),this._attachedNode._worldMatrix.multiplyToRef(s,oe.Matrix[0]),t=oe.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,oe.Matrix[1]),i=oe.Matrix[1]):i=t,i.decompose(oe.Vector3[1],oe.Quaternion[0],oe.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 s=this._attachedNode;s.rotation=oe.Quaternion[0].toEulerAngles(),s.rotationQuaternion&&(s.rotationQuaternion.copyFrom(oe.Quaternion[0]),s.rotationQuaternion.normalize())}e.position.copyFrom(oe.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=oe.Matrix[0],i=oe.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const n=oe.Matrix[4];if(this._handlePivotMatrixInverse(e,i,n),n.decompose(oe.Vector3[0],oe.Quaternion[0],e.position,Aa.PreserveScaling?e:void 0,Aa.UseAbsoluteScaling),oe.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const s=oe.Quaternion[1];Oe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,s);const a=oe.Matrix[2];pe.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,a);const o=oe.Matrix[2];s.toRotationMatrix(o);const l=e.getPivotMatrix(),c=oe.Matrix[3];l.invertToRef(c),l.multiplyToRef(a,oe.Matrix[4]),oe.Matrix[4].multiplyToRef(o,oe.Matrix[5]),oe.Matrix[5].multiplyToRef(c,oe.Matrix[6]),oe.Matrix[6].getTranslationToRef(oe.Vector3[1]),e.position.subtractInPlace(oe.Vector3[1])}}else{const t=oe.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(oe.Vector3[0],oe.Quaternion[0],e.position,Aa.PreserveScaling?e:void 0,Aa.UseAbsoluteScaling)}oe.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(oe.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(oe.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=oe.Quaternion[0].toEulerAngles())}else if(this._attachedNode.getClassName()==="Bone"){const e=this._attachedNode,t=e.getParent();if(t){const i=oe.Matrix[0],n=oe.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,n),e.getLocalMatrix().copyFrom(n)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===Dr.LIGHTTYPEID_DIRECTIONALLIGHT||t===Dr.LIGHTTYPEID_SPOTLIGHT||t===Dr.LIGHTTYPEID_POINTLIGHT){const i=e.parent;if(i){const n=oe.Matrix[0],s=oe.Matrix[1];i.getWorldMatrix().invertToRef(n),e.getWorldMatrix().multiplyToRef(n,s),s.decompose(void 0,oe.Quaternion[0],oe.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,oe.Quaternion[0],oe.Vector3[0]);e.position=new O(oe.Vector3[0].x,oe.Vector3[0].y,oe.Vector3[0].z),e.direction&&(e.direction=new O(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(s=>{var a,o;if(s.pickInfo){if(s.type===Wt.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=s==null?void 0:s.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(s.type===Wt.POINTERDOWN&&t.has((a=s.pickInfo.pickedMesh)==null?void 0:a.parent)){i=!0;const l=t.get((o=s.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=s==null?void 0:s.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)})})}s.type===Wt.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)}}Aa.PreserveScaling=!1;Aa.UseAbsoluteScaling=!0;class hp extends Aa{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,n=!1){const s=new Yt("arrow",e),a=zu("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=zu("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return a.parent=s,a.material=t,a.rotation.x=Math.PI/2,a.position.z+=.3,o.parent=s,o.material=t,o.position.z+=.275/2,o.rotation.x=Math.PI/2,n&&(o.visibility=0,a.visibility=0),s}static _CreateArrowInstance(e,t){const i=new Yt("arrow",e);for(const n of t.getChildMeshes()){const s=n.createInstance(n.name);s.parent=i}return i}constructor(e,t=Pe.Gray(),i=Tn.DefaultUtilityLayer,n=null,s=1,a=Pe.Yellow(),o=Pe.Gray()){var p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ce,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=n,this._coloredMaterial=new ct("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Pe(.1,.1,.1)),this._hoverMaterial=new ct("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new ct("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const l=hp._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s),c=hp._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s+4,!0);this._gizmoMesh=new Re("",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 Kl({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add(g=>{if(this.attachedNode){let m=!1;if(this.snapDistance==0)this.attachedNode.getWorldMatrix().getTranslationToRef(oe.Vector3[2]),oe.Vector3[2].addInPlace(g.delta),this.dragBehavior.validateDrag(oe.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(g.delta.x,g.delta.y,g.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(g.delta.x,g.delta.y,g.delta.z),this.attachedNode.updateCache(),m=!0);else if(u+=g.dragDistance,Math.abs(u)>this.snapDistance){const _=Math.floor(Math.abs(u)/this.snapDistance);u=u%this.snapDistance,g.delta.normalizeToRef(oe.Vector3[1]),oe.Vector3[1].scaleInPlace(this.snapDistance*_),this.attachedNode.getWorldMatrix().getTranslationToRef(oe.Vector3[2]),oe.Vector3[2].addInPlace(oe.Vector3[1]),this.dragBehavior.validateDrag(oe.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(oe.Vector3[1].x,oe.Vector3[1].y,oe.Vector3[1].z),this.attachedNode.updateCache(),h.snapDistance=this.snapDistance*_*Math.sign(u),this.onSnapObservable.notifyObservers(h),m=!0)}m&&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(g=>{var m;if(!this._customMeshSet&&(this._isHovered=f.colliderMeshes.indexOf((m=g==null?void 0:g.pickInfo)==null?void 0:m.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(g=>{this._setGizmoMeshMaterial(f.gizmoMeshes,g?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 Dv{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,n,s,a,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||ei.LastCreatedScene,!!e){if(!n){const l=new ct("xAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Pe.Red().scale(.5),n=hp._CreateArrow(e,l,o)}if(!s){const l=new ct("yAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Pe.Green().scale(.5),s=hp._CreateArrow(e,l,o)}if(!a){const l=new ct("zAxisMaterial",e);l.disableLighting=!0,l.emissiveColor=Pe.Blue().scale(.5),a=hp._CreateArrow(e,l,o)}this._xAxis=n,this._yAxis=s,this._zAxis=a,this.scaleLines=t,i!=null&&(Dv._SetRenderingGroupId(this._xAxis,i),Dv._SetRenderingGroupId(this._yAxis,i),Dv._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new O,O.Right(),O.Up(),O.Forward())}}update(e,t,i,n){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(n)}createInstance(){const e=hp._CreateArrowInstance(this.scene,this._xAxis),t=hp._CreateArrowInstance(this.scene,this._yAxis),i=hp._CreateArrowInstance(this.scene,this._zAxis),n=new Dv(this.scene,this.scaleLines,null,e,t,i);return n._instanced=!0,n}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 a4t extends Dv{constructor(e,t,i,n=1){super(e,n),this.pos=O.Zero(),this.xaxis=O.Zero(),this.yaxis=O.Zero(),this.zaxis=O.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(go.X,this.mesh,this.xaxis),e.getDirectionToRef(go.Y,this.mesh,this.yaxis),e.getDirectionToRef(go.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(Ut.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new nE(this)),this._debugLayer},enumerable:!0,configurable:!0});var dhe;(function(r){r[r.Properties=0]="Properties",r[r.Debug=1]="Debug",r[r.Statistics=2]="Statistics",r[r.Tools=3]="Tools",r[r.Settings=4]="Settings"})(dhe||(dhe={}));class nE{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new Ce),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new Ce),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||ei.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={...nE.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:nE.InspectorURL;Ie.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}nE.InspectorURL=`${Ie._DefaultCdnUrl}/v${Qe.Version}/inspector/babylon.inspector.bundle.js`;nE.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function lee(r){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],n=[];let s=[];const a=r.width||r.size||1,o=r.height||r.size||1,l=r.depth||r.size||1,c=r.wrap||!1;let u=r.topBaseAt===void 0?1:r.topBaseAt,h=r.bottomBaseAt===void 0?0:r.bottomBaseAt;u=(u+4)%4,h=(h+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let p=d[u],g=f[h],m=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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],m=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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 A=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],E=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const P=[17,18,19,16],w=[22,23,20,21];for(;p>0;)A.unshift(A.pop()),P.unshift(P.pop()),p--;for(;g>0;)E.unshift(E.pop()),w.unshift(w.pop()),g--;A=A.flat(),E=E.flat(),m=m.concat(A).concat(E),t.push(P[0],P[2],P[3],P[0],P[1],P[2]),t.push(w[0],w[2],w[3],w[0],w[1],w[2])}const _=[a/2,o/2,l/2];s=m.reduce((A,E,P)=>A.concat(E*_[P%3]),[]);const y=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,v=r.faceUV||new Array(6),x=r.faceColors,b=[];for(let A=0;A<6;A++)v[A]===void 0&&(v[A]=new It(0,0,1,1)),x&&x[A]===void 0&&(x[A]=new at(1,1,1,1));for(let A=0;A<6;A++)if(n.push(v[A].z,bn?1-v[A].w:v[A].w),n.push(v[A].x,bn?1-v[A].w:v[A].w),n.push(v[A].x,bn?1-v[A].y:v[A].y),n.push(v[A].z,bn?1-v[A].y:v[A].y),x)for(let E=0;E<4;E++)b.push(x[A].r,x[A].g,x[A].b,x[A].a);vt._ComputeSides(y,s,t,i,n,r.frontUVs,r.backUVs);const C=new vt;if(C.indices=t,C.positions=s,C.normals=i,C.uvs=n,x){const A=y===vt.DOUBLESIDE?b.concat(b):b;C.colors=A}return C}function Hke(r){const e=r.width||r.size||1,t=r.height||r.size||1,i=r.depth||r.size||1,n=(r.widthSegments||r.segments||1)|0,s=(r.heightSegments||r.segments||1)|0,a=(r.depthSegments||r.segments||1)|0,o=new pe,l=new pe,c=new pe,u=q1({width:e,height:i,subdivisionsX:n,subdivisionsY:a});pe.TranslationToRef(0,-t/2,0,l),pe.RotationZToRef(Math.PI,o),o.multiplyToRef(l,c),u.transform(c);const h=q1({width:e,height:i,subdivisionsX:n,subdivisionsY:a});pe.TranslationToRef(0,t/2,0,c),h.transform(c);const d=q1({width:t,height:i,subdivisionsX:s,subdivisionsY:a});pe.TranslationToRef(-e/2,0,0,l),pe.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,c),d.transform(c);const f=q1({width:t,height:i,subdivisionsX:s,subdivisionsY:a});pe.TranslationToRef(e/2,0,0,l),pe.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,c),f.transform(c);const p=q1({width:e,height:t,subdivisionsX:n,subdivisionsY:s});pe.TranslationToRef(0,0,-i/2,l),pe.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,c),p.transform(c);const g=q1({width:e,height:t,subdivisionsX:n,subdivisionsY:s});return pe.TranslationToRef(0,0,i/2,l),pe.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,c),g.transform(c),u.merge([h,f,d,p,g],!0),u}function jh(r,e={},t=null){const i=new Re(r,t);return e.sideOrientation=Re._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,lee(e).applyToMesh(i,e.updatable),i}const o4t={CreateBox:jh};vt.CreateBox=lee;Re.CreateBox=(r,e,t=null,i,n)=>jh(r,{size:e,sideOrientation:n,updatable:i},t);function cee(r){const e=(r.segments||32)|0,t=r.diameterX||r.diameter||1,i=r.diameterY||r.diameter||1,n=r.diameterZ||r.diameter||1,s=r.arc&&(r.arc<=0||r.arc>1)?1:r.arc||1,a=r.slice&&r.slice<=0?1:r.slice||1,o=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,l=!!r.dedupTopBottomIndices,c=new O(t/2,i/2,n/2),u=2+e,h=2*u,d=[],f=[],p=[],g=[];for(let _=0;_<=u;_++){const y=_/u,v=y*Math.PI*a;for(let x=0;x<=h;x++){const b=x/h,C=b*Math.PI*2*s,A=pe.RotationZ(-v),E=pe.RotationY(C),P=O.TransformCoordinates(O.Up(),A),w=O.TransformCoordinates(P,E),M=w.multiply(c),R=w.divide(c).normalize();f.push(M.x,M.y,M.z),p.push(R.x,R.y,R.z),g.push(b,bn?1-y:y)}if(_>0){const x=f.length/3;for(let b=x-2*(h+1);b+h+21&&(d.push(b),d.push(b+1),d.push(b+h+1)),(_bu(r,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:s,updatable:n},i);class cs{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)}}cs.DistanceJoint=0;cs.HingeJoint=1;cs.BallAndSocketJoint=2;cs.WheelJoint=3;cs.SliderJoint=4;cs.PrismaticJoint=5;cs.UniversalJoint=6;cs.Hinge2Joint=cs.WheelJoint;cs.PointToPointJoint=8;cs.SpringJoint=9;cs.LockJoint=10;class c4t extends cs{constructor(e){super(cs.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class X1e extends cs{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 u4t extends X1e{constructor(e){super(cs.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class h4t extends X1e{constructor(e){super(cs.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)}}Re._PhysicsImpostorParser=function(r,e,t){return new Gi(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},r)};class Gi{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},n){if(this.object=e,this.type=t,this._options=i,this._scene=n,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=O.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new Oe,this._tmpQuat2=new Oe,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 Oe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(s=>{s(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(s=>{s(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,Gi._TmpVecs[0]),this.object.translate(Gi._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=s=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const a=this._physicsEngine.getImpostorWithPhysicsBody(s.body);a&&(this.onCollideEvent&&this.onCollideEvent(this,a),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(a)!==-1).forEach(o=>{o.callback(this,a,s.point,s.distance,s.impulse,s.normal)}))},!this.object){ge.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&ge.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=Oe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new Oe),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&&ge.Warn("You must affect impostors to children before affecting impostor to parent.")):ge.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 vr?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=Gi.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}else return Gi.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):O.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):O.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):ge.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):ge.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 n=-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&&(n=o),l}return!1})?this._onPhysicsCollideCallbacks.splice(n,1):ge.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):Oe.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 n=new cs(t,i);return this.addJoint(e,n),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,n,s){if(!this._physicsEngine)return this;const a=this._physicsEngine.getPhysicsPlugin();return a.appendAnchor?(this._physicsEngine&&a.appendAnchor(this,e,t,i,n,s),this):this}addHook(e,t,i,n){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,n),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 Gi(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 Oe),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,n,s){const a=Gi._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const l=Gi._TmpQuat;o.rotationQuaternion.multiplyToRef(s,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),n==null&&(n=i.length()),a.x*=n,a.y*=n,a.z*=n),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,n,s,a){const o=this.object;if(o.rotationQuaternion)if(s){const u=Gi._TmpQuat;e.getRotationQuaternionToRef(1,t,u),u.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const l=Gi._TmpVecs[0],c=Gi._TmpVecs[1];a||(a=Gi._TmpVecs[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,c),e.getAbsolutePositionToRef(t,l),n==null&&i&&(n=i.length()),n!=null&&(l.x+=c.x*n,l.y+=c.y*n,l.z+=c.z*n),o.setAbsolutePosition(l)}}Gi.DEFAULT_OBJECT_SIZE=new O(1,1,1);Gi.IDENTITY_QUATERNION=Oe.Identity();Gi._TmpVecs=Qh(3,O.Zero);Gi._TmpQuat=Oe.Identity();Gi.NoImpostor=0;Gi.SphereImpostor=1;Gi.BoxImpostor=2;Gi.PlaneImpostor=3;Gi.MeshImpostor=4;Gi.CapsuleImpostor=6;Gi.CylinderImpostor=7;Gi.ParticleImpostor=8;Gi.HeightmapImpostor=9;Gi.ConvexHullImpostor=10;Gi.CustomImpostor=100;Gi.RopeImpostor=101;Gi.ClothImpostor=102;Gi.SoftbodyImpostor=103;function uee(r={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(r.subdivisions?r.subdivisions:2,1)|0,t=Math.max(r.tessellation?r.tessellation:16,3)|0,i=Math.max(r.height?r.height:1,0),n=Math.max(r.radius?r.radius:.25,0),s=Math.max(r.capSubdivisions?r.capSubdivisions:6,1)|0,a=t,o=e,l=Math.max(r.radiusTop?r.radiusTop:n,0),c=Math.max(r.radiusBottom?r.radiusBottom:n,0),u=i-(l+c),h=0,d=2*Math.PI,f=Math.max(r.topCapSubdivisions?r.topCapSubdivisions:s,1),p=Math.max(r.bottomCapSubdivisions?r.bottomCapSubdivisions:s,1),g=Math.acos((c-l)/i);let m=[];const _=[],y=[],v=[];let x=0;const b=[],C=u*.5,A=Math.PI*.5;let E,P;const w=O.Zero(),M=O.Zero(),R=Math.cos(g),I=Math.sin(g),D=new Ne(l*I,C+l*R).subtract(new Ne(c*I,-C+c*R)).length(),k=l*g+D+c*(A-g);let z=0;for(P=0;P<=f;P++){const j=[],B=A-g*(P/f);z+=l*g/f;const G=Math.cos(B),Y=Math.sin(B),Z=G*l;for(E=0;E<=a;E++){const te=E/a,le=te*d+h,ce=Math.sin(le),ue=Math.cos(le);M.x=Z*ce,M.y=C+Y*l,M.z=Z*ue,_.push(M.x,M.y,M.z),w.set(G*ce,Y,G*ue),y.push(w.x,w.y,w.z),v.push(te,bn?z/k:1-z/k),j.push(x),x++}b.push(j)}const W=i-l-c+R*l-R*c,K=I*(c-l)/W;for(P=1;P<=o;P++){const j=[];z+=D/o;const B=I*(P*(c-l)/o+l);for(E=0;E<=a;E++){const G=E/a,Y=G*d+h,Z=Math.sin(Y),te=Math.cos(Y);M.x=B*Z,M.y=C+R*l-P*W/o,M.z=B*te,_.push(M.x,M.y,M.z),w.set(Z,K,te).normalize(),y.push(w.x,w.y,w.z),v.push(G,bn?z/k:1-z/k),j.push(x),x++}b.push(j)}for(P=1;P<=p;P++){const j=[],B=A-g-(Math.PI-g)*(P/p);z+=c*g/p;const G=Math.cos(B),Y=Math.sin(B),Z=G*c;for(E=0;E<=a;E++){const te=E/a,le=te*d+h,ce=Math.sin(le),ue=Math.cos(le);M.x=Z*ce,M.y=-C+Y*c,M.z=Z*ue,_.push(M.x,M.y,M.z),w.set(G*ce,Y,G*ue),y.push(w.x,w.y,w.z),v.push(te,bn?z/k:1-z/k),j.push(x),x++}b.push(j)}for(E=0;EQz(r,e,t);vt.CreateCapsule=uee;function Y1e(r){let e=r.pathArray;const t=r.closeArray||!1,i=r.closePath||!1,n=r.invertUV||!1,s=Math.floor(e[0].length/2);let a=r.offset||s;a=a>s?s:Math.floor(a);const o=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,l=r.uvs,c=r.colors,u=[],h=[],d=[],f=[],p=[],g=[],m=[],_=[];let y;const v=[],x=[];let b,C,A;if(e.length<2){const J=[],ae=[];for(C=0;C0&&(I=M[A].subtract(M[A-1]).length(),D=I+m[b],p[b].push(D),m[b]=D),A++;i&&(A--,u.push(M[0].x,M[0].y,M[0].z),I=M[A].subtract(M[0]).length(),D=I+m[b],p[b].push(D),m[b]=D),v[b]=R+P,x[b]=E,E+=R+P}let k,z,W=null,K=null;for(C=0;C{let p=i[0].length;const g=o;let m=0;const _=g._originalBuilderSideOrientation===Re.DOUBLESIDE?2:1;for(let y=1;y<=_;++y)for(let v=0;vR_(r,{pathArray:e,closeArray:t,closePath:i,offset:n,updatable:a,sideOrientation:o,instance:l},s);function hee(r){const e=[],t=[],i=[],n=[],s=r.radius||.5,a=r.tessellation||64,o=r.arc&&(r.arc<=0||r.arc>1)?1:r.arc||1,l=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE;e.push(0,0,0),n.push(.5,.5);const c=Math.PI*2*o,u=o===1?c/a:c/(a-1);let h=0;for(let p=0;plD(r,{radius:e,tessellation:t,sideOrientation:s,updatable:n},i);function s5(r){const e=r.pattern||Re.NO_FLIP,t=r.tileWidth||r.tileSize||1,i=r.tileHeight||r.tileSize||1,n=r.alignHorizontal||0,s=r.alignVertical||0,a=r.width||r.size||1,o=Math.floor(a/t);let l=a-o*t;const c=r.height||r.size||1,u=Math.floor(c/i);let h=c-u*i;const d=t*o/2,f=i*u/2;let p=0,g=0,m=0,_=0,y=0,v=0;if(l>0||h>0){switch(m=-d,_=-f,y=d,v=f,n){case Re.CENTER:l/=2,m-=l,y+=l;break;case Re.LEFT:y+=l,p=-l/2;break;case Re.RIGHT:m-=l,p=l/2;break}switch(s){case Re.CENTER:h/=2,_-=h,v+=h;break;case Re.BOTTOM:v+=h,g=-h/2;break;case Re.TOP:_-=h,g=h/2;break}}const x=[],b=[],C=[];C[0]=[0,0,1,0,1,1,0,1],C[1]=[0,0,1,0,1,1,0,1],(e===Re.ROTATE_TILE||e===Re.ROTATE_ROW)&&(C[1]=[1,1,0,1,0,0,1,0]),(e===Re.FLIP_TILE||e===Re.FLIP_ROW)&&(C[1]=[1,0,0,0,0,1,1,1]),(e===Re.FLIP_N_ROTATE_TILE||e===Re.FLIP_N_ROTATE_ROW)&&(C[1]=[0,1,1,1,1,0,0,0]);let A=[];const E=[],P=[];let w=0;for(let D=0;D0||h>0){const D=h>0&&(s===Re.CENTER||s===Re.TOP),k=h>0&&(s===Re.CENTER||s===Re.BOTTOM),z=l>0&&(n===Re.CENTER||n===Re.RIGHT),W=l>0&&(n===Re.CENTER||n===Re.LEFT);let K=[],U,j,B,G;if(D&&z&&(x.push(m+p,_+g,0),x.push(-d+p,_+g,0),x.push(-d+p,_+h+g,0),x.push(m+p,_+h+g,0),P.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,U=1-l/t,j=1-h/i,B=1,G=1,K=[U,j,B,j,B,G,U,G],e===Re.ROTATE_ROW&&(K=[1-U,1-j,1-B,1-j,1-B,1-G,1-U,1-G]),e===Re.FLIP_ROW&&(K=[1-U,j,1-B,j,1-B,G,1-U,G]),e===Re.FLIP_N_ROTATE_ROW&&(K=[U,1-j,B,1-j,B,1-G,U,1-G]),A=A.concat(K),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),D&&W&&(x.push(d+p,_+g,0),x.push(y+p,_+g,0),x.push(y+p,_+h+g,0),x.push(d+p,_+h+g,0),P.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,U=0,j=1-h/i,B=l/t,G=1,K=[U,j,B,j,B,G,U,G],(e===Re.ROTATE_ROW||e===Re.ROTATE_TILE&&o%2===0)&&(K=[1-U,1-j,1-B,1-j,1-B,1-G,1-U,1-G]),(e===Re.FLIP_ROW||e===Re.FLIP_TILE&&o%2===0)&&(K=[1-U,j,1-B,j,1-B,G,1-U,G]),(e===Re.FLIP_N_ROTATE_ROW||e===Re.FLIP_N_ROTATE_TILE&&o%2===0)&&(K=[U,1-j,B,1-j,B,1-G,U,1-G]),A=A.concat(K),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),k&&z&&(x.push(m+p,f+g,0),x.push(-d+p,f+g,0),x.push(-d+p,v+g,0),x.push(m+p,v+g,0),P.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,U=1-l/t,j=0,B=1,G=h/i,K=[U,j,B,j,B,G,U,G],(e===Re.ROTATE_ROW&&u%2===1||e===Re.ROTATE_TILE&&u%1===0)&&(K=[1-U,1-j,1-B,1-j,1-B,1-G,1-U,1-G]),(e===Re.FLIP_ROW&&u%2===1||e===Re.FLIP_TILE&&u%2===0)&&(K=[1-U,j,1-B,j,1-B,G,1-U,G]),(e===Re.FLIP_N_ROTATE_ROW&&u%2===1||e===Re.FLIP_N_ROTATE_TILE&&u%2===0)&&(K=[U,1-j,B,1-j,B,1-G,U,1-G]),A=A.concat(K),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),k&&W&&(x.push(d+p,f+g,0),x.push(y+p,f+g,0),x.push(y+p,v+g,0),x.push(d+p,v+g,0),P.push(w,w+1,w+3,w+1,w+2,w+3),w+=4,U=0,j=0,B=l/t,G=h/i,K=[U,j,B,j,B,G,U,G],(e===Re.ROTATE_ROW&&u%2===1||e===Re.ROTATE_TILE&&(u+o)%2===1)&&(K=[1-U,1-j,1-B,1-j,1-B,1-G,1-U,1-G]),(e===Re.FLIP_ROW&&u%2===1||e===Re.FLIP_TILE&&(u+o)%2===1)&&(K=[1-U,j,1-B,j,1-B,G,1-U,G]),(e===Re.FLIP_N_ROTATE_ROW&&u%2===1||e===Re.FLIP_N_ROTATE_TILE&&(u+o)%2===1)&&(K=[U,1-j,B,1-j,B,1-G,U,1-G]),A=A.concat(K),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),D){const Y=[];U=0,j=1-h/i,B=1,G=1,Y[0]=[U,j,B,j,B,G,U,G],Y[1]=[U,j,B,j,B,G,U,G],(e===Re.ROTATE_TILE||e===Re.ROTATE_ROW)&&(Y[1]=[1-U,1-j,1-B,1-j,1-B,1-G,1-U,1-G]),(e===Re.FLIP_TILE||e===Re.FLIP_ROW)&&(Y[1]=[1-U,j,1-B,j,1-B,G,1-U,G]),(e===Re.FLIP_N_ROTATE_TILE||e===Re.FLIP_N_ROTATE_ROW)&&(Y[1]=[U,1-j,B,1-j,B,1-G,U,1-G]);for(let Z=0;ZY+M)),M+=A[B].length,i)for(let Y=0;Y<4;Y++)C.push(i[B].r,i[B].g,i[B].b,i[B].a)}const R=new O(0,0,g),I=pe.RotationY(Math.PI);y=A[0].map(B=>O.TransformNormal(B,I).add(R)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]),v=E[0].map(B=>O.TransformNormal(B,I)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]),y=y.concat(A[1].map(B=>B.subtract(R)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),v=v.concat(E[1].map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]));const D=new O(f,0,0),k=pe.RotationY(-Math.PI/2);y=y.concat(A[2].map(B=>O.TransformNormal(B,k).add(D)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),v=v.concat(E[2].map(B=>O.TransformNormal(B,k)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]));const z=pe.RotationY(Math.PI/2);y=y.concat(A[3].map(B=>O.TransformNormal(B,z).subtract(D)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),v=v.concat(E[3].map(B=>O.TransformNormal(B,z)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]));const W=new O(0,p,0),K=pe.RotationX(Math.PI/2);y=y.concat(A[4].map(B=>O.TransformNormal(B,K).add(W)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),v=v.concat(E[4].map(B=>O.TransformNormal(B,K)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[]));const U=pe.RotationX(-Math.PI/2);y=y.concat(A[5].map(B=>O.TransformNormal(B,U).subtract(W)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),v=v.concat(E[5].map(B=>O.TransformNormal(B,U)).map(B=>[B.x,B.y,B.z]).reduce((B,G)=>B.concat(G),[])),vt._ComputeSides(d,y,b,v,x);const j=new vt;if(j.indices=b,j.positions=y,j.normals=v,j.uvs=x,i){const B=d===vt.DOUBLESIDE?C.concat(C):C;j.colors=B}return j}function q1e(r,e,t=null){const i=new Re(r,t);return e.sideOrientation=Re._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Z1e(e).applyToMesh(i,e.updatable),i}const g4t={CreateTiledBox:q1e};vt.CreateTiledBox=Z1e;function J1e(r){const e=[],t=[],i=[],n=[],s=r.radius||2,a=r.tube||.5,o=r.radialSegments||32,l=r.tubularSegments||32,c=r.p||2,u=r.q||3,h=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,d=m=>{const _=Math.cos(m),y=Math.sin(m),v=u/c*m,x=Math.cos(v),b=s*(2+x)*.5*_,C=s*(2+x)*y*.5,A=s*Math.sin(v)*.5;return new O(b,C,A)};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 b=v.add(y);const C=O.Cross(x,b);for(b=O.Cross(C,x),C.normalize(),b.normalize(),p=0;pdee(r,{radius:e,tube:t,radialSegments:i,tubularSegments:n,p:s,q:a,sideOrientation:c,updatable:l},o);Re._LinesMeshParser=(r,e)=>vg.Parse(r,e);class vg extends Re{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,n=null,s,a,o,l){super(e,t,i,n,s),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new Pe(1,1,1),this.alpha=1,this._shaderLanguage=0,n&&(this.color=n.color.clone(),this.alpha=n.alpha,this.useVertexColor=n.useVertexColor,this.useVertexAlpha=n.useVertexAlpha),this.intersectionThreshold=.1;const c=[],u={attributes:[ee.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(ee.ColorKind)):(u.uniforms.push("color"),this._color4=new at),l?this.material=l:(this.getScene().getEngine().isWebGPU&&!vg.ForceGLSL&&(this._shaderLanguage=1),u.shaderLanguage=this._shaderLanguage,u.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([je(()=>Promise.resolve().then(()=>KRt),void 0),je(()=>Promise.resolve().then(()=>WRt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>FAt),void 0),je(()=>Promise.resolve().then(()=>OAt),void 0)])},this.material=new ua("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=tt.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:n,g:s,b:a}=this.color;this._color4.set(n,s,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 n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(tt.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(tt.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 vg(e,this.getScene(),t,this,i)}createInstance(e){const t=new e_e(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 vg(e.name,t);return i.color=Pe.FromArray(e.color),i.alpha=e.alpha,i}}vg.ForceGLSL=!1;class e_e extends W0{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function t_e(r){const e=[],t=[],i=r.lines,n=r.colors,s=[];let a=0;for(let l=0;l0&&(e.push(a-1),e.push(a)),a++}}const o=new vt;return o.indices=e,o.positions=t,n&&(o.colors=s),o}function i_e(r){const e=r.dashSize||3,t=r.gapSize||1,i=r.dashNb||200,n=r.points,s=[],a=[],o=O.Zero();let l=0,c=0,u=0,h=0,d=0,f=0,p=0;for(p=0;p{const h=O.Zero(),d=u.length/6;let f=0,p=0,g=0,m=0,_=0,y=0,v=0,x=0;for(v=0;vzs(r,{points:e,updatable:i,instance:n},t);Re.CreateDashedLines=(r,e,t,i,n,s=null,a,o)=>fee(r,{points:e,dashSize:t,gapSize:i,dashNb:n,updatable:a,instance:o},s);class y4t extends Ne{constructor(e,t){super(e.x,e.y),this.index=t}}class pae{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const n=new y4t(i,this.elements.length);t.push(n),this.elements.push(n)}),t}computeBounds(){const e=new Ne(this.elements[0].x,this.elements[0].y),t=new Ne(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 x4t=class{static Rectangle(e,t,i,n){return[new Ne(e,t),new Ne(i,t),new Ne(i,n),new Ne(e,n)]}static Circle(e,t=0,i=0,n=32){const s=[];let a=0;const o=Math.PI*2/n;for(let l=0;l!isNaN(s));let i;const n=[];for(i=0;i<(t.length&2147483646);i+=2)n.push(new Ne(t[i],t[i+1]));return n}static StartingAt(e,t){return eD.StartingAt(e,t)}};class jke{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,n=earcut){this._points=new pae,this._outlinepoints=new pae,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=n,this._name=e,this._scene=i||ei.LastCreatedScene;let s;t instanceof eD?s=t.getPoints():s=t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),typeof this.bjsEarcut>"u"&&ge.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new pae;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 n=new Re(this._name,this._scene),s=this.buildVertexData(t,i);return n.setVerticesData(ee.PositionKind,s.positions,e),n.setVerticesData(ee.NormalKind,s.normals,e),n.setVerticesData(ee.UVKind,s.uvs,e),n.setIndices(s.indices),n}buildVertexData(e=0,t=2){const i=new vt,n=[],s=[],a=[],o=this._points.computeBounds();this._points.elements.forEach(u=>{n.push(0,1,0),s.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=s.length/3;this._points.elements.forEach(d=>{n.push(0,-1,0),s.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(s,n,a,l,o,d,e,!0,t)})}return i.indices=l,i.positions=s,i.normals=n,i.uvs=a,i}_addSide(e,t,i,n,s,a,o,l,c){let u=e.length/3,h=0;for(let d=0;dc?Ac?EZz(r,{shape:e,holes:i,updatable:n,sideOrientation:s},t,a);Re.ExtrudePolygon=(r,e,t,i,n,s,a,o=earcut)=>qz(r,{shape:e,holes:n,depth:t,updatable:s,sideOrientation:a},i,o);function Jz(r,e,t=null){const i=e.path,n=e.shape,s=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||Re.NO_CAP,l=e.updatable,c=Re._GetDefaultSideOrientation(e.sideOrientation),u=e.instance||null,h=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return $ke(r,n,i,s,a,null,null,f,d,o,!1,t,!!l,c,u,h,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function eV(r,e,t=null){const i=e.path,n=e.shape,s=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||Re.NO_CAP,u=e.updatable,h=e.firstNormal||null,d=e.adjustFrame||!1,f=Re._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,g=e.invertUV||!1;return $ke(r,n,i,null,null,s,a,o,l,c,!0,t,!!u,f,p||null,g,e.frontUVs||null,e.backUVs||null,h,d)}function $ke(r,e,t,i,n,s,a,o,l,c,u,h,d,f,p,g,m,_,y,v){const x=(P,w,M,R,I,D,k,z,W,K,U)=>{const j=M.getTangents(),B=M.getNormals(),G=M.getBinormals(),Y=M.getDistances();if(U){for(let J=0;J0){let ae=j[J-1];O.Dot(ae,j[J])<0&&j[J].scaleInPlace(-1),ae=B[J-1],O.Dot(ae,B[J])<0&&B[J].scaleInPlace(-1),ae=G[J-1],O.Dot(ae,G[J])<0&&G[J].scaleInPlace(-1)}}let Z=0;const te=()=>I!==null?I:1,ce=K&&z?z:()=>D!==null?D:0,ue=K&&k?k:te;let N=W===Re.NO_CAP||W===Re.CAP_END?0:2;const F=oe.Matrix[0];for(let J=0;J{const ae=Array(),ne=O.Zero();let he;for(he=0;he3?0:c,C=x(e,t,b,A,i,n,s,a,c,u,v);const E=R_(r,{pathArray:C,closeArray:o,closePath:l,updatable:d,sideOrientation:f,invertUV:g,frontUVs:m||void 0,backUVs:_||void 0},h);return E._creationDataStorage.pathArray=C,E._creationDataStorage.path3D=b,E._creationDataStorage.cap=c,E}const C4t={ExtrudeShape:Jz,ExtrudeShapeCustom:eV};Re.ExtrudeShape=(r,e,t,i,n,s,a=null,o,l,c)=>{const u={shape:e,path:t,scale:i,rotation:n,cap:s===0?0:s||Re.NO_CAP,sideOrientation:l,instance:c,updatable:o};return Jz(r,u,a)};Re.ExtrudeShapeCustom=(r,e,t,i,n,s,a,o,l,c,u,h)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:n,ribbonCloseArray:s,ribbonClosePath:a,cap:o===0?0:o||Re.NO_CAP,sideOrientation:u,instance:h,updatable:c};return eV(r,d,l)};function pee(r,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,n=e.closed===void 0?!0:e.closed,s=e.shape,a=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,u=Re._GetDefaultSideOrientation(e.sideOrientation),h=e.cap||Re.NO_CAP,d=Math.PI*2,f=[],p=e.invertUV||!1;let g=0,m=0;const _=d/o*i;let y,v;for(g=0;g<=o-l;g++){for(v=[],(h==Re.CAP_START||h==Re.CAP_ALL)&&(v.push(new O(0,s[0].y,0)),v.push(new O(Math.cos(g*_)*s[0].x*a,s[0].y,Math.sin(g*_)*s[0].x*a))),m=0;mpee(r,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:s},n);function mee(r,e,t=null){const i=e.path;let n=e.instance,s=1;e.radius!==void 0?s=e.radius:n&&(s=n._creationDataStorage.radius);const a=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||Re.NO_CAP;const c=e.invertUV||!1,u=e.updatable,h=Re._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(_,y,v,x,b,C,A,E)=>{const P=y.getTangents(),w=y.getNormals(),M=y.getDistances(),I=Math.PI*2/b*E,k=C||(()=>x);let z,W,K,U;const j=oe.Matrix[0];let B=A===Re.NO_CAP||A===Re.CAP_END?0:2;for(let Y=0;Y<_.length;Y++){W=k(Y,M[Y]),z=Array(),K=w[Y];for(let Z=0;Z{const te=Array();for(let le=0;le3?0:l,p=d(i,f,g,s,a,o,l,e.arc);const m=R_(r,{pathArray:p,closePath:!0,closeArray:!1,updatable:u,sideOrientation:h,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return m._creationDataStorage.pathArray=p,m._creationDataStorage.path3D=f,m._creationDataStorage.tessellation=a,m._creationDataStorage.cap=l,m._creationDataStorage.arc=e.arc,m._creationDataStorage.radius=s,m}const S4t={CreateTube:mee};Re.CreateTube=(r,e,t,i,n,s,a,o,l,c)=>mee(r,{path:e,radius:t,tessellation:i,radiusFunction:n,arc:1,cap:s,updatable:o,sideOrientation:l,instance:c},a);function n_e(r){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=r.type&&(r.type<0||r.type>=e.length)?0:r.type||0,i=r.size,n=r.sizeX||i||1,s=r.sizeY||i||1,a=r.sizeZ||i||1,o=r.custom||e[t],l=o.face.length,c=r.faceUV||new Array(l),u=r.faceColors,h=r.flat===void 0?!0:r.flat,d=r.sideOrientation===0?0:r.sideOrientation||vt.DEFAULTSIDE,f=[],p=[],g=[],m=[],_=[];let y=0,v=0;const x=[];let b=0,C=0,A,E,P,w,M,R;if(h)for(C=0;CsE(r,e,t);function gee(r){const e=r.sideOrientation||vt.DEFAULTSIDE,t=r.radius||1,i=r.flat===void 0?!0:r.flat,n=(r.subdivisions||4)|0,s=r.radiusX||t,a=r.radiusY||t,o=r.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,g=60/1024,m=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=[],b=[],C=[],A=[];let E=0;const P=new Array(3),w=new Array(3);let M;for(M=0;M<3;M++)P[M]=O.Zero(),w[M]=Ne.Zero();for(let I=0;I<20;I++){for(M=0;M<3;M++){const k=u[3*I+M];P[M].copyFromFloats(c[3*h[k]],c[3*h[k]+1],c[3*h[k]+2]),P[M].normalize(),w[M].copyFromFloats(d[2*k]*f+g+v[I]*_,d[2*k+1]*p+m+v[I]*y)}const D=(k,z,W,K)=>{const U=O.Lerp(P[0],P[2],z/n),j=O.Lerp(P[1],P[2],z/n),B=n===z?P[2]:O.Lerp(U,j,k/(n-z));B.normalize();let G;if(i){const le=O.Lerp(P[0],P[2],K/n),ce=O.Lerp(P[1],P[2],K/n);G=O.Lerp(le,ce,W/(n-K))}else G=new O(B.x,B.y,B.z);G.x/=s,G.y/=a,G.z/=o,G.normalize();const Y=Ne.Lerp(w[0],w[2],z/n),Z=Ne.Lerp(w[1],w[2],z/n),te=n===z?w[2]:Ne.Lerp(Y,Z,k/(n-z));b.push(B.x*s,B.y*a,B.z*o),C.push(G.x,G.y,G.z),A.push(te.x,bn?1-te.y:te.y),x.push(E),E++};for(let k=0;ktV(r,e,t);const M4t=new O(1,0,0),R4t=new O(-1,0,0),I4t=new O(0,1,0),P4t=new O(0,-1,0),w4t=new O(0,0,1),D4t=new O(0,0,-1);class yZ{constructor(e=O.Zero(),t=O.Up(),i=Ne.Zero(),n=0,s=0,a=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=n,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,n;return new yZ(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(),(n=this.matrixWeightsOverride)==null?void 0:n.slice())}}function _ee(r,e,t){var z,W,K,U;const i=!!e.skeleton,n=t.localMode||i,s=e.getIndices(),a=i?e.getPositionData(!0,!0):e.getVerticesData(ee.PositionKind),o=i?e.getNormalsData(!0,!0):e.getVerticesData(ee.NormalKind),l=n?i?e.getVerticesData(ee.PositionKind):a:null,c=n?i?e.getVerticesData(ee.NormalKind):o:null,u=e.getVerticesData(ee.UVKind),h=i?e.getVerticesData(ee.MatricesIndicesKind):null,d=i?e.getVerticesData(ee.MatricesWeightsKind):null,f=i?e.getVerticesData(ee.MatricesIndicesExtraKind):null,p=i?e.getVerticesData(ee.MatricesWeightsExtraKind):null,g=t.position||O.Zero();let m=t.normal||O.Up();const _=t.size||O.One(),y=t.angle||0;if(!m){const j=new O(0,0,1),B=e.getScene().activeCamera,G=O.TransformCoordinates(j,B.getWorldMatrix());m=B.globalPosition.subtract(G)}const v=-Math.atan2(m.z,m.x)-Math.PI/2,x=Math.sqrt(m.x*m.x+m.z*m.z),b=Math.atan2(m.y,x),C=new vt;C.indices=[],C.positions=[],C.normals=[],C.uvs=[],C.matricesIndices=i?[]:null,C.matricesWeights=i?[]:null,C.matricesIndicesExtra=f?[]:null,C.matricesWeightsExtra=p?[]:null;let A=0;const E=(j,B)=>{const G=new yZ;if(!s||!a||!o)return G;const Y=s[j];if(G.vertexIdx=Y*3,G.vertexIdxForBones=Y*4,G.position=new O(a[Y*3],a[Y*3+1],a[Y*3+2]),O.TransformCoordinatesToRef(G.position,B,G.position),G.normal=new O(o[Y*3],o[Y*3+1],o[Y*3+2]),O.TransformNormalToRef(G.normal,B,G.normal),t.captureUVS&&u){const Z=u[Y*2+1];G.uv=new Ne(u[Y*2],bn?1-Z:Z)}return G},P=[0,0,0,0],w=(j,B)=>{if(j.length===0)return j;const G=.5*Math.abs(O.Dot(_,B)),Y=(le,ce,ue,N)=>{for(let F=0;F{const ue=O.GetClipFactor(le.position,ce.position,B,G);let N=P,F=P;if(h&&d){const Dt=le.matrixIndicesOverride?0:le.vertexIdxForBones,Qt=le.matrixIndicesOverride??h,qt=le.matrixWeightsOverride??d,wt=ce.matrixIndicesOverride?0:ce.vertexIdxForBones,zt=ce.matrixIndicesOverride??h,Ot=ce.matrixWeightsOverride??d;N=[0,0,0,0],F=[0,0,0,0];let St=0;for(let Bt=0;Bt<4;++Bt)if(qt[Dt+Bt]>0){const Kt=Y(zt,Qt[Dt+Bt],wt,4);N[St]=Qt[Dt+Bt],F[St]=Xt.Lerp(qt[Dt+Bt],Kt>=0?Ot[Kt]:0,ue),St++}for(let Bt=0;Bt<4&&St<4;++Bt){const Kt=zt[wt+Bt];Y(Qt,Kt,Dt,4)===-1&&(N[St]=Kt,F[St]=Xt.Lerp(0,Ot[wt+Bt],ue),St++)}const Lt=F[0]+F[1]+F[2]+F[3];F[0]/=Lt,F[1]/=Lt,F[2]/=Lt,F[3]/=Lt}const X=le.localPositionOverride?le.localPositionOverride[0]:(l==null?void 0:l[le.vertexIdx])??0,J=le.localPositionOverride?le.localPositionOverride[1]:(l==null?void 0:l[le.vertexIdx+1])??0,ae=le.localPositionOverride?le.localPositionOverride[2]:(l==null?void 0:l[le.vertexIdx+2])??0,ne=ce.localPositionOverride?ce.localPositionOverride[0]:(l==null?void 0:l[ce.vertexIdx])??0,he=ce.localPositionOverride?ce.localPositionOverride[1]:(l==null?void 0:l[ce.vertexIdx+1])??0,fe=ce.localPositionOverride?ce.localPositionOverride[2]:(l==null?void 0:l[ce.vertexIdx+2])??0,ye=le.localNormalOverride?le.localNormalOverride[0]:(c==null?void 0:c[le.vertexIdx])??0,Se=le.localNormalOverride?le.localNormalOverride[1]:(c==null?void 0:c[le.vertexIdx+1])??0,De=le.localNormalOverride?le.localNormalOverride[2]:(c==null?void 0:c[le.vertexIdx+2])??0,ze=ce.localNormalOverride?ce.localNormalOverride[0]:(c==null?void 0:c[ce.vertexIdx])??0,Le=ce.localNormalOverride?ce.localNormalOverride[1]:(c==null?void 0:c[ce.vertexIdx+1])??0,Je=ce.localNormalOverride?ce.localNormalOverride[2]:(c==null?void 0:c[ce.vertexIdx+2])??0,ke=ye+(ze-ye)*ue,We=Se+(Le-Se)*ue,it=De+(Je-De)*ue,_t=Math.sqrt(ke*ke+We*We+it*it);return new yZ(O.Lerp(le.position,ce.position,ue),O.Lerp(le.normal,ce.normal,ue).normalize(),Ne.Lerp(le.uv,ce.uv,ue),-1,-1,l?[X+(ne-X)*ue,J+(he-J)*ue,ae+(fe-ae)*ue]:null,c?[ke/_t,We/_t,it/_t]:null,N,F)};let te=null;j.length>3&&(te=[]);for(let le=0;le0,fe=ae>0,ye=ne>0;switch(ce=(he?1:0)+(fe?1:0)+(ye?1:0),ce){case 0:j.length>3?(te.push(j[le]),te.push(j[le+1]),te.push(j[le+2])):te=j;break;case 1:if(te=te??new Array,he&&(ue=j[le+1],N=j[le+2],F=Z(j[le],ue),X=Z(j[le],N)),fe){ue=j[le],N=j[le+2],F=Z(j[le+1],ue),X=Z(j[le+1],N),te.push(F),te.push(N.clone()),te.push(ue.clone()),te.push(N.clone()),te.push(F.clone()),te.push(X);break}ye&&(ue=j[le],N=j[le+1],F=Z(j[le+2],ue),X=Z(j[le+2],N)),ue&&N&&F&&X&&(te.push(ue.clone()),te.push(N.clone()),te.push(F),te.push(X),te.push(F.clone()),te.push(N.clone()));break;case 2:te=te??new Array,he||(ue=j[le].clone(),N=Z(ue,j[le+1]),F=Z(ue,j[le+2]),te.push(ue),te.push(N),te.push(F)),fe||(ue=j[le+1].clone(),N=Z(ue,j[le+2]),F=Z(ue,j[le]),te.push(ue),te.push(N),te.push(F)),ye||(ue=j[le+2].clone(),N=Z(ue,j[le]),F=Z(ue,j[le+1]),te.push(ue),te.push(N),te.push(F));break}}return te},M=e instanceof Re?e:null,R=M==null?void 0:M._thinInstanceDataStorage.matrixData,I=(M==null?void 0:M.thinInstanceCount)||1,D=oe.Matrix[0];D.copyFrom(pe.IdentityReadOnly);for(let j=0;j_ee(r,e,{position:t,normal:i,size:n,angle:s});class Ha{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),ge.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),ge.Warn("y is not an integer, floor(y) used"))}clone(){return new Ha(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),ge.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),ge.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),ge.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),ge.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=O.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 Ha(0,0)}}class s_e{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new xZ("icosahedron","Regular",[[0,cl,-1],[-cl,1,0],[-1,0,-cl],[1,0,-cl],[cl,1,0],[0,cl,1],[-1,0,cl],[-cl,-1,0],[0,-cl,-1],[cl,-1,0],[1,0,cl],[0,-cl,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,n=this.n;let s=i,a=1,o=0;n!==0&&(s=Xt.HCF(i,n)),a=i/s,o=n/s;let l,c,u,h,d;const f=Ha.Zero(),p=new Ha(i,n),g=new Ha(-n,i+n),m=Ha.Zero(),_=Ha.Zero(),y=Ha.Zero();let v=[],x,b,C,A;const E=[],P=this.vertByDist,w=(M,R,I,D)=>{x=M+"|"+I,b=R+"|"+D,x in t||b in t?x in t&&!(b in t)?t[b]=t[x]:b in t&&!(x in t)&&(t[x]=t[b]):(t[x]=e,t[b]=e,e++),P[I][0]>2?E[t[x]]=[-P[I][0],P[I][1],t[x]]:E[t[x]]=[v[P[I][0]],P[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],C=f.x+"|"+f.y,x=M+"|"+C,x in t||(t[x]=u,E[u]=[v[P[C][0]],P[C][1]]),C=p.x+"|"+p.y,x=M+"|"+C,x in t||(t[x]=h,E[h]=[v[P[C][0]],P[C][1]]),C=g.x+"|"+g.y,x=M+"|"+C,x in t||(t[x]=d,E[d]=[v[P[C][0]],P[C][1]]),l=this.IDATA.edgematch[M][0],c=this.IDATA.edgematch[M][1],c==="B")for(let R=1;R2?E[t[x]]=[-P[C][0],P[C][1],t[x]]:E[t[x]]=[v[P[C][0]],P[C][1],t[x]])}this.closestTo=E,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,n=e*e+t*t+e*t;this.coau=(e+t)/n,this.cobu=-t/n,this.coav=-i*(e-t)/n,this.cobv=i*(2*e+t)/n}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&n0){const b=Xt.HCF(e,t),C=e/b,A=t/b;for(let P=1;Pb.x-C.x),i.sort((b,C)=>b.y-C.y);const o=new Array(e+t+1),l=new Array(e+t+1);for(let b=0;b{const A=b.clone();return C==="A"&&A.rotateNeg120(e,t),C==="B"&&A.rotate120(e,t),A.x<0?A.y:A.x+A.y},f=[],p=[],g=[],m=[],_={},y=[];let v=-1,x=-1;for(let b=0;bb[2]-C[2]),y.sort((b,C)=>b[3]-C[3]),y.sort((b,C)=>b[1]-C[1]),y.sort((b,C)=>b[0]-C[0]);for(let b=0;bt.vecToidx[e+n]))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let n=0;n-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);const n=[];for(let a=0;a<12;a++)n[a]=a;let s=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;)s=t[l],this.face[s].indexOf(o)>-1?(a=(this.face[s].indexOf(o)+1)%3,o=this.face[s][a],i.push(o),n.push(s),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),n}toGoldbergPolyhedronData(){const e=new xZ("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let c=0;c{n=0,s=0,a=0,o=this.face[u];for(let h=0;h<3;h++)l=this.vertex[o[h]],n+=l[0],s+=l[1],a+=l[2];e.vertex[u]=[n/3,s/3,a/3]});return e}static BuildGeodesicData(e){const t=new iV("Geodesic-m-n","Geodesic",[[0,cl,-1],[-cl,1,0],[-1,0,-cl],[1,0,-cl],[cl,1,0],[0,cl,1],[-1,0,cl],[-cl,-1,0],[0,-cl,-1],[cl,-1,0],[1,0,cl],[0,-cl,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let n=0;ni){const c=n;n=i,i=c,ge.Warn("n > m therefore m and n swapped")}const s=new s_e;s.build(i,n);const o={custom:iV.BuildGeodesicData(s),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 sE(r,o,t)}Re._GoldbergMeshParser=(r,e)=>rV.Parse(r,e);class rV extends Re{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&&(ge.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(ge.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(ge.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=n;fat.FromArray(s)),i.faceCenters=i.faceCenters.map(s=>O.FromArray(s)),i.faceZaxis=i.faceZaxis.map(s=>O.FromArray(s)),i.faceXaxis=i.faceXaxis.map(s=>O.FromArray(s)),i.faceYaxis=i.faceYaxis.map(s=>O.FromArray(s));const n=new rV(e.name,t);return n.goldbergData=i,n}}function Yke(r,e){const t=r.size,i=r.sizeX||t||1,n=r.sizeY||t||1,s=r.sizeZ||t||1,a=r.sideOrientation===0?0:r.sideOrientation||vt.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,ge.Warn("n > m therefore m and n swapped")}const c=new s_e;c.build(o,l);const u=iV.BuildGeodesicData(c),h=u.toGoldbergPolyhedronData(),d=new rV(r,t);e.sideOrientation=Re._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,Yke(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 N4t(r,e,t,i,n,s){const a=s.glyphs[r]||s.glyphs["?"];if(!a)return null;const o=new L4t(n);if(a.o){const l=a.o.split(" ");for(let c=0,u=l.length;cKi&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>Ki&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>Ki&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:n,axisA:s,axisB:a,perpAxisA:o,perpAxisB:l}=e._initOptions;!i||!n||!s||!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:g}=h.metadata,m=this._getTransformFromBodyToRef(d,oe.Matrix[0],f),_=this._getTransformFromBodyToRef(p,oe.Matrix[1],g);m.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(n),Oe.FromRotationMatrixToRef(pe.FromXYZAxesToRef(s,o,O.CrossToRef(s,o,oe.Vector3[0]),oe.Matrix[0]),y.rotationQuaternion),Oe.FromRotationMatrixToRef(pe.FromXYZAxesToRef(a,l,O.CrossToRef(a,l,oe.Vector3[1]),oe.Matrix[1]),v.rotationQuaternion)})}showImpostor(e,t){if(!this._scene)return null;for(let n=0;nthis._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 n=0;n-1&&this._debugMeshMeshes.splice(a,1),this._numMeshes--,this._numMeshes>0?(this._meshes[n]=this._meshes[this._numMeshes],this._impostors[n]=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 n=0;n0?(this._bodyMeshes[n]=this._bodyMeshes[this._numBodies],this._bodies[n]=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 n=0;n0?(this._constraints[n]=this._constraints[this._numConstraints],this._constraintMeshes[n]=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 ct("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Pe.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new ct("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=jh("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=Oe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=bu("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=Oe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Qz("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=Oe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=zu("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=Oe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Re(e.name,t,null,e);return i.setParent(e),i.position=O.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 n=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return ge.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case Gi.BoxImpostor:i=this._getDebugBoxMesh(n),e.getBoxSizeToRef(i.scaling);break;case Gi.SphereImpostor:{i=this._getDebugSphereMesh(n);const s=e.getRadius();i.scaling.x=s*2,i.scaling.y=s*2,i.scaling.z=s*2;break}case Gi.CapsuleImpostor:{i=this._getDebugCapsuleMesh(n);const s=e.object.getBoundingInfo();i.scaling.x=(s.boundingBox.maximum.x-s.boundingBox.minimum.x)*2*e.object.scaling.x,i.scaling.y=(s.boundingBox.maximum.y-s.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(s.boundingBox.maximum.z-s.boundingBox.minimum.z)*2*e.object.scaling.z;break}case Gi.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,n));break;case Gi.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 Gi.BoxImpostor:i=this._getDebugBoxMesh(n),i.position.copyFrom(l),i.position.addInPlace(c),i.position.scaleInPlace(.5);break;case Gi.SphereImpostor:i=this._getDebugSphereMesh(n);break;case Gi.CylinderImpostor:i=this._getDebugCylinderMesh(n);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)}}):ge.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case Gi.CylinderImpostor:{i=this._getDebugCylinderMesh(n);const s=e.object.getBoundingInfo();i.scaling.x=(s.boundingBox.maximum.x-s.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(s.boundingBox.maximum.y-s.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(s.boundingBox.maximum.z-s.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Re("custom",t),n=new vt,s=e.getGeometry();if(n.positions=s.positions,n.indices=s.indices,n.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??Oe.Identity(),n=e.inertia??O.Zero(),s=e.centerOfMass??O.Zero(),a=(n.x-n.y+n.z)*6,o=Math.sqrt(Math.max(a,0)),l=n.x*12-a,c=Math.sqrt(Math.max(l,0)),u=n.z*12-a,h=Math.sqrt(Math.max(u,0)),d=oe.Vector3[0];d.set(h,o,c);const f=pe.ScalingToRef(d.x,d.y,d.z,oe.Matrix[0]),p=i.toRotationMatrix(oe.Matrix[1]),g=pe.TranslationToRef(s.x,s.y,s.z,oe.Matrix[2]);return f.multiplyToRef(p,t),t.multiplyToRef(g,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=Cd.CreateBox("custom",{size:1},t),n=pe.Identity();if(e._pluginDataInstances.length){const s=new Float32Array(e._pluginDataInstances.length*16);for(let a=0;a=0?pe.FromArrayToRef(n._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(n.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:n,axisA:s,axisB:a,perpAxisA:o,perpAxisB:l}=e._initOptions;if(!i||!n||!s||!a||!o||!l)return null;const c=new Re("parentingDebugConstraint",t),u=e.getBodiesUsingConstraint();for(const h of u){const d=new Yt("parentOfPair",t);d.parent=c;const{parentBody:f,parentBodyIndex:p,childBody:g,childBodyIndex:m}=h,_=this._getTransformFromBodyToRef(f,oe.Matrix[0],p),y=this._getTransformFromBodyToRef(g,oe.Matrix[1],m),v=new Yt("parentCoordSystem",t);v.parent=d,v.metadata={parentBody:f,parentBodyIndex:p},_.decomposeToTransformNode(v);const x=new Yt("childCoordSystem",t);x.parent=d,x.metadata={childBody:g,childBodyIndex:m},y.decomposeToTransformNode(x);const b=Oe.FromRotationMatrix(pe.FromXYZAxesToRef(s,o,s.cross(o),oe.Matrix[0])),C=Oe.FromRotationMatrix(pe.FromXYZAxesToRef(a,l,a.cross(l),oe.Matrix[0])),A=i,E=n,P=new Yt("constraint_parent",t);P.position.copyFrom(A),P.rotationQuaternion=b,P.parent=v;const w=new Yt("constraint_child",t);w.parent=x,w.position.copyFrom(E),w.rotationQuaternion=C;const M=new Dv(t,this._constraintAxesSize);M.xAxis.parent=P,M.yAxis.parent=P,M.zAxis.parent=P;const R=new Dv(t,this._constraintAxesSize);R.xAxis.parent=w,R.yAxis.parent=w,R.zAxis.parent=w}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 o_e{static CreateAndShow(e,t,i){const n=new o_e(e);return n.show(t,i),n}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=zs("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 n;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),zs("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),(n=this._renderLine)==null||n.refreshBoundingInfo()}attachToMesh(e,t,i,n){this._attachedToMesh=e;const s=this.ray;s&&(s.direction||(s.direction=O.Zero()),s.origin||(s.origin=O.Zero()),n&&(s.length=n),i||(i=O.Zero()),t||(t=new O(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),O.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)}}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class zh{static CreateBoneWeightShader(e,t){const i=e.skeleton,n=e.colorBase??Pe.Black(),s=e.colorZero??Pe.Blue(),a=e.colorQuarter??Pe.Green(),o=e.colorHalf??Pe.Yellow(),l=e.colorFull??Pe.Red(),c=e.targetBoneIndex??0;Sr.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; }`,Sr.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 ua("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",n),u.setColor3("colorZero",s),u.setColor3("colorQuarter",a),u.setColor3("colorHalf",o),u.setColor3("colorFull",l),u.setFloat("targetBoneIndex",c),u.getClassName=()=>"BoneWeightShader",u.transparencyMode=tt.MATERIAL_OPAQUE,u}static CreateSkeletonMapShader(e,t){const i=e.skeleton,n=e.colorMap??[{color:new Pe(1,.38,.18),location:0},{color:new Pe(.59,.18,1),location:.2},{color:new Pe(.59,1,.18),location:.4},{color:new Pe(1,.87,.17),location:.6},{color:new Pe(1,.17,.42),location:.8},{color:new Pe(.17,.68,1),location:1}],s=i.bones.length+1,a=zh._CreateBoneMapColorBuffer(s,n,t),o=new ua("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=tt.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const n=new Ep("temp",{width:e,height:1},i,!1),s=n.getContext(),a=s.createLinearGradient(0,0,e,0);t.forEach(u=>{a.addColorStop(u.location,u.color.toHexString())}),s.fillStyle=a,s.fillRect(0,0,e,1),n.update();const o=[],l=s.getImageData(0,0,e,1).data,c=1/255;for(let u=0;uzh.DISPLAY_SPHERE_AND_SPURS&&(e=zh.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,n=!0,s=3,a={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=n,this.renderingGroupId=s,this.options=a,this.color=Pe.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??zh.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(ee.MatricesIndicesKind),c=t==null?void 0:t.getVerticesData(ee.MatricesWeightsKind);if(l&&c)for(let u=0;uzh.DISPLAY_SPHERE_AND_SPURS&&(o=zh.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){switch(this.displayMode){case zh.DISPLAY_LINES:{this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()});break}}}update(){switch(this.displayMode){case zh.DISPLAY_LINES:{this._displayLinesUpdate();break}case zh.DISPLAY_SPHERES:{this._buildSpheresAndSpurs(!0);break}case zh.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,n=0,s=0,a=0){const o=oe.Matrix[0],l=t.getParent();if(o.copyFrom(t.getLocalMatrix()),n!==0||s!==0||a!==0){const c=oe.Matrix[1];pe.IdentityToRef(c),c.setTranslationFromFloats(n,s,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 n,s;t?(n=t.getWorldMatrix(),s=t.position):(n=new pe,s=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=[O.Zero(),O.Zero()],this._debugLines[i]=u),l.getAbsolutePositionToRef(s,u[0]),c.getAbsolutePositionToRef(s,u[1]),u[0].subtractInPlace(a),u[1].subtractInPlace(a),i++}n||s.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(pe.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_createSpur(e,t,i,n,s,a){const o=i.subtract(e),l=o.length(),c=o.normalize().scale(l),u=s.midStep||.165,h=s.midStepFactor||.215,d=c.scale(u),f=eV("skeletonViewer",{shape:[new O(1,-1,0),new O(1,1,0),new O(-1,1,0),new O(-1,-1,0),new O(1,-1,0)],path:[O.Zero(),d,c],scaleFunction:_=>{switch(_){case 0:case 2:return 0;case 1:return l*h}return 0},sideOrientation:Re.DEFAULTSIDE,updatable:!1},a),p=f.getTotalVertices(),g=[],m=[];for(let _=0;_9?m.push(n.getIndex(),0,0,0):m.push(t.getIndex(),0,0,0);return f.position=e.clone(),f.setVerticesData(ee.MatricesWeightsKind,g,!1),f.setVerticesData(ee.MatricesIndicesKind,m,!1),f.convertToFlatShadedMesh(),f}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(ee.PositionKind),i=this.mesh.getIndices(),n=this.mesh.getVerticesData(ee.MatricesWeightsKind),s=this.mesh.getVerticesData(ee.MatricesIndicesKind);if(!t||!i||!n||!s)return null;const a=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let l=0;for(let c=0;c1e-5){O.FromArrayToRef(t,u*3,oe.Vector3[0]),a.minimizeInPlace(oe.Vector3[0]),o.maximizeInPlace(oe.Vector3[0]),l++;break}}}return l>1?{center:O.Center(a,o),radius:O.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,n=[],s=[],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)g.children.forEach(A=>{const E=new pe;A.getLocalMatrix().multiplyToRef(m,E);const P=new O;E.decompose(void 0,void 0,P);const w=O.Distance(_,P);w>l&&(l=w),!e&&s.push(this._createSpur(_,g,P,A,c,t))});else{const A=this._getBoundingSphereForBone(g.getIndex());if(A&&(A.radius>l&&(l=A.radius),!e)){let E;const P=g.getParent();P?(this._getAbsoluteBindPoseToRef(P,m),m.decompose(void 0,void 0,oe.Vector3[0]),E=_.subtract(oe.Vector3[0]).normalize().scale(A.radius).add(_)):E=A.center.subtract(_).normalize().scale(A.radius).add(_),s.push(this._createSpur(_,g,E,null,c,t))}}const y=c.sphereBaseSize||.2,v=bu("skeletonViewer",{segments:6,diameter:y,updatable:!0},t),x=v.getTotalVertices(),b=[],C=[];for(let A=0;A{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,n,s,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,oe.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,this._light.shadowMinZ!==void 0?this._light.shadowMinZ:this._camera.minZ),oe.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,this._light.shadowMaxZ!==void 0?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();oe.Vector3[2].copyFromFloats(oe.Vector3[1].x,oe.Vector3[1].y,oe.Vector3[0].z),oe.Vector3[3].copyFromFloats(oe.Vector3[1].x,oe.Vector3[0].y,oe.Vector3[0].z),oe.Vector3[4].copyFromFloats(oe.Vector3[0].x,oe.Vector3[0].y,oe.Vector3[0].z),oe.Vector3[5].copyFromFloats(oe.Vector3[0].x,oe.Vector3[1].y,oe.Vector3[0].z),O.TransformCoordinatesToRef(oe.Vector3[2],e,oe.Vector3[2]),O.TransformCoordinatesToRef(oe.Vector3[3],e,oe.Vector3[3]),O.TransformCoordinatesToRef(oe.Vector3[4],e,oe.Vector3[4]),O.TransformCoordinatesToRef(oe.Vector3[5],e,oe.Vector3[5]),oe.Vector3[6].copyFromFloats(oe.Vector3[1].x,oe.Vector3[1].y,oe.Vector3[1].z),oe.Vector3[7].copyFromFloats(oe.Vector3[1].x,oe.Vector3[0].y,oe.Vector3[1].z),oe.Vector3[8].copyFromFloats(oe.Vector3[0].x,oe.Vector3[0].y,oe.Vector3[1].z),oe.Vector3[9].copyFromFloats(oe.Vector3[0].x,oe.Vector3[1].y,oe.Vector3[1].z),O.TransformCoordinatesToRef(oe.Vector3[6],e,oe.Vector3[6]),O.TransformCoordinatesToRef(oe.Vector3[7],e,oe.Vector3[7]),O.TransformCoordinatesToRef(oe.Vector3[8],e,oe.Vector3[8]),O.TransformCoordinatesToRef(oe.Vector3[9],e,oe.Vector3[9]),zs("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),zs("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),zs("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),zs("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),zs("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),zs("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),oe.Vector3[2].toArray(this._nearPlaneVertices,0),oe.Vector3[3].toArray(this._nearPlaneVertices,3),oe.Vector3[4].toArray(this._nearPlaneVertices,6),oe.Vector3[5].toArray(this._nearPlaneVertices,9),(t=this._lightHelperFrustumMeshes[6].geometry)==null||t.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),oe.Vector3[6].toArray(this._farPlaneVertices,0),oe.Vector3[7].toArray(this._farPlaneVertices,3),oe.Vector3[8].toArray(this._farPlaneVertices,6),oe.Vector3[9].toArray(this._farPlaneVertices,9),(i=this._lightHelperFrustumMeshes[7].geometry)==null||i.updateVerticesDataDirectly("position",this._farPlaneVertices,0),oe.Vector3[2].toArray(this._rightPlaneVertices,0),oe.Vector3[6].toArray(this._rightPlaneVertices,3),oe.Vector3[7].toArray(this._rightPlaneVertices,6),oe.Vector3[3].toArray(this._rightPlaneVertices,9),(n=this._lightHelperFrustumMeshes[8].geometry)==null||n.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),oe.Vector3[5].toArray(this._leftPlaneVertices,0),oe.Vector3[9].toArray(this._leftPlaneVertices,3),oe.Vector3[8].toArray(this._leftPlaneVertices,6),oe.Vector3[4].toArray(this._leftPlaneVertices,9),(s=this._lightHelperFrustumMeshes[9].geometry)==null||s.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),oe.Vector3[2].toArray(this._topPlaneVertices,0),oe.Vector3[6].toArray(this._topPlaneVertices,3),oe.Vector3[9].toArray(this._topPlaneVertices,6),oe.Vector3[5].toArray(this._topPlaneVertices,9),(a=this._lightHelperFrustumMeshes[10].geometry)==null||a.updateVerticesDataDirectly("position",this._topPlaneVertices,0),oe.Vector3[3].toArray(this._bottomPlaneVertices,0),oe.Vector3[7].toArray(this._bottomPlaneVertices,3),oe.Vector3[8].toArray(this._bottomPlaneVertices,6),oe.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 Yt("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[oe.Vector3[0],oe.Vector3[1],oe.Vector3[2],oe.Vector3[3],oe.Vector3[4]];const e=zs("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[oe.Vector3[5],oe.Vector3[6],oe.Vector3[7],oe.Vector3[8],oe.Vector3[9]];const t=zs("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[oe.Vector3[10],oe.Vector3[11]];const i=zs("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[oe.Vector3[12],oe.Vector3[0]];const n=zs("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[oe.Vector3[1],oe.Vector3[2]];const s=zs("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[oe.Vector3[3],oe.Vector3[4]];const a=zs("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);a.parent=this._rootNode,a.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,n,s,a);const o=(l,c,u)=>{const h=new Re(l+"plane",this._scene),d=new ct(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 vt;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 Pe(1,0,0),this._nearPlaneVertices),o("far",new Pe(.3,0,0),this._farPlaneVertices),o("right",new Pe(0,1,0),this._rightPlaneVertices),o("left",new Pe(0,.3,0),this._leftPlaneVertices),o("top",new Pe(0,0,1),this._topPlaneVertices),o("bottom",new Pe(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=oe.Vector3[2],this._nearLinesPoints[1]=oe.Vector3[3],this._nearLinesPoints[2]=oe.Vector3[4],this._nearLinesPoints[3]=oe.Vector3[5],this._nearLinesPoints[4]=oe.Vector3[2],this._farLinesPoints[0]=oe.Vector3[6],this._farLinesPoints[1]=oe.Vector3[7],this._farLinesPoints[2]=oe.Vector3[8],this._farLinesPoints[3]=oe.Vector3[9],this._farLinesPoints[4]=oe.Vector3[6],this._trLinesPoints[0]=oe.Vector3[2],this._trLinesPoints[1]=oe.Vector3[6],this._brLinesPoints[0]=oe.Vector3[3],this._brLinesPoints[1]=oe.Vector3[7],this._tlLinesPoints[0]=oe.Vector3[4],this._tlLinesPoints[1]=oe.Vector3[8],this._blLinesPoints[0]=oe.Vector3[5],this._blLinesPoints[1]=oe.Vector3[9]}_getInvertViewMatrix(){return pe.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),O.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class Fe{}Fe.AUTOSAMPLERSUFFIX="Sampler";Fe.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";Fe.ALPHA_DISABLE=0;Fe.ALPHA_ADD=1;Fe.ALPHA_COMBINE=2;Fe.ALPHA_SUBTRACT=3;Fe.ALPHA_MULTIPLY=4;Fe.ALPHA_MAXIMIZED=5;Fe.ALPHA_ONEONE=6;Fe.ALPHA_PREMULTIPLIED=7;Fe.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Fe.ALPHA_INTERPOLATE=9;Fe.ALPHA_SCREENMODE=10;Fe.ALPHA_ONEONE_ONEONE=11;Fe.ALPHA_ALPHATOCOLOR=12;Fe.ALPHA_REVERSEONEMINUS=13;Fe.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;Fe.ALPHA_ONEONE_ONEZERO=15;Fe.ALPHA_EXCLUSION=16;Fe.ALPHA_LAYER_ACCUMULATE=17;Fe.ALPHA_EQUATION_ADD=0;Fe.ALPHA_EQUATION_SUBSTRACT=1;Fe.ALPHA_EQUATION_REVERSE_SUBTRACT=2;Fe.ALPHA_EQUATION_MAX=3;Fe.ALPHA_EQUATION_MIN=4;Fe.ALPHA_EQUATION_DARKEN=5;Fe.DELAYLOADSTATE_NONE=0;Fe.DELAYLOADSTATE_LOADED=1;Fe.DELAYLOADSTATE_LOADING=2;Fe.DELAYLOADSTATE_NOTLOADED=4;Fe.NEVER=512;Fe.ALWAYS=519;Fe.LESS=513;Fe.EQUAL=514;Fe.LEQUAL=515;Fe.GREATER=516;Fe.GEQUAL=518;Fe.NOTEQUAL=517;Fe.KEEP=7680;Fe.ZERO=0;Fe.REPLACE=7681;Fe.INCR=7682;Fe.DECR=7683;Fe.INVERT=5386;Fe.INCR_WRAP=34055;Fe.DECR_WRAP=34056;Fe.TEXTURE_CLAMP_ADDRESSMODE=0;Fe.TEXTURE_WRAP_ADDRESSMODE=1;Fe.TEXTURE_MIRROR_ADDRESSMODE=2;Fe.TEXTURE_CREATIONFLAG_STORAGE=1;Fe.TEXTUREFORMAT_ALPHA=0;Fe.TEXTUREFORMAT_LUMINANCE=1;Fe.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Fe.TEXTUREFORMAT_RGB=4;Fe.TEXTUREFORMAT_RGBA=5;Fe.TEXTUREFORMAT_RED=6;Fe.TEXTUREFORMAT_R=6;Fe.TEXTUREFORMAT_RG=7;Fe.TEXTUREFORMAT_RED_INTEGER=8;Fe.TEXTUREFORMAT_R_INTEGER=8;Fe.TEXTUREFORMAT_RG_INTEGER=9;Fe.TEXTUREFORMAT_RGB_INTEGER=10;Fe.TEXTUREFORMAT_RGBA_INTEGER=11;Fe.TEXTUREFORMAT_BGRA=12;Fe.TEXTUREFORMAT_DEPTH24_STENCIL8=13;Fe.TEXTUREFORMAT_DEPTH32_FLOAT=14;Fe.TEXTUREFORMAT_DEPTH16=15;Fe.TEXTUREFORMAT_DEPTH24=16;Fe.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;Fe.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;Fe.TEXTUREFORMAT_STENCIL8=19;Fe.TEXTUREFORMAT_UNDEFINED=4294967295;Fe.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;Fe.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;Fe.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;Fe.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;Fe.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;Fe.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;Fe.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;Fe.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;Fe.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;Fe.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;Fe.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;Fe.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;Fe.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;Fe.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;Fe.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;Fe.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;Fe.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;Fe.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;Fe.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;Fe.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;Fe.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;Fe.TEXTURETYPE_UNSIGNED_BYTE=0;Fe.TEXTURETYPE_UNSIGNED_INT=0;Fe.TEXTURETYPE_FLOAT=1;Fe.TEXTURETYPE_HALF_FLOAT=2;Fe.TEXTURETYPE_BYTE=3;Fe.TEXTURETYPE_SHORT=4;Fe.TEXTURETYPE_UNSIGNED_SHORT=5;Fe.TEXTURETYPE_INT=6;Fe.TEXTURETYPE_UNSIGNED_INTEGER=7;Fe.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Fe.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Fe.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Fe.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Fe.TEXTURETYPE_UNSIGNED_INT_24_8=12;Fe.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Fe.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Fe.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Fe.TEXTURETYPE_UNDEFINED=16;Fe.TEXTURE_2D=3553;Fe.TEXTURE_2D_ARRAY=35866;Fe.TEXTURE_CUBE_MAP=34067;Fe.TEXTURE_CUBE_MAP_ARRAY=3735928559;Fe.TEXTURE_3D=32879;Fe.TEXTURE_NEAREST_SAMPLINGMODE=1;Fe.TEXTURE_NEAREST_NEAREST=1;Fe.TEXTURE_BILINEAR_SAMPLINGMODE=2;Fe.TEXTURE_LINEAR_LINEAR=2;Fe.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Fe.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Fe.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Fe.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Fe.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Fe.TEXTURE_NEAREST_LINEAR=7;Fe.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Fe.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Fe.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Fe.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Fe.TEXTURE_LINEAR_NEAREST=12;Fe.TEXTURE_EXPLICIT_MODE=0;Fe.TEXTURE_SPHERICAL_MODE=1;Fe.TEXTURE_PLANAR_MODE=2;Fe.TEXTURE_CUBIC_MODE=3;Fe.TEXTURE_PROJECTION_MODE=4;Fe.TEXTURE_SKYBOX_MODE=5;Fe.TEXTURE_INVCUBIC_MODE=6;Fe.TEXTURE_EQUIRECTANGULAR_MODE=7;Fe.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Fe.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Fe.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;Fe.TEXTURE_FILTERING_QUALITY_HIGH=64;Fe.TEXTURE_FILTERING_QUALITY_MEDIUM=16;Fe.TEXTURE_FILTERING_QUALITY_LOW=8;Fe.SCALEMODE_FLOOR=1;Fe.SCALEMODE_NEAREST=2;Fe.SCALEMODE_CEILING=3;Fe.MATERIAL_TextureDirtyFlag=1;Fe.MATERIAL_LightDirtyFlag=2;Fe.MATERIAL_FresnelDirtyFlag=4;Fe.MATERIAL_AttributesDirtyFlag=8;Fe.MATERIAL_MiscDirtyFlag=16;Fe.MATERIAL_PrePassDirtyFlag=32;Fe.MATERIAL_AllDirtyFlag=63;Fe.MATERIAL_TriangleFillMode=0;Fe.MATERIAL_WireFrameFillMode=1;Fe.MATERIAL_PointFillMode=2;Fe.MATERIAL_PointListDrawMode=3;Fe.MATERIAL_LineListDrawMode=4;Fe.MATERIAL_LineLoopDrawMode=5;Fe.MATERIAL_LineStripDrawMode=6;Fe.MATERIAL_TriangleStripDrawMode=7;Fe.MATERIAL_TriangleFanDrawMode=8;Fe.MATERIAL_ClockWiseSideOrientation=0;Fe.MATERIAL_CounterClockWiseSideOrientation=1;Fe.ACTION_NothingTrigger=0;Fe.ACTION_OnPickTrigger=1;Fe.ACTION_OnLeftPickTrigger=2;Fe.ACTION_OnRightPickTrigger=3;Fe.ACTION_OnCenterPickTrigger=4;Fe.ACTION_OnPickDownTrigger=5;Fe.ACTION_OnDoublePickTrigger=6;Fe.ACTION_OnPickUpTrigger=7;Fe.ACTION_OnPickOutTrigger=16;Fe.ACTION_OnLongPressTrigger=8;Fe.ACTION_OnPointerOverTrigger=9;Fe.ACTION_OnPointerOutTrigger=10;Fe.ACTION_OnEveryFrameTrigger=11;Fe.ACTION_OnIntersectionEnterTrigger=12;Fe.ACTION_OnIntersectionExitTrigger=13;Fe.ACTION_OnKeyDownTrigger=14;Fe.ACTION_OnKeyUpTrigger=15;Fe.PARTICLES_BILLBOARDMODE_Y=2;Fe.PARTICLES_BILLBOARDMODE_ALL=7;Fe.PARTICLES_BILLBOARDMODE_STRETCHED=8;Fe.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;Fe.MESHES_CULLINGSTRATEGY_STANDARD=0;Fe.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Fe.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Fe.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;Fe.SCENELOADER_NO_LOGGING=0;Fe.SCENELOADER_MINIMAL_LOGGING=1;Fe.SCENELOADER_SUMMARY_LOGGING=2;Fe.SCENELOADER_DETAILED_LOGGING=3;Fe.PREPASS_IRRADIANCE_TEXTURE_TYPE=0;Fe.PREPASS_POSITION_TEXTURE_TYPE=1;Fe.PREPASS_VELOCITY_TEXTURE_TYPE=2;Fe.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;Fe.PREPASS_COLOR_TEXTURE_TYPE=4;Fe.PREPASS_DEPTH_TEXTURE_TYPE=5;Fe.PREPASS_NORMAL_TEXTURE_TYPE=6;Fe.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;Fe.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8;Fe.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9;Fe.PREPASS_NDC_DEPTH_TEXTURE_TYPE=10;Fe.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11;Fe.BUFFER_CREATIONFLAG_READ=1;Fe.BUFFER_CREATIONFLAG_WRITE=2;Fe.BUFFER_CREATIONFLAG_READWRITE=3;Fe.BUFFER_CREATIONFLAG_UNIFORM=4;Fe.BUFFER_CREATIONFLAG_VERTEX=8;Fe.BUFFER_CREATIONFLAG_INDEX=16;Fe.BUFFER_CREATIONFLAG_STORAGE=32;Fe.BUFFER_CREATIONFLAG_INDIRECT=64;Fe.RENDERPASS_MAIN=0;Fe.INPUT_ALT_KEY=18;Fe.INPUT_CTRL_KEY=17;Fe.INPUT_META_KEY1=91;Fe.INPUT_META_KEY2=92;Fe.INPUT_META_KEY3=93;Fe.INPUT_SHIFT_KEY=16;Fe.SNAPSHOTRENDERING_STANDARD=0;Fe.SNAPSHOTRENDERING_FAST=1;Fe.PERSPECTIVE_CAMERA=0;Fe.ORTHOGRAPHIC_CAMERA=1;Fe.FOVMODE_VERTICAL_FIXED=0;Fe.FOVMODE_HORIZONTAL_FIXED=1;Fe.RIG_MODE_NONE=0;Fe.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Fe.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Fe.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Fe.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Fe.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Fe.RIG_MODE_VR=20;Fe.RIG_MODE_CUSTOM=22;Fe.MAX_SUPPORTED_UV_SETS=6;Fe.GL_ALPHA_EQUATION_ADD=32774;Fe.GL_ALPHA_EQUATION_MIN=32775;Fe.GL_ALPHA_EQUATION_MAX=32776;Fe.GL_ALPHA_EQUATION_SUBTRACT=32778;Fe.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;Fe.GL_ALPHA_FUNCTION_SRC=768;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;Fe.GL_ALPHA_FUNCTION_SRC_ALPHA=770;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;Fe.GL_ALPHA_FUNCTION_DST_ALPHA=772;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;Fe.GL_ALPHA_FUNCTION_DST_COLOR=774;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;Fe.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;Fe.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;Fe.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;Fe.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;Fe.SnippetUrl="https://snippet.babylonjs.com";Fe.FOGMODE_NONE=0;Fe.FOGMODE_EXP=1;Fe.FOGMODE_EXP2=2;Fe.FOGMODE_LINEAR=3;Fe.BYTE=5120;Fe.UNSIGNED_BYTE=5121;Fe.SHORT=5122;Fe.UNSIGNED_SHORT=5123;Fe.INT=5124;Fe.UNSIGNED_INT=5125;Fe.FLOAT=5126;Fe.PositionKind="position";Fe.NormalKind="normal";Fe.TangentKind="tangent";Fe.UVKind="uv";Fe.UV2Kind="uv2";Fe.UV3Kind="uv3";Fe.UV4Kind="uv4";Fe.UV5Kind="uv5";Fe.UV6Kind="uv6";Fe.ColorKind="color";Fe.ColorInstanceKind="instanceColor";Fe.MatricesIndicesKind="matricesIndices";Fe.MatricesWeightsKind="matricesWeights";Fe.MatricesIndicesExtraKind="matricesIndicesExtra";Fe.MatricesWeightsExtraKind="matricesWeightsExtra";class qke{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class Jke extends Vt{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new qke){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,jl.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,supportIBLShadows:!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),ge.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 mg;return t.references=1,t}createIndexBuffer(e){const t=new mg;return t.references=1,t}clear(e,t,i,n=!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,n,s){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=e!==null&&kJ(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,n=!1,s,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,n){return!0}setBool(e,t){return!0}setFloat4(e,t,i,n,s){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,n){}drawElementsType(e,t,i,n){}drawArraysType(e,t,i,n){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,n,s=3,a=null,o=null,l=null,c=null,u=null,h=null,d){const f=new _n(this,1),p=String(e);return f.url=p,f.generateMipMaps=!t,f.samplingMode=s,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 n=new Kz(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),n={};t!==void 0&&typeof t=="object"?(n.generateMipMaps=t.generateMipMaps,n.generateDepthBuffer=t.generateDepthBuffer===void 0?!0:t.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&t.generateStencilBuffer,n.type=t.type===void 0?0:t.type,n.samplingMode=t.samplingMode===void 0?3:t.samplingMode):(n.generateMipMaps=t,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.type=0,n.samplingMode=3);const s=new _n(this,5),a=e.width||e,o=e.height||e;return i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=!!n.generateStencilBuffer,s.baseWidth=a,s.baseHeight=o,s.width=a,s.height=o,s.isReady=!0,s.samples=1,s.generateMipMaps=!!n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,this._internalTexturesCache.push(s),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(n.type===1&&!this._caps.textureFloatLinearFiltering||n.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(n.samplingMode=1),i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=!!n.generateStencilBuffer;const s=new _n(this,5);return s.baseWidth=e,s.baseHeight=e,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=!!n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,this._internalTexturesCache.push(s),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,n,s,a,o,l=null,c=0,u=0,h=!1){const d=new _n(this,3);return d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=n,d.generateMipMaps=s,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,n,s=null,a=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s,e.type=a,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,n,s){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!s&&this.setViewport(this._cachedViewport,i,n)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new mg;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,n=!1,s){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,n){}_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,n,s,a=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,n=0){}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){}_uploadImageToTexture(e,t,i=0,n=0){}}Qe.prototype._partialLoadFile=function(r,e,t,i,n=null){const s=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,l)=>{n&&o&&n(o.status+" "+o.statusText,l)};this._loadFile(r,s,void 0,void 0,!0,a)};Qe.prototype._cascadeLoadFiles=function(r,e,t,i=null){const n=[];n._internalCount=0;for(let s=0;s<6;s++)this._partialLoadFile(t[s],s,n,e,i)};Qe.prototype._cascadeLoadImgs=function(r,e,t,i,n=null,s){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,r,e,t,n,s)};Qe.prototype._partialLoadImg=function(r,e,t,i,n,s,a=null,o){const l=Xh();qw(r,h=>{t[e]=h,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&s&&s(n,t)},(h,d)=>{i&&i.removePendingData(l),a&&a(h,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};Qe.prototype.createCubeTextureBase=function(r,e,t,i,n=null,s=null,a,o=null,l=!1,c=0,u=0,h=null,d=null,f=null,p=!1,g=null){const m=h||new _n(this,7);m.isCube=!0,m.url=r,m.generateMipMaps=!i,m._lodGenerationScale=c,m._lodGenerationOffset=u,m._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),m!==h&&(m.label=r.substring(0,60)),this._doNotHandleContextLost||(m._extension=o,m._files=t,m._buffer=g);const _=r;this._transformTextureUrl&&!h&&(r=this._transformTextureUrl(r));const y=r.split("?")[0],v=y.lastIndexOf("."),x=o||(v>-1?y.substring(v).toLowerCase():""),b=LJ(x),C=(A,E)=>{r===_?s&&A&&s(A.status+" "+A.statusText,E):(ge.Warn(`Failed to load ${r}, falling back to the ${_}`),this.createCubeTextureBase(_,e,t,!!i,n,s,a,o,l,c,u,m,d,f,p,g))};if(b)b.then(A=>{const E=P=>{d&&d(m,P),A.loadCubeData(P,m,l,n,s)};g?E(g):t&&t.length===6?A.supportCascades?this._cascadeLoadFiles(e,P=>E(P.map(w=>new Uint8Array(w))),t,s):s?s("Textures type does not support cascades."):ge.Warn("Texture loader does not support cascades."):this._loadFile(r,P=>E(new Uint8Array(P)),void 0,void 0,!0,C)});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,m,(A,E)=>{f&&f(A,E)},t,s)}return this._internalTexturesCache.push(m),m};class eUe{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=vr.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=vr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}Qe.prototype.getGPUFrameTimeCounter=function(){return null};Qe.prototype.captureGPUFrameTime=function(r){};Qe.prototype.createQuery=function(){return null};Qe.prototype.deleteQuery=function(r){return this};Qe.prototype.isQueryResultAvailable=function(r){return!1};Qe.prototype.getQueryResult=function(r){return 0};Qe.prototype.beginOcclusionQuery=function(r,e){return!1};Qe.prototype.endOcclusionQuery=function(r){return this};Object.defineProperty(vr.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(r){this._occlusionDataStorage.isOcclusionQueryInProgress=r},enumerable:!1,configurable:!0});Object.defineProperty(vr.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new eUe),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(vr.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(r){this._occlusionDataStorage.isOccluded=r},enumerable:!0,configurable:!0});Object.defineProperty(vr.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(r){this._occlusionDataStorage.occlusionQueryAlgorithmType=r},enumerable:!0,configurable:!0});Object.defineProperty(vr.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(r){this._occlusionDataStorage.occlusionType=r},enumerable:!0,configurable:!0});Object.defineProperty(vr.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(r){this._occlusionDataStorage.occlusionRetryCount=r},enumerable:!0,configurable:!0});Object.defineProperty(vr.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(r){this._occlusionDataStorage.forceRenderingWhenOccluded=r},enumerable:!0,configurable:!0});vr.prototype._checkOcclusionQuery=function(){const r=this._occlusionDataStorage;if(r.occlusionType===vr.OCCLUSION_TYPE_NONE)return r.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return r.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const n=e.getQueryResult(this._occlusionQuery);r.isOcclusionQueryInProgress=!1,r.occlusionInternalRetryCounter=0,r.isOccluded=!(n>0)}else if(r.occlusionInternalRetryCounter++,r.occlusionRetryCount!==-1&&r.occlusionInternalRetryCounter>r.occlusionRetryCount)r.isOcclusionQueryInProgress=!1,r.occlusionInternalRetryCounter=0,r.isOccluded=r.occlusionType===vr.OCCLUSION_TYPE_OPTIMISTIC?!1:r.isOccluded;else return r.occlusionType===vr.OCCLUSION_TYPE_OPTIMISTIC?!1:r.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),this._occlusionQuery&&e.beginOcclusionQuery(r.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(r.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return r.isOccluded};class k4t{}const tUe=new Ce,iUe=new Ce;Object.defineProperty(Qe.prototype,"onBeforeViewRenderObservable",{get:function(){return tUe}});Object.defineProperty(Qe.prototype,"onAfterViewRenderObservable",{get:function(){return iUe}});Object.defineProperty(Qe.prototype,"inputElement",{get:function(){return this._inputElement},set:function(r){var e;this._inputElement!==r&&(this._inputElement=r,(e=this._onEngineViewChanged)==null||e.call(this))}});Qe.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()};Qe.prototype.registerView=function(r,e,t){this.views||(this.views=[]);for(const s of this.views)if(s.target===r)return s;const i=this.getRenderingCanvas();i&&(r.width=i.width,r.height=i.height);const n={target:r,camera:e,clearBeforeCopy:t,enabled:!0,id:(Math.random()*1e5).toFixed()};return this.views.push(n),e&&!Array.isArray(e)&&e.onDisposeObservable.add(()=>{this.unRegisterView(r)}),n};Qe.prototype.unRegisterView=function(r){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===r){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};Qe.prototype._renderViewStep=function(r){const e=r.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();tUe.notifyObservers(r);const n=r.camera;let s=null,a=null,o=null;if(n&&(o=Array.isArray(n)?n[0].getScene():n.getScene(),s=o.activeCamera,a=o.activeCameras,Array.isArray(n)?o.activeCameras=n:(o.activeCamera=n,o.activeCameras=null)),this.activeView=r,r.customResize)r.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(),r.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),o&&(o.activeCameras=a,o.activeCamera=s),iUe.notifyObservers(r),!0)};Qe.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)};Qe.prototype._debugPushGroup=function(r,e){};Qe.prototype._debugPopGroup=function(r){};Qe.prototype._debugInsertMarker=function(r,e){};Qe.prototype._debugFlushPendingCommands=function(){};class rUe{constructor(){this._timeElapsedQueryEnded=!1}}Vt.prototype.createQuery=function(){const r=this._gl.createQuery();if(!r)throw new Error("Unable to create Occlusion Query");return r};Vt.prototype.deleteQuery=function(r){return this._gl.deleteQuery(r),this};Vt.prototype.isQueryResultAvailable=function(r){return this._gl.getQueryParameter(r,this._gl.QUERY_RESULT_AVAILABLE)};Vt.prototype.getQueryResult=function(r){return this._gl.getQueryParameter(r,this._gl.QUERY_RESULT)};Vt.prototype.beginOcclusionQuery=function(r,e){const t=this._getGlAlgorithmType(r);return this._gl.beginQuery(t,e),!0};Vt.prototype.endOcclusionQuery=function(r){const e=this._getGlAlgorithmType(r);return this._gl.endQuery(e),this};Vt.prototype._createTimeQuery=function(){const r=this.getCaps().timerQuery;return r.createQueryEXT?r.createQueryEXT():this.createQuery()};Vt.prototype._deleteTimeQuery=function(r){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(r);return}this.deleteQuery(r)};Vt.prototype._getTimeQueryResult=function(r){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(r,e.QUERY_RESULT_EXT):this.getQueryResult(r)};Vt.prototype._getTimeQueryAvailability=function(r){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(r,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(r)};Vt.prototype.startTimeQuery=function(){const r=this.getCaps(),e=r.timerQuery;if(!e)return null;const t=new rUe;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),r.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(r){const e=this.getCaps(),t=e.timerQuery;if(!t||!r)return-1;if(e.canUseTimestampForTimerQuery){if(!r._startTimeQuery)return-1;r._endTimeQuery||(r._endTimeQuery=this._createTimeQuery(),r._endTimeQuery&&t.queryCounterEXT(r._endTimeQuery,t.TIMESTAMP_EXT))}else if(!r._timeElapsedQueryEnded){if(!r._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),r._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let n=!1;if(r._endTimeQuery?n=this._getTimeQueryAvailability(r._endTimeQuery):r._timeElapsedQuery&&(n=this._getTimeQueryAvailability(r._timeElapsedQuery)),n&&!i){let s=0;if(e.canUseTimestampForTimerQuery){if(!r._startTimeQuery||!r._endTimeQuery)return-1;const a=this._getTimeQueryResult(r._startTimeQuery);s=this._getTimeQueryResult(r._endTimeQuery)-a,this._deleteTimeQuery(r._startTimeQuery),this._deleteTimeQuery(r._endTimeQuery),r._startTimeQuery=null,r._endTimeQuery=null}else{if(!r._timeElapsedQuery)return-1;s=this._getTimeQueryResult(r._timeElapsedQuery),this._deleteTimeQuery(r._timeElapsedQuery),r._timeElapsedQuery=null,r._timeElapsedQueryEnded=!1}return s}return-1};Vt.prototype._captureGPUFrameTime=!1;Vt.prototype._gpuFrameTime=new zo;Vt.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};Vt.prototype.captureGPUFrameTime=function(r){r!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=r,r?(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(r){return r===vr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var U4t=!0;Vt.prototype.createTransformFeedback=function(){const r=this._gl.createTransformFeedback();if(!r)throw new Error("Unable to create Transform Feedback");return r};Vt.prototype.deleteTransformFeedback=function(r){this._gl.deleteTransformFeedback(r)};Vt.prototype.bindTransformFeedback=function(r){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,r)};Vt.prototype.beginTransformFeedback=function(r=!0){this._gl.beginTransformFeedback(r?this._gl.POINTS:this._gl.TRIANGLES)};Vt.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};Vt.prototype.setTranformFeedbackVaryings=function(r,e){this._gl.transformFeedbackVaryings(r,e,this._gl.INTERLEAVED_ATTRIBS)};Vt.prototype.bindTransformFeedbackBuffer=function(r){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,r?r.underlyingResource:null)};Vt.prototype.readTransformFeedbackBuffer=function(r){this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,r)};ir.prototype.updateVideoTexture=function(r,e,t){if(!r||r._isDisabled)return;const i=this._getInternalFormat(r.format),n=this._getRGBABufferInternalSizedFormat(0,r.format),s=this._bindTextureDirectly(this._gl.TEXTURE_2D,r,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,n,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,n,i,this._gl.UNSIGNED_BYTE,e);else{if(!r._workingCanvas){r._workingCanvas=this.createCanvas(r.width,r.height);const a=r._workingCanvas.getContext("2d");if(!a)throw new Error("Unable to get 2d context");r._workingContext=a,r._workingCanvas.width=r.width,r._workingCanvas.height=r.height}r._workingContext.clearRect(0,0,r.width,r.height),r._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,r.width,r.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,n,i,this._gl.UNSIGNED_BYTE,r._workingCanvas)}r.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),s||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),r.isReady=!0}catch{r._isDisabled=!0}};ir.prototype.restoreSingleAttachment=function(){const r=this._gl;this.bindAttachments([r.BACK])};ir.prototype.restoreSingleAttachmentForRenderTarget=function(){const r=this._gl;this.bindAttachments([r.COLOR_ATTACHMENT0])};ir.prototype.buildTextureLayout=function(r){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],i.readBuffer(n[a]),i.drawBuffers(n),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(n)}for(let a=0;a1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),C.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const A=this._gl,E=A.createFramebuffer();this._bindUnboundFramebuffer(E);const P=r.width||r,w=r.height||r,M=[],R=[],I=this.webGLVersion>1&&a&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),D=this._setupFramebufferDepthAttachments(!I&&s,!a&&n,P,w);C._framebuffer=E,C._depthStencilBuffer=D,C._generateDepthBuffer=!a&&n,C._generateStencilBuffer=!I&&s,C._attachments=R;for(let k=0;k1||this.isWebGPU);const Y=this.webGLVersion>1,Z=A[Y?"COLOR_ATTACHMENT"+k:"COLOR_ATTACHMENT"+k+"_WEBGL"];if(R.push(Z),j===-1)continue;const te=new _n(this,6);M[k]=te,A.activeTexture(A["TEXTURE"+k]),A.bindTexture(j,te._hardwareTexture.underlyingResource),A.texParameteri(j,A.TEXTURE_MAG_FILTER,G.mag),A.texParameteri(j,A.TEXTURE_MIN_FILTER,G.min),A.texParameteri(j,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(j,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE);const le=this._getRGBABufferInternalSizedFormat(W,U,K),ce=this._getInternalFormat(U),ue=this._getWebGLTextureType(W);if(Y&&(j===35866||j===32879))j===35866?te.is2DArray=!0:te.is3D=!0,te.baseDepth=te.depth=B,A.texImage3D(j,0,le,P,w,B,0,ce,ue,null);else if(j===34067){for(let N=0;N<6;N++)A.texImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+N,0,le,P,w,0,ce,ue,null);te.isCube=!0}else A.texImage2D(A.TEXTURE_2D,0,le,P,w,0,ce,ue,null);i&&A.generateMipmap(j),this._bindTextureDirectly(j,null),te.baseWidth=P,te.baseHeight=w,te.width=P,te.height=w,te.isReady=!0,te.samples=1,te.generateMipMaps=i,te.samplingMode=z,te.type=W,te._useSRGBBuffer=K,te.format=U,this._internalTexturesCache.push(te)}if(a&&this._caps.depthTextureExtension){const k=new _n(this,14);let z=5,W=A.DEPTH_COMPONENT16,K=A.DEPTH_COMPONENT,U=A.UNSIGNED_SHORT,j=A.DEPTH_ATTACHMENT;this.webGLVersion<2?W=A.DEPTH_COMPONENT:o===14?(z=1,U=A.FLOAT,W=A.DEPTH_COMPONENT32F):o===18?(z=0,U=A.FLOAT_32_UNSIGNED_INT_24_8_REV,W=A.DEPTH32F_STENCIL8,K=A.DEPTH_STENCIL,j=A.DEPTH_STENCIL_ATTACHMENT):o===16?(z=0,U=A.UNSIGNED_INT,W=A.DEPTH_COMPONENT24,j=A.DEPTH_ATTACHMENT):(o===13||o===17)&&(z=12,U=A.UNSIGNED_INT_24_8,W=A.DEPTH24_STENCIL8,K=A.DEPTH_STENCIL,j=A.DEPTH_STENCIL_ATTACHMENT),A.activeTexture(A.TEXTURE0),A.bindTexture(A.TEXTURE_2D,k._hardwareTexture.underlyingResource),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE),A.texImage2D(A.TEXTURE_2D,0,W,P,w,0,K,U,null),A.framebufferTexture2D(A.FRAMEBUFFER,j,A.TEXTURE_2D,k._hardwareTexture.underlyingResource,0),k.baseWidth=P,k.baseHeight=w,k.width=P,k.height=w,k.isReady=!0,k.samples=1,k.generateMipMaps=i,k.samplingMode=1,k.format=o,k.type=z,M[l]=k,this._internalTexturesCache.push(k)}return C.setTextures(M),t&&A.drawBuffers(R),this._bindUnboundFramebuffer(null),C.setLayerAndFaceIndices(x,v),this.resetTextureCache(),C};ir.prototype.updateMultipleRenderTargetTextureSampleCount=function(r,e,t=!0){if(this.webGLVersion<2||!r||!r.texture)return 1;if(r.samples===e)return e;const i=r._attachments.length;if(i===0)return 1;const n=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const s=!!r._depthStencilBuffer;if(s&&(n.deleteRenderbuffer(r._depthStencilBuffer),r._depthStencilBuffer=null),r._MSAAFramebuffer&&(n.deleteFramebuffer(r._MSAAFramebuffer),r._MSAAFramebuffer=null),e>1&&typeof n.renderbufferStorageMultisample=="function"){const a=n.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");r._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&&n.drawBuffers(o)}else this._bindUnboundFramebuffer(r._framebuffer);return s&&(r._depthStencilBuffer=this._setupFramebufferDepthAttachments(r._generateStencilBuffer,r._generateDepthBuffer,r.texture.width,r.texture.height,e)),this._bindUnboundFramebuffer(null),e};ir.prototype._createDepthStencilCubeTexture=function(r,e){const t=new _n(this,12);if(t.isCube=!0,this.webGLVersion===1)return ge.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,r,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let s=0;s<6;s++)i.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,n.DEPTH24_STENCIL8,r,r,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,n.DEPTH_COMPONENT24,r,r,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};ir.prototype._setCubeMapTextureParams=function(r,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),r.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),r._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};ir.prototype.createCubeTexture=function(r,e,t,i,n=null,s=null,a,o=null,l=!1,c=0,u=0,h=null,d,f=!1,p=null){const g=this._gl;return this.createCubeTextureBase(r,e,t,!!i,n,s,a,o,l,c,u,h,m=>this._bindTextureDirectly(g.TEXTURE_CUBE_MAP,m,!0),(m,_)=>{const y=this.needPOTTextures?Ld(_[0].width,this._caps.maxCubemapTextureSize):_[0].width,v=y,x=[g.TEXTURE_CUBE_MAP_POSITIVE_X,g.TEXTURE_CUBE_MAP_POSITIVE_Y,g.TEXTURE_CUBE_MAP_POSITIVE_Z,g.TEXTURE_CUBE_MAP_NEGATIVE_X,g.TEXTURE_CUBE_MAP_NEGATIVE_Y,g.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(g.TEXTURE_CUBE_MAP,m,!0),this._unpackFlipY(!1);const b=a?this._getInternalFormat(a,m._useSRGBBuffer):m._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:g.RGBA;let C=a?this._getInternalFormat(a):g.RGBA;m._useSRGBBuffer&&this.webGLVersion===1&&(C=b);for(let A=0;A1,r=>r.y,r=>r.z,r=>r.x,r=>r.x*r.y,r=>r.y*r.z,r=>3*r.z*r.z-1,r=>r.x*r.z,r=>r.x*r.x-r.y*r.y],iv=(r,e)=>k1[r]*z4t[r](e),rv=[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 Ux{constructor(){this.preScaled=!1,this.l00=O.Zero(),this.l1_1=O.Zero(),this.l10=O.Zero(),this.l11=O.Zero(),this.l2_2=O.Zero(),this.l2_1=O.Zero(),this.l20=O.Zero(),this.l21=O.Zero(),this.l22=O.Zero()}addLight(e,t,i){oe.Vector3[0].set(t.r,t.g,t.b);const n=oe.Vector3[0],s=oe.Vector3[1];n.scaleToRef(i,s),s.scaleToRef(iv(0,e),oe.Vector3[2]),this.l00.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(1,e),oe.Vector3[2]),this.l1_1.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(2,e),oe.Vector3[2]),this.l10.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(3,e),oe.Vector3[2]),this.l11.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(4,e),oe.Vector3[2]),this.l2_2.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(5,e),oe.Vector3[2]),this.l2_1.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(6,e),oe.Vector3[2]),this.l20.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(7,e),oe.Vector3[2]),this.l21.addInPlace(oe.Vector3[2]),s.scaleToRef(iv(8,e),oe.Vector3[2]),this.l22.addInPlace(oe.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(rv[0]),this.l1_1.scaleInPlace(rv[1]),this.l10.scaleInPlace(rv[2]),this.l11.scaleInPlace(rv[3]),this.l2_2.scaleInPlace(rv[4]),this.l2_1.scaleInPlace(rv[5]),this.l20.scaleInPlace(rv[6]),this.l21.scaleInPlace(rv[7]),this.l22.scaleInPlace(rv[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(k1[0]),this.l1_1.scaleInPlace(k1[1]),this.l10.scaleInPlace(k1[2]),this.l11.scaleInPlace(k1[3]),this.l2_2.scaleInPlace(k1[4]),this.l2_1.scaleInPlace(k1[5]),this.l20.scaleInPlace(k1[6]),this.l21.scaleInPlace(k1[7]),this.l22.scaleInPlace(k1[8])}updateFromArray(e){return O.FromArrayToRef(e[0],0,this.l00),O.FromArrayToRef(e[1],0,this.l1_1),O.FromArrayToRef(e[2],0,this.l10),O.FromArrayToRef(e[3],0,this.l11),O.FromArrayToRef(e[4],0,this.l2_2),O.FromArrayToRef(e[5],0,this.l2_1),O.FromArrayToRef(e[6],0,this.l20),O.FromArrayToRef(e[7],0,this.l21),O.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return O.FromFloatsToRef(e[0],e[1],e[2],this.l00),O.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),O.FromFloatsToRef(e[6],e[7],e[8],this.l10),O.FromFloatsToRef(e[9],e[10],e[11],this.l11),O.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),O.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),O.FromFloatsToRef(e[18],e[19],e[20],this.l20),O.FromFloatsToRef(e[21],e[22],e[23],this.l21),O.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new Ux().updateFromArray(e)}static FromPolynomial(e){const t=new Ux;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 wg{constructor(){this.x=O.Zero(),this.y=O.Zero(),this.z=O.Zero(),this.xx=O.Zero(),this.yy=O.Zero(),this.zz=O.Zero(),this.xy=O.Zero(),this.yz=O.Zero(),this.zx=O.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Ux.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){oe.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=oe.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),oe.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),oe.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(oe.Vector3[0]).addInPlace(oe.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(oe.Vector3[0]).subtractInPlace(oe.Vector3[1]),this.zz.copyFrom(e.l00),oe.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(oe.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 wg().updateFromHarmonics(e)}static FromArray(e){const t=new wg;return O.FromArrayToRef(e[0],0,t.x),O.FromArrayToRef(e[1],0,t.y),O.FromArrayToRef(e[2],0,t.z),O.FromArrayToRef(e[3],0,t.xx),O.FromArrayToRef(e[4],0,t.yy),O.FromArrayToRef(e[5],0,t.zz),O.FromArrayToRef(e[6],0,t.yz),O.FromArrayToRef(e[7],0,t.zx),O.FromArrayToRef(e[8],0,t.xy),t}}class wI{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}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),n=e.readPixels(1,void 0,void 0,!1);let s,a;e.isRenderTarget?(s=e.readPixels(3,void 0,void 0,!1),a=e.readPixels(2,void 0,void 0,!1)):(s=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([n,i,s,a,o,l]).then(([p,g,m,_,y,v])=>{const x={size:t,right:g,left:p,up:m,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 Ux;let i=0;const n=2/e.size,s=n,a=.5*n,o=a-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],p=e[f.name];let g=o;const m=e.format===5?4:3;for(let _=0;_P){const R=P/M;C*=R,A*=R,E*=R}}else C=Xt.Clamp(C,0,P),A=Xt.Clamp(A,0,P),E=Xt.Clamp(E,0,P);const w=new Pe(C,A,E);t.addLight(x,w,b),i+=b,y+=n}g+=s}}const h=4*Math.PI*6/6/i;return t.scaleInPlace(h),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),wg.FromHarmonics(t)}}oT._FileFaces=[new wI("right",new O(1,0,0),new O(0,0,-1),new O(0,-1,0)),new wI("left",new O(-1,0,0),new O(0,0,1),new O(0,-1,0)),new wI("up",new O(0,1,0),new O(1,0,0),new O(0,0,1)),new wI("down",new O(0,-1,0),new O(1,0,0),new O(0,0,-1)),new wI("front",new O(0,0,1),new O(1,0,0),new O(0,-1,0)),new wI("back",new O(0,0,-1),new O(-1,0,0),new O(0,-1,0))];oT.MAX_HDRI_VALUE=4096;oT.PRESERVE_CLAMPED_COLORS=!1;const V4t="lodPixelShader",G4t=`#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));}} `;me.ShadersStore[V4t]=G4t;const W4t="lodCubePixelShader",K4t=`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));}} `;me.ShadersStore[W4t]=K4t;function nUe(r,e,t,i=!0){const n=r.getScene(),s=n.getEngine(),a=new vn("resized"+r.name,{width:e,height:t},n,!r.noMipmap,!0,r._texture.type,!1,r.samplingMode,!1);a.wrapU=r.wrapU,a.wrapV=r.wrapV,a.uOffset=r.uOffset,a.vOffset=r.vOffset,a.uScale=r.uScale,a.vScale=r.vScale,a.uAng=r.uAng,a.vAng=r.vAng,a.wAng=r.wAng,a.coordinatesIndex=r.coordinatesIndex,a.level=r.level,a.anisotropicFilteringLevel=r.anisotropicFilteringLevel,a._texture.isReady=!1,r.wrapU=be.CLAMP_ADDRESSMODE,r.wrapV=be.CLAMP_ADDRESSMODE;const o=new J0("pass",1,null,i?be.BILINEAR_SAMPLINGMODE:be.NEAREST_SAMPLINGMODE,s,!1,0);return o.externalTextureSamplerBinding=!0,o.onEffectCreatedObservable.addOnce(l=>{l.executeWhenCompiled(()=>{o.onApply=function(u){u.setTexture("textureSampler",r)};const c=a.renderTarget;c&&(n.postProcessManager.directRender([o],c),s.unBindFramebuffer(c),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)})}),a}function vee(r,e,t,i,n,s,a,o){const l=e.getEngine();return e.isReady=!1,n=n??e.samplingMode,i=i??e.type,s=s??e.format,a=a??e.width,o=o??e.height,i===-1&&(i=0),new Promise(c=>{const u=new ii("postprocess",r,null,null,1,null,n,l,!1,void 0,i,void 0,null,!1,s);u.externalTextureSamplerBinding=!0;const h=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:n,type:i,format:s});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 pX,MMe;function tg(r){pX||(pX=new Float32Array(1),MMe=new Int32Array(pX.buffer)),pX[0]=r;const e=MMe[0];let t=e>>16&32768,i=e>>12&2047;const n=e>>23&255;return n<103?t:n>142?(t|=31744,t|=(n==255?0:1)&&e&8388607,t):n<113?(i|=2048,t|=(i>>114-n)+(i>>113-n&1),t):(t|=n-112<<10|i>>1,t+=i&1,t)}function jm(r){const e=(r&32768)>>15,t=(r&31744)>>10,i=r&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 H4t=async(r,e,t,i,n)=>{const s=r.getScene(),a=s.getEngine();let o;if(!r.isCube)o=new ii("lod","lod",["lod","gamma"],null,1,null,be.NEAREST_NEAREST_MIPNEAREST,a);else{const u=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];o=new ii("lodCube","lodCube",["lod","gamma"],null,1,null,be.NEAREST_NEAREST_MIPNEAREST,a,!1,u[i])}await new Promise(u=>{o.onEffectCreatedObservable.addOnce(h=>{h.executeWhenCompiled(()=>{u(0)})})});const l=new vn("temp",{width:e,height:t},s,!1);o.onApply=function(u){u.setTexture("textureSampler",r),u.setFloat("lod",n),u.setBool("gamma",r.gammaSpace)};const c=r.getInternalTexture();try{if(l.renderTarget&&c){const u=c.samplingMode;n!==0?r.updateSamplingMode(be.NEAREST_NEAREST_MIPNEAREST):r.updateSamplingMode(be.NEAREST_NEAREST),s.postProcessManager.directRender([o],l.renderTarget,!0),r.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 sUe(r,e,t,i=0,n=0){return!r.isReady()&&r._texture&&await new Promise((s,a)=>{if(r._texture===null){a(0);return}r._texture.onLoadedObservable.addOnce(()=>{s(0)})}),await H4t(r,e,t,i,n)}const aUe={CreateResizedCopy:nUe,ApplyPostProcess:vee,ToHalfFloat:tg,FromHalfFloat:jm,GetTextureDataAsync:sUe},j4t=542327876,RMe=131072,IMe=512,PMe=4,wMe=64,DMe=131072;function yee(r){return r.charCodeAt(0)+(r.charCodeAt(1)<<8)+(r.charCodeAt(2)<<16)+(r.charCodeAt(3)<<24)}function $4t(r){return String.fromCharCode(r&255,r>>8&255,r>>16&255,r>>24&255)}const OMe=yee("DXT1"),LMe=yee("DXT3"),NMe=yee("DXT5"),mae=yee("DX10"),FMe=113,BMe=116,kMe=2,UMe=10,X4t=88,gae=31,Y4t=0,Q4t=1,zMe=2,VMe=3,_ae=4,GMe=7,vae=20,WMe=21,Z4t=22,q4t=23,J4t=24,eyt=25,tyt=26,iyt=28,ryt=32;class _s{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,gae),i=new Int32Array(e.buffer,e.byteOffset,gae+4);let n=1;t[zMe]&RMe&&(n=Math.max(1,t[GMe]));const s=t[WMe],a=s===mae?i[ryt]:0;let o=0;switch(s){case FMe:o=2;break;case BMe:o=1;break;case mae:if(a===UMe){o=2;break}if(a===kMe){o=1;break}}return{width:t[_ae],height:t[VMe],mipmapCount:n,isFourCC:(t[vae]&PMe)===PMe,isRGB:(t[vae]&wMe)===wMe,isLuminance:(t[vae]&DMe)===DMe,isCube:(t[iyt]&IMe)===IMe,isCompressed:s===OMe||s===LMe||s===NMe,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,n,s,a){const o=new Float32Array(n),l=new Uint16Array(s,i);let c=0;for(let u=0;u>8)}static _GetRGBArrayBuffer(e,t,i,n,s,a,o,l){const c=new Uint8Array(n),u=new Uint8Array(s,i);let h=0;for(let d=0;d0?n.sphericalPolynomial=oT.ConvertCubeMapToSphericalPolynomial({size:d[_ae],right:u[0],left:u[1],up:u[2],down:u[3],front:u[4],back:u[5],format:5,type:1,gammaSpace:!1}):n.sphericalPolynomial=void 0}}_s.StoreLODInAlphaChannel=!1;ir.prototype.createPrefilteredCubeTexture=function(r,e,t,i,n=null,s=null,a,o=null,l=!0){const c=u=>{if(!u){n&&n(null);return}const h=u.texture;if(l?u.info.sphericalPolynomial&&(h._sphericalPolynomial=u.info.sphericalPolynomial):h._sphericalPolynomial=new wg,h._source=9,this.getCaps().textureLOD){n&&n(h);return}const d=3,f=this._gl,p=u.width;if(!p)return;const g=[];for(let m=0;m{const a="\\b"+s+"\\b";return r&&(r===s||r.match(new RegExp(a,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return r;const t=r.lastIndexOf("."),i=r.lastIndexOf("?"),n=i>-1?r.substring(i,r.length):"";return(t>-1?r.substring(0,t):r)+this._textureFormatInUse+n}Object.defineProperty(Vt.prototype,"texturesSupported",{get:function(){const r=[];return this._caps.astc&&r.push("-astc.ktx"),this._caps.s3tc&&r.push("-dxt.ktx"),this._caps.pvrtc&&r.push("-pvrtc.ktx"),this._caps.etc2&&r.push("-etc2.ktx"),this._caps.etc1&&r.push("-etc1.ktx"),r},enumerable:!0,configurable:!0});Object.defineProperty(Vt.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});Vt.prototype.setCompressedTextureExclusions=function(r){this._excludedCompressedTextures=r};Vt.prototype.setTextureFormatToUse=function(r){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}}zx.DEFAULT_BUFFER_SIZE=65536;class Zk{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),s=t.isReady;let a=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(a=!0,t.type=2):n.textureFloatRender&&n.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([je(()=>Promise.resolve().then(()=>Bet),void 0),je(()=>Promise.resolve().then(()=>BDt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>Pet),void 0),je(()=>Promise.resolve().then(()=>FDt),void 0)]));const u=new ii("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&&(s?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return vee("rgbdEncode",e,t,i,1,5)}}Zk._ShaderImported=!1;Cn.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Cn.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(r=>{this._texture._sphericalPolynomial=r,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(r){this._texture&&(this._texture._sphericalPolynomial=r)},enumerable:!0,configurable:!0});const u_e="image/png",phe=2,Z9=[134,22,135,150,246,214,150,54];function xee(r){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);let t=0;for(let a=0;aphe)throw new Error(`Unsupported babylon environment map version "${r.version}". Latest supported version is "${phe}".`);return r.version===2||(r={...r,version:2,imageType:u_e}),r}async function oUe(r,e={}){var b;const t=r.getInternalTexture();if(!t)return Promise.reject("The cube texture is invalid.");const i=e.imageType??u_e,n=t.getEngine();if(r.textureType!==2&&r.textureType!==1&&r.textureType!==0&&r.textureType!==0&&r.textureType!==7&&r.textureType!==-1)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let s=1;if(!n.getCaps().textureFloatRender&&(s=2,!n.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");r.sphericalPolynomial;const a=(b=r.getInternalTexture())==null?void 0:b._sphericalPolynomialPromise,o=t.width,l=new Ut(n),c={};n.flushFramebuffer();const u=Xt.ILog2(t.width);for(let C=0;C<=u;C++){const A=Math.pow(2,u-C);for(let E=0;E<6;E++){let P=await r.readPixels(E,C,void 0,!1);if(P&&P.byteLength===P.length){const I=new Float32Array(P.byteLength*4);for(let D=0;D{if(t){const f=e.createTexture(null,!0,!0,null,1,null,p=>{d(p)},r);i==null||i.onEffectCreatedObservable.addOnce(p=>{p.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=g=>{g._bindTexture("textureSampler",f),g.setFloat2("scale",1,e._features.needsInvertingBitmap&&r instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,s,a),e.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(n),h())})})}else{if(e._uploadImageToTexture(u,r,s,a),o){const f=l[a];f&&e._uploadImageToTexture(f._texture,r,s,0)}h()}})}async function qk(r,e,t=u_e){if(!Ie.IsExponentOfTwo(r.width))throw new Error("Texture size must be a power of two");const i=Xt.ILog2(r.width)+1,n=r.getEngine();let s=!1,a=!1,o=null,l=null,c=null;const u=n.getCaps();r.format=5,r.type=0,r.generateMipMaps=!0,r._cachedAnisotropicFilteringLevel=null,n.updateTextureSamplingMode(3,r),u.textureLOD?n._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(s=!0,r.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(s=!0,r.type=1):s=!1:(s=!1,a=!0,c={});let h=0;if(s)n.isWebGPU?(h=1,await je(()=>Promise.resolve().then(()=>Bet),void 0)):await je(()=>Promise.resolve().then(()=>Pet),void 0),o=new ii("rgbdDecode","rgbdDecode",null,null,1,null,3,n,!1,void 0,r.type,void 0,null,!1,void 0,h),r._isRGBD=!1,r.invertY=!1,l=n.createRenderTargetCubeTexture(r.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:r.type,format:5});else if(r._isRGBD=!0,r.invertY=!0,a){const p=r._lodGenerationScale,g=r._lodGenerationOffset;for(let m=0;m<3;m++){const y=1-m/2,v=g,x=(i-1)*p+g,b=v+(x-v)*y,C=Math.round(Math.min(Math.max(b,0),x)),A=new _n(n,2);A.isCube=!0,A.invertY=!0,A.generateMipMaps=!1,n.updateTextureSamplingMode(2,A);const E=new Cn(null);switch(E._isCube=!0,E._texture=A,c[C]=E,m){case 0:r._lodTextureLow=E;break;case 1:r._lodTextureMid=E;break;case 2:r._lodTextureHigh=E;break}}}const d=[];for(let f=0;fKMe(v,n,s,o,_,p,f,a,c,l,r));else{const v=new Image;v.src=_,y=new Promise((x,b)=>{v.onload=()=>{KMe(v,n,s,o,_,p,f,a,c,l,r).then(()=>x()).catch(C=>{b(C)})},v.onerror=C=>{b(C)}})}d.push(y)}if(e.length{l&&(n._releaseTexture(r),l._swapAndDie(r)),o&&o.dispose(),a&&(r._lodTextureHigh&&r._lodTextureHigh._texture&&(r._lodTextureHigh._texture.isReady=!0),r._lodTextureMid&&r._lodTextureMid._texture&&(r._lodTextureMid._texture.isReady=!0),r._lodTextureLow&&r._lodTextureLow._texture&&(r._lodTextureLow._texture.isReady=!0))})}function Cee(r,e){e=nV(e);const t=e.irradiance;if(!t)return;const i=new wg;O.FromArrayToRef(t.x,0,i.x),O.FromArrayToRef(t.y,0,i.y),O.FromArrayToRef(t.z,0,i.z),O.FromArrayToRef(t.xx,0,i.xx),O.FromArrayToRef(t.yy,0,i.yy),O.FromArrayToRef(t.zz,0,i.zz),O.FromArrayToRef(t.yz,0,i.yz),O.FromArrayToRef(t.zx,0,i.zx),O.FromArrayToRef(t.xy,0,i.xy),r._sphericalPolynomial=i}function lUe(r,e,t,i,n){const s=r.getEngine().createRawCubeTexture(null,r.width,r.format,r.type,r.generateMipMaps,r.invertY,r.samplingMode,r._compression),a=qk(s,e).then(()=>r);return r.onRebuildCallback=o=>({proxy:a,isReady:!0,isAsync:!0}),r._source=13,r._bufferViewArrayArray=e,r._lodGenerationScale=i,r._lodGenerationOffset=n,r._sphericalPolynomial=t,qk(r,e).then(()=>(r.isReady=!0,r))}const ayt={GetEnvInfo:xee,CreateEnvTextureAsync:oUe,CreateImageDataArrayBufferViews:bee,UploadEnvLevelsAsync:h_e,UploadLevelsAsync:qk,UploadEnvSpherical:Cee};function mX(r,e,t,i){let n=i,s=0,a="";for(;n=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function mhe(r){let e=0,t="",i=!1;const n=[];for(;e=0&&r.charAt(e)!==t&&r.charAt(e)!==i;)e--;return e}function lyt(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bZ(r,e,t,i){let n=r.indexOf(e);if(n<0)return r;if(t){for(;n++=0&&f.push(_.substring(y+1))}s!=="void"&&f.push("return"),this._functionDescr.push({name:a,type:s,parameters:f,body:h,callIndex:0}),e=u+1;const p=t>0?this._sourceCode.substring(0,t):"",g=u+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&ge.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:n,parameters:s,body:a}=t;let o=0;for(;o{const x=[];let b=0,C=0;for(;b0?this._sourceCode.substring(0,l):"";const y=u+1{const u=c[0];return yae(e.charAt(u-1))||yae(e.charAt(u+a))?t[n]:o})}return e}}Kv._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const cyt=/(flat\s)?\s*varying\s*.*/;class uyt{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 n=i[1],s=i[2],a=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[s];if(a!==void 0){const o=a<0?a===-1?"int":"ivec"+-a:a===1?"uint":"uvec"+a,l=`_int_${s}_`;e=e.replace(i[0],`in ${o} ${l}; ${n} ${s};`),this._nativeProcessingContext.injectInVertexMain+=`${s} = ${n}(${l}); `,this._nativeProcessingContext.remappedAttributeNames[s]=l}else e=e.replace(i[0],`in ${n} ${s};`)}return e}varyingCheck(e,t){return cyt.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){var a;const n=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#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(s,""),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,(n||o?"":`layout(location = 0) out vec4 glFragColor; `)+"void main(")}else if((a=this._nativeProcessingContext)!=null&&a.injectInVertexMain&&(e=bZ(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 hyt{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,n,s,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)=>{n[i[f]]=d}),this._uniforms=n;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],n=t.updateFlag;return i!==void 0&&i===n?!1:(this._valueCache[e]=n,!0)}_cacheFloat2(e,t,i){let n=this._valueCache[e];if(!n)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s)return s=[t,i,n],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==n&&(s[2]=n,a=!0),a}_cacheFloat4(e,t,i,n,s){let a=this._valueCache[e];if(!a)return a=[t,i,n,s],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]!==n&&(a[2]=n,o=!0),a[3]!==s&&(a[3]=s,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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setInt4(this._uniforms[e],t,i,n,s)||(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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setUInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setUInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,n,s)||(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,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setFloat3(this._uniforms[e],t,i,n)||(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,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,n,s)||(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 dyt extends Kz{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,n){super(e,t,i,n),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=n}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class jMe{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 xae(r,e){switch(r){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 Q0(`Unsupported texture format or type: format ${r}, type ${e}.`,B_.UnsupportedTextureError)}function PB(r){switch(r){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: ${r}.`)}}function bae(r){switch(r){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: "+r+".")}}function fyt(r){switch(r){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: ${r}.`)}}function pyt(r){switch(r){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: ${r}.`)}}function myt(r){switch(r){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: ${r}.`)}}function gyt(r){switch(r){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: ${r}.`)}}function _yt(r){switch(r){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: ${r}.`)}}function vyt(r){switch(r){case ee.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case ee.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case ee.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case ee.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case ee.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${r}.`)}}const yyt={[ee.PositionKind]:!0,[ee.NormalKind]:!0,[ee.TangentKind]:!0,[ee.UVKind]:!0,[ee.UV2Kind]:!0,[ee.UV3Kind]:!0,[ee.UV4Kind]:!0,[ee.UV5Kind]:!0,[ee.UV6Kind]:!0,[ee.ColorKind]:!0,[ee.ColorInstanceKind]:!0,[ee.MatricesIndicesKind]:!0,[ee.MatricesWeightsKind]:!0,[ee.MatricesIndicesExtraKind]:!0,[ee.MatricesWeightsExtraKind]:!0};function xyt(r){switch(r){case ee.BYTE:case ee.SHORT:case ee.INT:case ee.FLOAT:return!0;case ee.UNSIGNED_BYTE:case ee.UNSIGNED_SHORT:case ee.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${r}'`)}}function cUe(r,e){const t=e.getEngine(),i=e._pipelineContext;if(!(i!=null&&i.vertexBufferKindToType))return;let n=null;for(const s in r){const a=r[s];if(!a||!yyt[s])continue;const o=a.normalized?ee.FLOAT:a.type,l=i.vertexBufferKindToType[s];(o!==ee.FLOAT&&l===void 0||l!==void 0&&l!==o)&&(n||(n=t._getShaderProcessingContext(e.shaderLanguage,!1)),i.vertexBufferKindToType[s]=o,o!==ee.FLOAT&&(n.vertexBufferKindToNumberOfComponents[s]=ee.DeduceStride(s),xyt(o)&&(n.vertexBufferKindToNumberOfComponents[s]*=-1)))}if(n){const s=t._caps.parallelShaderCompile;t._caps.parallelShaderCompile=void 0,e._processShaderCodeAsync(null,t._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,n),t._caps.parallelShaderCompile=s}}class byt{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const uUe=new Ce;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let r;Object.defineProperty(self,"_native",{get:()=>r,set:e=>{r=e,r&&uUe.notifyObservers(r)}})}function hUe(){return new Promise(r=>{typeof _native>"u"?uUe.addOnce(e=>r(e)):r(_native)})}async function dUe(r,e){(await hUe())[r]=e}class $Me extends mg{}class Cyt{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=aE._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 Cae=[];class aE 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 Cyt(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!==aE.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${aE.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,supportIBLShadows:!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},Ie.Log("Babylon Native (v"+Vt.Version+") launched"),Ie.LoadScript=function(n,s,a,o){Ie.LoadFile(n,l=>{Function(l).apply(null),s&&s()},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(n){return n}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function n(){const s=isNaN(arguments[0])?1:Number(arguments[0]);return s?Array.prototype.reduce.call(this,function(a,o){return Array.isArray(o)?a.push.apply(a,n.call(o,s-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 uyt,this.onNewSceneAddedObservable.add(n=>{const s=n.render;n.render=(...a)=>{this._commandBufferEncoder.beginCommandScope(),s.apply(n,a),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new zx}_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,n=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=n,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,n=!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(n?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const n=this._normalizeIndexData(e),s=new $Me;return s.references=1,s.is32Bits=n.BYTES_PER_ELEMENT===4,n.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(n.buffer,n.byteOffset,n.byteLength,s.is32Bits,t??!1)),s}createVertexBuffer(e,t,i){const n=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new $Me;return s.references=1,n.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(n.buffer,n.byteOffset,n.byteLength,t??!1)),s}_recordVertexArrayObject(e,t,i,n,s){n._checkedNonFloatVertexBuffers||(cUe(t,n),n._checkedNonFloatVertexBuffers=!0),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const a=n.getAttributesNames();for(let o=0;o=0){const c=a[o];let u=null;if(s&&(u=s[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(),vyt(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,n){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,n),s}_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,n=i.shaderProcessingContext;Cae.length=0;for(let s=0;s{n(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,n){const s=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=new Kv(t);a.processCode(),t=a.code;const o=new Kv(i);o.processCode(),i=o.code,t=ir._ConcatenateShader(t,n),i=ir._ConcatenateShader(i,n);const l=()=>{var c;s.isCompiled=!0,(c=s.onCompiled)==null||c.call(s),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)s.program=this._engine.createProgramAsync(t,i,l,c=>{s.compilationError=c});else try{s.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 s.program}inlineShaderCode(e){const t=new Kv(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 n=0;n{}}}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,pyt(this._stencilOpStencilFail),myt(this._stencilOpDepthFail),gyt(this._stencilOpStencilDepthPass),fyt(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,n,s,a){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),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,n){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=_yt(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,n){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,n,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),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,n=!1,s){if(n===void 0&&(n=!1),e&&e._hardwareTexture){const a=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,a),e.isReady=!0}}createDynamicTexture(e,t,i,n){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,n)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const n=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(n,t,i)}}createRawTexture(e,t,i,n,s,a,o,l=null,c=0,u=0,h=!1){const d=new _n(this,3);if(d.format=n,d.generateMipMaps=s,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,!s),this.updateRawTexture(d,e,n,a,l,c,d._useSRGBBuffer),d._hardwareTexture){const f=d._hardwareTexture.underlyingResource,p=PB(o);this._setTextureSampling(f,p)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,n,s,a,o,l,c=null,u=0){const h=new _n(this,11);if(h.baseWidth=t,h.baseHeight=i,h.baseDepth=n,h.width=t,h.height=i,h.depth=n,h.format=s,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,n,xae(s,u),a,o);const f=PB(l);this._setTextureSampling(d,f)}return h.isReady=!0,this._internalTexturesCache.push(h),h}updateRawTexture(e,t,i,n,s=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,xae(i,a),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,n,s=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,g=!1){e=e||"";const m=e.substr(0,5)==="data:",_=m&&e.indexOf(";base64,")!==-1,y=c||new _n(this,1),v=e;this._transformTextureUrl&&!_&&!c&&!l&&(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=h||(x>-1?e.substring(x).toLowerCase():"");let C=null;(b.endsWith(".basis")||b.endsWith(".ktx")||b.endsWith(".ktx2")||d==="image/ktx"||d==="image/ktx2")&&(C=LJ(b)),n&&n.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=s,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(g,t),this.doNotHandleContextLost||(y._buffer=l);let A=null;a&&!c&&(A=y.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(y);const E=(P,w)=>{n&&n.removePendingData(y),e===v?(A&&y.onLoadedObservable.remove(A),ei.UseFallbackTexture&&this.createTexture(ei.FallbackTexture,t,y.invertY,n,s,null,o,l,y),o&&o((P||"Unknown error")+(ei.UseFallbackTexture?" - Fallback texture was used":""),w)):(ge.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,y.invertY,n,s,a,o,l,y,u,h,d,f))};if(C)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const P=w=>{if(!y._hardwareTexture){n&&n.removePendingData(y);return}const M=y._hardwareTexture.underlyingResource;this._engine.loadTexture(M,w,!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=PB(s);this._setTextureSampling(M,R),n&&n.removePendingData(y),y.onLoadedObservable.notifyObservers(y),y.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(m&&l)if(l instanceof ArrayBuffer)P(new Uint8Array(l));else if(ArrayBuffer.isView(l))P(l);else if(typeof l=="string")P(new Uint8Array(Ie.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else _?P(new Uint8Array(Ie.DecodeBase64(e))):this._loadFile(e,w=>P(new Uint8Array(w)),void 0,void 0,!0,(w,M)=>{E("Unable to load "+(w&&w.responseURL,M))})}return y}wrapNativeTexture(e,t=!1,i=3){const n=new jMe(e,this._engine),s=new _n(this,0,!0);return s._hardwareTexture=n,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const n=t.generateStencil||!1,s=t.samples||1,a=i,o=new _n(this,12),l=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,c,n,!0,s);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((n,s)=>{const a=this.createCanvasImage();a.onload=()=>{try{const o=this._engine.createImageBitmap(a);n(o)}catch(o){s(`Error loading image ${a.src} with exception: ${o}`)}},a.onerror=o=>{s(`Error loading image ${a.src} with exception: ${o}`)},a.src=e})}createImageBitmap(e,t){return new Promise((i,n)=>{if(Array.isArray(e)){const s=e;if(s.length){const a=this._engine.createImageBitmap(s[0]);if(a){i(a);return}}}n("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,n,s=null,a=null,o,l=null,c=!1,u=0,h=0,d=null,f,p=!1,g=null){const m=d||new _n(this,7);m.isCube=!0,m.url=e,m.generateMipMaps=!n,m._lodGenerationScale=u,m._lodGenerationOffset=h,m._useSRGBBuffer=this._getUseSRGBBuffer(p,!!n),this._doNotHandleContextLost||(m._extension=l,m._files=i,m._buffer=g);const _=e.lastIndexOf(".");if((l||(_>-1?e.substring(_).toLowerCase():""))===".env"){const v=x=>{const b=xee(x);m.width=b.width,m.height=b.width,Cee(m,b);const C=b.specular;if(!C)throw new Error("Nothing else parsed so far");m._lodGenerationScale=C.lodGenerationScale;const A=bee(x,b);m.format=5,m.type=0,m.generateMipMaps=!0,m.getEngine().updateTextureSamplingMode(be.TRILINEAR_SAMPLINGMODE,m),m._isRGBD=!0,m.invertY=!0,this._engine.loadCubeTextureWithMips(m._hardwareTexture.underlyingResource,A,!1,m._useSRGBBuffer,()=>{m.isReady=!0,s&&s()},()=>{throw new Error("Could not load a native cube texture.")})};if(g)v(g);else{if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");{const x=(b,C)=>{a&&b&&a(b.status+" "+b.statusText,C)};this._loadFile(e,b=>{v(new Uint8Array(b,0,b.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(b=>new Uint8Array(b,0,b.byteLength)))).then(x=>new Promise((b,C)=>{this._engine.loadCubeTexture(m._hardwareTexture.underlyingResource,x,!n,!0,m._useSRGBBuffer,b,C)})).then(()=>{m.isReady=!0,s&&s()},x=>{a&&a(`Failed to load cubemap: ${x.message}`,x)})}return this._internalTexturesCache.push(m),m}_createHardwareTexture(){return new jMe(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const n=new dyt(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}_createInternalTexture(e,t,i=!0,n=0){let s=!1,a=0,o=3,l=5,c=!1,u=1,h;t!==void 0&&typeof t=="object"?(s=!!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):s=!!t,c=this._getUseSRGBBuffer(c,!s),(a===1&&!this._caps.textureFloatLinearFiltering||a===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),a===1&&!this._caps.textureFloat&&(a=0,ge.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new _n(this,n),f=e.width??e,p=e.height??e,g=e.layers||0;if(g!==0)throw new Error("Texture layers are not supported in Babylon Native");const m=d._hardwareTexture.underlyingResource,_=xae(l,a);return this._engine.initializeTexture(m,f,p,s,_,!0,c,u),this._setTextureSampling(m,PB(o)),d._useSRGBBuffer=c,d.baseWidth=f,d.baseHeight=p,d.width=f,d.height=p,d.depth=g,d.isReady=!0,d.samples=u,d.generateMipMaps=s,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 n=!0,s=!1,a=!1,o,l=1;t!==void 0&&typeof t=="object"&&(n=t.generateDepthBuffer??!0,s=!!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,s,n,l);return i._framebuffer=d,i._generateDepthBuffer=n,i._generateStencilBuffer=s,i._samples=l,i.setTextures(c),i}updateRenderTargetTextureSampleCount(e,t){return ge.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=PB(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,n,s){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||n)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 n=e,s=this._normalizeIndexData(t);n.is32Bits=s.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(n.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,n){const s=e,a=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(a.buffer,a.byteOffset,n??a.byteLength);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,n=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(s)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;return n?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,bae(t.wrapU),bae(t.wrapV),bae(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(s,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,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),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 n=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,n)}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,n,s,a,o=0,l=0,c=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,a=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,n=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,n,s,a,o,l,c,u){var h;if(n!==void 0&&n!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${n}.`);return this._engine.readTexture((h=e._hardwareTexture)==null?void 0:h.underlyingResource,s??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))}}aE.PROTOCOL_VERSION=8;aE._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new fUe:new zx};class fUe extends zx{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 ghe;(function(r){r.LowPower="low-power",r.HighPerformance="high-performance"})(ghe||(ghe={}));var _he;(function(r){r.DepthClipControl="depth-clip-control",r.Depth32FloatStencil8="depth32float-stencil8",r.TextureCompressionBC="texture-compression-bc",r.TextureCompressionETC2="texture-compression-etc2",r.TextureCompressionASTC="texture-compression-astc",r.TimestampQuery="timestamp-query",r.IndirectFirstInstance="indirect-first-instance",r.ShaderF16="shader-f16",r.RG11B10UFloatRenderable="rg11b10ufloat-renderable",r.BGRA8UnormStorage="bgra8unorm-storage",r.Float32Filterable="float32-filterable"})(_he||(_he={}));var vhe;(function(r){r.Unmapped="unmapped",r.Pending="pending",r.Mapped="mapped"})(vhe||(vhe={}));var ts;(function(r){r[r.MapRead=1]="MapRead",r[r.MapWrite=2]="MapWrite",r[r.CopySrc=4]="CopySrc",r[r.CopyDst=8]="CopyDst",r[r.Index=16]="Index",r[r.Vertex=32]="Vertex",r[r.Uniform=64]="Uniform",r[r.Storage=128]="Storage",r[r.Indirect=256]="Indirect",r[r.QueryResolve=512]="QueryResolve"})(ts||(ts={}));var yhe;(function(r){r[r.Read=1]="Read",r[r.Write=2]="Write"})(yhe||(yhe={}));var xhe;(function(r){r.E1d="1d",r.E2d="2d",r.E3d="3d"})(xhe||(xhe={}));var bhe;(function(r){r[r.CopySrc=1]="CopySrc",r[r.CopyDst=2]="CopyDst",r[r.TextureBinding=4]="TextureBinding",r[r.StorageBinding=8]="StorageBinding",r[r.RenderAttachment=16]="RenderAttachment"})(bhe||(bhe={}));var Che;(function(r){r.E1d="1d",r.E2d="2d",r.E2dArray="2d-array",r.Cube="cube",r.CubeArray="cube-array",r.E3d="3d"})(Che||(Che={}));var Ahe;(function(r){r.All="all",r.StencilOnly="stencil-only",r.DepthOnly="depth-only"})(Ahe||(Ahe={}));var She;(function(r){r.R8Unorm="r8unorm",r.R8Snorm="r8snorm",r.R8Uint="r8uint",r.R8Sint="r8sint",r.R16Uint="r16uint",r.R16Sint="r16sint",r.R16Float="r16float",r.RG8Unorm="rg8unorm",r.RG8Snorm="rg8snorm",r.RG8Uint="rg8uint",r.RG8Sint="rg8sint",r.R32Uint="r32uint",r.R32Sint="r32sint",r.R32Float="r32float",r.RG16Uint="rg16uint",r.RG16Sint="rg16sint",r.RG16Float="rg16float",r.RGBA8Unorm="rgba8unorm",r.RGBA8UnormSRGB="rgba8unorm-srgb",r.RGBA8Snorm="rgba8snorm",r.RGBA8Uint="rgba8uint",r.RGBA8Sint="rgba8sint",r.BGRA8Unorm="bgra8unorm",r.BGRA8UnormSRGB="bgra8unorm-srgb",r.RGB9E5UFloat="rgb9e5ufloat",r.RGB10A2UINT="rgb10a2uint",r.RGB10A2Unorm="rgb10a2unorm",r.RG11B10UFloat="rg11b10ufloat",r.RG32Uint="rg32uint",r.RG32Sint="rg32sint",r.RG32Float="rg32float",r.RGBA16Uint="rgba16uint",r.RGBA16Sint="rgba16sint",r.RGBA16Float="rgba16float",r.RGBA32Uint="rgba32uint",r.RGBA32Sint="rgba32sint",r.RGBA32Float="rgba32float",r.Stencil8="stencil8",r.Depth16Unorm="depth16unorm",r.Depth24Plus="depth24plus",r.Depth24PlusStencil8="depth24plus-stencil8",r.Depth32Float="depth32float",r.BC1RGBAUnorm="bc1-rgba-unorm",r.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",r.BC2RGBAUnorm="bc2-rgba-unorm",r.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",r.BC3RGBAUnorm="bc3-rgba-unorm",r.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",r.BC4RUnorm="bc4-r-unorm",r.BC4RSnorm="bc4-r-snorm",r.BC5RGUnorm="bc5-rg-unorm",r.BC5RGSnorm="bc5-rg-snorm",r.BC6HRGBUFloat="bc6h-rgb-ufloat",r.BC6HRGBFloat="bc6h-rgb-float",r.BC7RGBAUnorm="bc7-rgba-unorm",r.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",r.ETC2RGB8Unorm="etc2-rgb8unorm",r.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",r.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",r.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",r.ETC2RGBA8Unorm="etc2-rgba8unorm",r.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",r.EACR11Unorm="eac-r11unorm",r.EACR11Snorm="eac-r11snorm",r.EACRG11Unorm="eac-rg11unorm",r.EACRG11Snorm="eac-rg11snorm",r.ASTC4x4Unorm="astc-4x4-unorm",r.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",r.ASTC5x4Unorm="astc-5x4-unorm",r.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",r.ASTC5x5Unorm="astc-5x5-unorm",r.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",r.ASTC6x5Unorm="astc-6x5-unorm",r.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",r.ASTC6x6Unorm="astc-6x6-unorm",r.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",r.ASTC8x5Unorm="astc-8x5-unorm",r.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",r.ASTC8x6Unorm="astc-8x6-unorm",r.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",r.ASTC8x8Unorm="astc-8x8-unorm",r.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",r.ASTC10x5Unorm="astc-10x5-unorm",r.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",r.ASTC10x6Unorm="astc-10x6-unorm",r.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",r.ASTC10x8Unorm="astc-10x8-unorm",r.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",r.ASTC10x10Unorm="astc-10x10-unorm",r.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",r.ASTC12x10Unorm="astc-12x10-unorm",r.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",r.ASTC12x12Unorm="astc-12x12-unorm",r.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",r.Depth32FloatStencil8="depth32float-stencil8"})(She||(She={}));var Ehe;(function(r){r.ClampToEdge="clamp-to-edge",r.Repeat="repeat",r.MirrorRepeat="mirror-repeat"})(Ehe||(Ehe={}));var The;(function(r){r.Nearest="nearest",r.Linear="linear"})(The||(The={}));var Mhe;(function(r){r.Nearest="nearest",r.Linear="linear"})(Mhe||(Mhe={}));var Rhe;(function(r){r.Never="never",r.Less="less",r.Equal="equal",r.LessEqual="less-equal",r.Greater="greater",r.NotEqual="not-equal",r.GreaterEqual="greater-equal",r.Always="always"})(Rhe||(Rhe={}));var Ihe;(function(r){r[r.Vertex=1]="Vertex",r[r.Fragment=2]="Fragment",r[r.Compute=4]="Compute"})(Ihe||(Ihe={}));var Phe;(function(r){r.Uniform="uniform",r.Storage="storage",r.ReadOnlyStorage="read-only-storage"})(Phe||(Phe={}));var whe;(function(r){r.Filtering="filtering",r.NonFiltering="non-filtering",r.Comparison="comparison"})(whe||(whe={}));var Dhe;(function(r){r.Float="float",r.UnfilterableFloat="unfilterable-float",r.Depth="depth",r.Sint="sint",r.Uint="uint"})(Dhe||(Dhe={}));var Ohe;(function(r){r.WriteOnly="write-only",r.ReadOnly="read-only",r.ReadWrite="read-write"})(Ohe||(Ohe={}));var Lhe;(function(r){r.Error="error",r.Warning="warning",r.Info="info"})(Lhe||(Lhe={}));var Nhe;(function(r){r.Validation="validation",r.Internal="internal"})(Nhe||(Nhe={}));var Fhe;(function(r){r.Auto="auto"})(Fhe||(Fhe={}));var Bhe;(function(r){r.PointList="point-list",r.LineList="line-list",r.LineStrip="line-strip",r.TriangleList="triangle-list",r.TriangleStrip="triangle-strip"})(Bhe||(Bhe={}));var khe;(function(r){r.CCW="ccw",r.CW="cw"})(khe||(khe={}));var Uhe;(function(r){r.None="none",r.Front="front",r.Back="back"})(Uhe||(Uhe={}));var zhe;(function(r){r[r.Red=1]="Red",r[r.Green=2]="Green",r[r.Blue=4]="Blue",r[r.Alpha=8]="Alpha",r[r.All=15]="All"})(zhe||(zhe={}));var Vhe;(function(r){r.Zero="zero",r.One="one",r.Src="src",r.OneMinusSrc="one-minus-src",r.SrcAlpha="src-alpha",r.OneMinusSrcAlpha="one-minus-src-alpha",r.Dst="dst",r.OneMinusDst="one-minus-dst",r.DstAlpha="dst-alpha",r.OneMinusDstAlpha="one-minus-dst-alpha",r.SrcAlphaSaturated="src-alpha-saturated",r.Constant="constant",r.OneMinusConstant="one-minus-constant"})(Vhe||(Vhe={}));var Ghe;(function(r){r.Add="add",r.Subtract="subtract",r.ReverseSubtract="reverse-subtract",r.Min="min",r.Max="max"})(Ghe||(Ghe={}));var Whe;(function(r){r.Keep="keep",r.Zero="zero",r.Replace="replace",r.Invert="invert",r.IncrementClamp="increment-clamp",r.DecrementClamp="decrement-clamp",r.IncrementWrap="increment-wrap",r.DecrementWrap="decrement-wrap"})(Whe||(Whe={}));var Khe;(function(r){r.Uint16="uint16",r.Uint32="uint32"})(Khe||(Khe={}));var Hhe;(function(r){r.Uint8x2="uint8x2",r.Uint8x4="uint8x4",r.Sint8x2="sint8x2",r.Sint8x4="sint8x4",r.Unorm8x2="unorm8x2",r.Unorm8x4="unorm8x4",r.Snorm8x2="snorm8x2",r.Snorm8x4="snorm8x4",r.Uint16x2="uint16x2",r.Uint16x4="uint16x4",r.Sint16x2="sint16x2",r.Sint16x4="sint16x4",r.Unorm16x2="unorm16x2",r.Unorm16x4="unorm16x4",r.Snorm16x2="snorm16x2",r.Snorm16x4="snorm16x4",r.Float16x2="float16x2",r.Float16x4="float16x4",r.Float32="float32",r.Float32x2="float32x2",r.Float32x3="float32x3",r.Float32x4="float32x4",r.Uint32="uint32",r.Uint32x2="uint32x2",r.Uint32x3="uint32x3",r.Uint32x4="uint32x4",r.Sint32="sint32",r.Sint32x2="sint32x2",r.Sint32x3="sint32x3",r.Sint32x4="sint32x4",r.UNORM10x10x10x2="unorm10-10-10-2"})(Hhe||(Hhe={}));var jhe;(function(r){r.Vertex="vertex",r.Instance="instance"})(jhe||(jhe={}));var $he;(function(r){r.Beginning="beginning",r.End="end"})($he||($he={}));var Xhe;(function(r){r.Beginning="beginning",r.End="end"})(Xhe||(Xhe={}));var Yhe;(function(r){r.Load="load",r.Clear="clear"})(Yhe||(Yhe={}));var Qhe;(function(r){r.Store="store",r.Discard="discard"})(Qhe||(Qhe={}));var Zhe;(function(r){r.Occlusion="occlusion",r.Timestamp="timestamp"})(Zhe||(Zhe={}));var qhe;(function(r){r.Opaque="opaque",r.Premultiplied="premultiplied"})(qhe||(qhe={}));var Jhe;(function(r){r.Unknown="unknown",r.Destroyed="destroyed"})(Jhe||(Jhe={}));var ede;(function(r){r.Validation="validation",r.OutOfMemory="out-of-memory",r.Internal="internal"})(ede||(ede={}));class Ml{constructor(){this.shaderLanguage=0}_addUniformToLeftOverUBO(e,t,i){let n=0;[e,t,n]=this._getArraySize(e,t,i);for(let s=0;s=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 Ci(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Ml.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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,n)}setInt4(e,t,i,n,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,n,s)}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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,n)}setUInt4(e,t,i,n,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,n,s)}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,n){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,n)}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,n,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,n,s)}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 Syt=4,Eyt=65536,XMe={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class _f{static get KnownUBOs(){return _f._SimplifiedKnownBindings?_f._SimplifiedKnownUBOs:_f._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=_f.KnownUBOs,t=[];for(const i in e){const n=e[i].binding;n.groupIndex!==-1&&(t[n.groupIndex]===void 0?t[n.groupIndex]=n.bindingIndex:t[n.groupIndex]=Math.max(t[n.groupIndex],n.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+=(XMe[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(XMe[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>Eyt-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===Syt)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}}_f._SimplifiedKnownBindings=!0;_f._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}}};_f._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 Tyt extends Ml{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=0,this.parseGLES3=!0}_getArraySize(e,t,i){let n=0;const s=e.indexOf("["),a=e.indexOf("]");if(s>0&&a>0){const o=e.substring(s+1,a);n=+o,isNaN(n)&&(n=+i[o.trim()]),e=e.substr(0,s)}return[e,t,n]}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 ${Ml.InternalsUBOName} { float yFactor_; float textureOutputHeight_; }; `,n=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),n?e:i+`##INJECTCODE## `+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),n?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,n=/(flat\s)?\s*\bin\b/,s=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?n:!t&&this._vertexIsGLES3?i:s).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const n=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,s=/\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?s:!t&&this._vertexIsGLES3?n: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&&ge.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,n=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,a=(this._vertexIsGLES3?i:n).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 s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(s!==null){let a=s[1],o=s[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 A=0;A<(l||1);++A)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=Ml._SamplerTypeByWebGLSamplerType[a]??"sampler",h=!!Ml._IsComparisonSamplerByWebGPUSamplerType[u],d=h?"comparison":"filtering",f=o+"Sampler";let p=this._webgpuProcessingContext.availableSamplers[f];p||(p={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const g=a.charAt(0)==="u"?"u":a.charAt(0)==="i"?"i":"";g&&(a=a.substr(1));const m=h?"depth":g==="u"?"uint":g==="i"?"sint":"float";c.sampleType=m;const _=l>0,y=p.binding.groupIndex,v=p.binding.bindingIndex,x=Ml._SamplerFunctionByWebGLSamplerType[a],b=Ml._TextureTypeByWebGLSamplerType[a],C=Ml._GpuTextureViewDimensionByWebGPUTextureType[b];if(!_)l=1,e=`layout(set = ${y}, binding = ${v}) uniform ${u} ${f}; layout(set = ${c.textures[0].groupIndex}, binding = ${c.textures[0].bindingIndex}) uniform ${g}${b} ${o}Texture; #define ${o} ${g}${x}(${o}Texture, ${f})`;else{const A=[];A.push(`layout(set = ${y}, binding = ${v}) uniform ${g}${u} ${f};`),e=` `;for(let E=0;E0?` `:""}#define ${o}${E} ${g}${x}(${o}Texture${E}, ${f})`}e=A.join(` `)+e,this._textureArrayProcessing.push(o)}this._webgpuProcessingContext.availableTextures[o]=c,this._webgpuProcessingContext.availableSamplers[f]=p,this._addSamplerBindingDescription(f,p,!t);for(let A=0;A=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=bZ(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 n=i.exec(e);for(;n!==null;){const s=n[1];let a=+s;this._preProcessors&&isNaN(a)&&(a=+this._preProcessors[s.trim()]),e=e.replace(n[0],t+a),n=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { `;for(const n of this._webgpuProcessingContext.leftOverUniforms)n.length>0?i+=` ${n.type} ${n.name}[${n.length}]; `:i+=` ${n.type} ${n.name}; `;return i+=`}; `,i}finalizeShaders(e,t){for(let n=0;n0&&(t=s+` `+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 pUe="helperFunctions",mUe=`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;} `;me.IncludesShadersStoreWGSL[pUe]=mUe;const gUe={name:pUe,shader:mUe},_Ue=Object.freeze(Object.defineProperty({__proto__:null,helperFunctionsWGSL:gUe},Symbol.toStringTag,{value:"Module"})),Myt="fresnelFunction",Ryt=`#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 `;me.IncludesShadersStoreWGSL[Myt]=Ryt;const Iyt="meshUboDeclaration",Pyt=`struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO `;me.IncludesShadersStoreWGSL[Iyt]=Pyt;const wyt="sceneUboDeclaration",Dyt=`struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif view : mat4x4, projection : mat4x4, vEyePosition : vec4,};var scene : Scene; `;me.IncludesShadersStoreWGSL[wyt]=Dyt;const Oyt="decalFragment",Lyt=`#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 `;me.IncludesShadersStoreWGSL[Oyt]=Lyt;const YMe="fragmentOutputs.fragDepth",Nyt="uniforms",Fyt="internals",Byt={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 kyt extends Ml{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,n,s){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 n=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let a=s;for(;a>0&&t.charAt(a)!==" "&&t.charAt(a)!==",";)a--;const o=t.substring(a+1,s);for(n=+o,isNaN(n)&&(n=+i[o.trim()]);a>0&&(t.charAt(a)===" "||t.charAt(a)===",");)a--;t=t.substring(t.indexOf("<")+1,a+1)}return[e,t,n]}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 ${Ml.InternalsUBOName} { yFactor_: f32, textureOutputHeight_: f32, }; var ${Fyt} : ${Ml.InternalsUBOName}; `;return e.indexOf(t)!==-1?e:t+mhe(e)}varyingCheck(e){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const a=s[1]??"perspective",o=s[2]??"center",l=s[4],c=s[3],u=a==="flat"?`@interpolate(${a})`:`@interpolate(${a}, ${o})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[c],h===void 0&&ge.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 n=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(n!==null){const s=n[2],a=n[1],o=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(a,s,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} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = ${s}(vertexInputs_.${u});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${o}) ${a} : ${s},`),this._attributesWGSL.push(`${a} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${a} = vertexInputs_.${a};`);e=""}return e}uniformProcessor(e,t,i){const n=this.uniformRegexp.exec(e);if(n!==null){const s=n[2],a=n[1];this._addUniformToLeftOverUBO(a,s,i),e=""}return e}textureProcessor(e,t,i){const n=this.textureRegexp.exec(e);if(n!==null){const s=n[1],a=n[2],o=!!n[3],l=n[4],c=l.indexOf("storage")>0,u=n[6],h=c?u.substring(0,u.indexOf(",")).trim():null;let d=o?this._getArraySize(s,a,i)[2]:0,f=this._webgpuProcessingContext.availableTextures[s];if(f)d=f.textures.length;else{f={isTextureArray:d>0,isStorageTexture:c,textures:[],sampleType:"float"},d=d||1;for(let _=0;_0,g=Byt[l],m=p?"depth":u==="u32"?"uint":u==="i32"?"sint":"float";if(f.sampleType=m,g===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 n=this._buildLeftOverUBO();e=n+e,t=n+t,e=e.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;"),e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s=`struct VertexInputs { @builtin(vertex_index) vertexIndex : u32, @builtin(instance_index) instanceIndex : u32, `;this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join(` `)),s+=` }; var vertexInputs`+(this._hasNonFloatAttribute?"_":"")+` : VertexInputs; `,this._hasNonFloatAttribute&&(s+=`struct VertexInputs_ { vertexIndex : u32, instanceIndex : u32, `,s+=this._attributesWGSL.join(` `),s+=` }; var vertexInputs : VertexInputs_; `);let a=`struct FragmentInputs { @builtin(position) position : vec4, `;this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join(` `)),a+=` }; var vertexOutputs : FragmentInputs; `,e=s+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); `:"")+bZ(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 g=!1,m=0;for(;!g&&(m=t.indexOf(YMe,m),!(m<0));){const v=m;for(g=!0;m>1&&t.charAt(m)!==` `;){if(t.charAt(m)==="/"&&t.charAt(m-1)==="/"){g=!1;break}m--}m=v+YMe.length}g&&(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); `:"")+bZ(t,"fn main",_,y),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",n=`struct ${e} { `;for(const s of this._webgpuProcessingContext.leftOverUniforms){const a=s.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=Ml.UniformSizes[a];if(s.length>0)if(o<=2){const l=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${l} { @size(16) el: ${a}, }`,this._stridedUniformArrays.push(s.name),n+=` @align(16) ${s.name} : array<${l}, ${s.length}>, `}else n+=` ${s.name} : array<${s.type}, ${s.length}>, `;else n+=` ${s.name} : ${s.type}, `}return n+=`}; `,n=`${i} ${n}`,n+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${Nyt} : ${e}; `,n}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const n=i.exec(e);if(n===null)break;const s=n[1],a=n[2],o=s.length-7,l=s.lastIndexOf("Sampler")===o?s.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[s];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c},this._webgpuProcessingContext.availableSamplers[s]=u),this._addSamplerBindingDescription(s,u,t);const h=e.substring(0,n.index),d=`@group(${u.binding.groupIndex}) @binding(${u.binding.bindingIndex}) `,f=e.substring(n.index);e=h+d+f,i.lastIndex+=d.length}return e}_processCustomBuffers(e,t){var n;const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const a=s[1],o=s[3];let l=s[4];const c=s[5];let u=this._webgpuProcessingContext.availableBuffers[l];if(!u){const m=a==="uniform"?_f.KnownUBOs[c]:null;let _;m?(l=c,_=m.binding,_.groupIndex===-1&&(_=(n=this._webgpuProcessingContext.availableBuffers[l])==null?void 0:n.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,s.index),p=`@group(${h}) @binding(${d}) `,g=e.substring(s.index);e=f+p+g,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 Nn{static ComputeNumMipmapLevels(e,t){return Xt.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 JY{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,n,s,a,o,l){let c="2d",u=1;n?(c=i?"cube-array":"cube",u=6*(l||1)):s?(c="3d",u=1):i&&(c="2d-array",u=l);const h=Nn.GetDepthFormatOnly(this.format),d=Nn.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:`TextureView${s?"3D":n?"Cube":"2D"}${i?"_Array"+u:""}_${a}x${o}_${t?"wmips":"womips"}_${this.format}_${c}`,format:h,dimension:c,mipLevelCount:t?Xt.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 Uyt=` 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); } `,zyt=` var imgSampler: sampler; var img: texture_2d; varying vTex: vec2f; @fragment fn main(input: FragmentInputs) -> FragmentOutputs { fragmentOutputs.color = textureSample(img, imgSampler, input.vTex); } `,vUe=` 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); } `,Vyt=` 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; } `,Gyt=vUe,Wyt=` 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; } `,Kyt=` 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); } `,Hyt=` uniform color: vec4f; @fragment fn main(input: FragmentInputs) -> FragmentOutputs { fragmentOutputs.color = uniforms.color; } `,jyt=` 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; } `,$yt=` @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); } `,Xyt=` @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 p0;(function(r){r[r.MipMap=0]="MipMap",r[r.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",r[r.Clear=2]="Clear",r[r.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(p0||(p0={}));var TP;(function(r){r[r.DontInvertY=0]="DontInvertY",r[r.InvertY=1]="InvertY"})(TP||(TP={}));const QMe=[{vertex:Uyt,fragment:zyt},{vertex:vUe,fragment:Vyt},{vertex:Kyt,fragment:Hyt},{vertex:Gyt,fragment:Wyt}],i_={"":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 Yyt{constructor(e,t,i,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=i,n.indexOf("rg11b10ufloat-renderable")!==-1){const s=Object.keys(i_);i_.rg11b10ufloat=i_[s[s.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,ts.Uniform|ts.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=p0.MipMap,i){const n=t===p0.MipMap?1:t===p0.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===p0.Clear?8:t===p0.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][n];if(!s){let a="";(t===p0.InvertYPremultiplyAlpha||t===p0.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(a+=`#define INVERTY `),i.premultiplyAlpha&&(a+=`#define PREMULTIPLYALPHA `));let o=this._compiledShaders[n];if(!o){let c=QMe[t].vertex,u=QMe[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};r1e(h),h.processor.pureMode=!0,dZ(c,h,g=>{c=g},this._engine),h.isFragment=!0,dZ(u,h,g=>{u=g},this._engine);const d=n1e(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[n]=[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"}});s=this._pipelines[e][n]=[l,l.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=TP.DontInvertY){const i=t===TP.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let n=this._videoPipelines[e][i];if(!n){let s=this._videoCompiledShaders[i];if(!s){const o=this._device.createShaderModule({code:jyt}),l=this._device.createShaderModule({code:i===0?$yt:Xyt});s=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:s[0],entryPoint:"main"},fragment:{module:s[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});n=this._videoPipelines[e][i]=[a,a.getBindGroupLayout(0)]}return n}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,n=!1,s){var p,g;const a=s===void 0,[o,l]=this._getVideoPipeline(i,n?TP.InvertY:TP.DontInvertY);a&&(s=this._device.createCommandEncoder({})),(p=s.pushDebugGroup)==null||p.call(s,`copy video to texture - invertY=${n}`);const c=t._hardwareTexture,u={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${n?"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=s.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(),(g=s.popDebugGroup)==null||g.call(s),a&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,n,s=!1,a=!1,o=0,l=0,c=1,u=0,h=0,d=0,f=0,p,g){var w,M;const m=d!==0,_=p===void 0,[y,v]=this._getPipeline(n,m?p0.InvertYPremultiplyAlphaWithOfst:p0.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:a});o=Math.max(o,0),_&&(p=this._device.createCommandEncoder({})),(w=p.pushDebugGroup)==null||w.call(p,`internal process texture - invertY=${s} premultiplyAlpha=${a}`);let x;if(Nn.IsHardwareTexture(e)?(x=e.underlyingResource,s&&!a&&c===1&&o===0||(e=void 0)):(x=e,e=void 0),!x)return;m&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([u,h,d,f]),0,4*4);const b=e,C=(b==null?void 0:b._copyInvertYTempTexture)??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,n,1,p,21,void 0,"TempTextureForCopyWithInvertY"),A=(b==null?void 0:b._copyInvertYRenderPassDescr)??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${n}_${s?"InvertY":"DontInvertY"}_${a?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:C.createView({format:n,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},E=p.beginRenderPass(A);let P=m?b==null?void 0:b._copyInvertYBindGroupWithOfst:b==null?void 0:b._copyInvertYBindGroup;if(!P){const R={layout:v,entries:[{binding:0,resource:x.createView({format:n,dimension:"2d",baseMipLevel:l,mipLevelCount:1,arrayLayerCount:c,baseArrayLayer:o})}]};m&&R.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),P=this._device.createBindGroup(R)}E.setPipeline(y),E.setBindGroup(0,P),E.draw(4,1,0,0),E.end(),p.copyTextureToTexture({texture:C},{texture:x,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=C,b._copyInvertYRenderPassDescr=A,m?b._copyInvertYBindGroupWithOfst=P:b._copyInvertYBindGroup=P):this._deferredReleaseTextures.push([C,null]),(M=p.popDebugGroup)==null||M.call(p),_&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,n){var u,h;const s=n===void 0,[a,o]=this._getPipeline(t,p0.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});s&&(n=this._device.createCommandEncoder({})),(u=n.pushDebugGroup)==null||u.call(n,"internal copy texture with invertY");const l=n.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=n.popDebugGroup)==null||h.call(n),s&&(this._device.queue.submit([n.finish()]),n=null)}createTexture(e,t=!1,i=!1,n=!1,s=!1,a=!1,o="rgba8unorm",l=1,c,u=-1,h=0,d){l=Nn.GetSample(l);const f=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:f},g=i_[o]?16:0,m=Nn.IsCompressedFormat(o),_=t?Nn.ComputeNumMipmapLevels(e.width,e.height):1,y=u>=0?u:7;h|=t&&!m?1|g:0,!m&&!a&&(h|=g|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 Nn.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,f,o,0,0,n,s,0,0),t&&i&&this.generateMipmaps(v,o,_,0,a,c)),v}createCubeTexture(e,t=!1,i=!1,n=!1,s=!1,a="rgba8unorm",o=1,l,c=-1,u=0,h){o=Nn.GetSample(o);const d=Nn.IsImageBitmapArray(e)?e[0].width:e.width,f=Nn.IsImageBitmapArray(e)?e[0].height:e.height,p=i_[a]?16:0,g=Nn.IsCompressedFormat(a),m=t?Nn.ComputeNumMipmapLevels(d,f):1,_=c>=0?c:7;u|=t&&!g?1|p:0,g||(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:m});return Nn.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,y,d,f,a,n,s,0,0),t&&i&&this.generateCubeMipmaps(y,a,m,l)),y}generateCubeMipmaps(e,t,i,n){var a,o;const s=n===void 0;s&&(n=this._device.createCommandEncoder({})),(a=n.pushDebugGroup)==null||a.call(n,`create cube mipmaps - ${i} levels`);for(let l=0;l<6;++l)this.generateMipmaps(e,t,i,l,!1,n);(o=n.popDebugGroup)==null||o.call(n),s&&(this._device.queue.submit([n.finish()]),n=null)}generateMipmaps(e,t,i,n=0,s=!1,a){var d,f,p,g;const o=a===void 0,[l,c]=this._getPipeline(t);n=Math.max(n,0),o&&(a=this._device.createCommandEncoder({})),(d=a.pushDebugGroup)==null||d.call(a,`create mipmaps for face #${n} - ${i} levels`);let u;if(Nn.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 m=1;mu;)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,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const n=new Uint16Array(t);for(;e--;)i[e]=jm(n[e]);return i}readDataFromBuffer(e,t,i,n,s,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,g)=>{e.mapAsync(1,l,t).then(()=>{const m=e.getMappedRange(l,t);let _=c;if(h)_===null?_=gZ(o,t,!0,m):_=gZ(o,_.buffer,void 0,m);else if(_===null)switch(d){case 0:_=new Uint8Array(t),_.set(new Uint8Array(m));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,m);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(m));break}else switch(d){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(m));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,m,c);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(m));break}if(s!==a){d===1&&!h&&(s*=2,a*=2);const y=new Uint8Array(_.buffer);let v=s,x=0;for(let b=1;b{this._engine.isDisposed||this._engine.uniqueId!==f?p(new Uint8Array):g(m)})})}releaseBuffer(e){return CZ._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 Qyt[e.samplingMode]+Zyt[(e._comparisonFunction||514)-512+1]+qyt[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,n,s,a,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i="linear",n="linear",s="nearest",l||(a=o=0);break;case 3:case 3:i="linear",n="linear",l?s="linear":(s="nearest",a=o=0);break;case 8:i="nearest",n="nearest",l?s="linear":(s="nearest",a=o=0);break;case 4:i="nearest",n="nearest",s="nearest",l||(a=o=0);break;case 5:i="nearest",n="linear",s="nearest",l||(a=o=0);break;case 6:i="nearest",n="linear",l?s="linear":(s="nearest",a=o=0);break;case 7:i="nearest",n="linear",s="nearest",a=o=0;break;case 1:case 1:i="nearest",n="nearest",s="nearest",a=o=0;break;case 9:i="linear",n="nearest",s="nearest",l||(a=o=0);break;case 10:i="linear",n="nearest",l?s="linear":(s="nearest",a=o=0);break;case 2:case 2:i="linear",n="linear",s="nearest",a=o=0;break;case 12:i="linear",n="nearest",s="nearest",a=o=0;break;default:i="nearest",n="nearest",s="nearest",a=o=0;break}return t>1&&(a!==0||o!==0)&&s!=="nearest"?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:n,mipmapFilter:s,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,n=this._GetSamplerFilterDescriptor(e,i);return{label:t,...n,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?ix.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:n.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,n){if(this.disabled)return this._device.createSampler(ix._GetSamplerDescriptor(e,n));t?i=0:i===0&&(i=ix.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(ix._GetSamplerDescriptor(e,n)),t||(this._samplers[i]=s)),s}}var No;(function(r){r[r.StencilReadMask=0]="StencilReadMask",r[r.StencilWriteMask=1]="StencilWriteMask",r[r.DepthBias=2]="DepthBias",r[r.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",r[r.DepthStencilState=4]="DepthStencilState",r[r.MRTAttachments1=5]="MRTAttachments1",r[r.MRTAttachments2=6]="MRTAttachments2",r[r.RasterizationState=7]="RasterizationState",r[r.ColorStates=8]="ColorStates",r[r.ShaderStage=9]="ShaderStage",r[r.TextureStage=10]="TextureStage",r[r.VertexState=11]="VertexState",r[r.NumStates=12]="NumStates"})(No||(No={}));const gX={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},DI={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class xa{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,n=0){if(i=Nn.GetSample(i),this.disabled){const a=xa._GetTopology(e);return this._setVertexState(t),this._setTextureState(n),this._parameter.pipeline=this._createRenderPipeline(t,a,i),xa.NumCacheMiss++,xa._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(n),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,xa.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return xa.NumCacheHitWithHash++,this._parameter.pipeline;const s=xa._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),xa.NumCacheMiss++,xa._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){xa.NumPipelineCreationLastFrame=xa._NumPipelineCreationCurrentFrame,xa._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,n,s,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(n),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[No.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[No.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=i_[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 n=0,s=0,a=0;for(let o=0;o=32&&(s=0,n++)}this._mrtFormats.length=a,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[No.MRTAttachments1]=i[0],this._states[No.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.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:i_[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:DI[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:DI[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:DI[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[No.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[No.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,n,s,a,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:DI[i],this._stencilFrontPassOp=n===null?2:DI[n],this._stencilFrontFailOp=s===null?1:DI[s],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,n=e.getSize();switch(t){case ee.BYTE:switch(n){case 1:case 2:return i?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case ee.UNSIGNED_BYTE:switch(n){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case ee.SHORT:switch(n){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case ee.UNSIGNED_SHORT:switch(n){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case ee.INT:switch(n){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case ee.UNSIGNED_INT:switch(n){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case ee.FLOAT:switch(n){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=${n}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:xa._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:xa._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:xa._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:xa._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:xa._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:xa._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[No.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,n=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,a=this._alphaToCoverageEnabled?1:0,o=i-1+(n<<1)+(s<<3)+(a<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[No.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.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:gX[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:gX[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:gX[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:gX[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[No.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.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[No.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,No.DepthStencilState))}_setVertexState(e){var c;const t=this._statesLength;let i=No.VertexState;const n=e._pipelineContext,s=n.shaderProcessingContext.attributeNamesFromEffect,a=n.shaderProcessingContext.attributeLocationsFromEffect;let o,l=0;for(let u=0;u0)for(let p=0;p=this._video.HAVE_CURRENT_DATA}dispose(){}}class Aee{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Aee._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],n=-1;i?n=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?ix.GetSamplerHashCode(t):0;const s=n!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var a;let i=this.textures[e],n=-1;i?n=((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=d_e.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const s=n!==((t==null?void 0:t.uniqueId)??-1);s&&this.updateId++,this.isDirty||(this.isDirty=s)}}Aee._Counter=0;class sV{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,ts.CopyDst|ts.Indirect|ts.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=sV._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}}sV._Counter=0;class C9{constructor(){this.values={}}}class vs{static get Statistics(){return{totalCreated:vs.NumBindGroupsCreatedTotal,lastFrameCreated:vs.NumBindGroupsCreatedLastFrame,lookupLastFrame:vs.NumBindGroupsLookupLastFrame,noLookupLastFrame:vs.NumBindGroupsNoLookupLastFrame}}static ResetCache(){vs._Cache=new C9,vs.NumBindGroupsCreatedTotal=0,vs.NumBindGroupsCreatedLastFrame=0,vs.NumBindGroupsLookupLastFrame=0,vs.NumBindGroupsNoLookupLastFrame=0,vs._NumBindGroupsCreatedCurrentFrame=0,vs._NumBindGroupsLookupCurrentFrame=0,vs._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){vs.NumBindGroupsCreatedLastFrame=vs._NumBindGroupsCreatedCurrentFrame,vs.NumBindGroupsLookupLastFrame=vs._NumBindGroupsLookupCurrentFrame,vs.NumBindGroupsNoLookupLastFrame=vs._NumBindGroupsNoLookupCurrentFrame,vs._NumBindGroupsCreatedCurrentFrame=0,vs._NumBindGroupsLookupCurrentFrame=0,vs._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var l,c,u,h,d,f;let n,s=vs._Cache;const a=this.disabled||i.forceBindGroupCreation;if(!a){if(!t.isDirty(i.updateId)&&!i.isDirty)return vs._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const p of e.shaderProcessingContext.bufferNames){const g=((l=t.buffers[p])==null?void 0:l.uniqueId)??0;let m=s.values[g];m||(m=new C9,s.values[g]=m),s=m}for(const p of e.shaderProcessingContext.samplerNames){const g=((c=i.samplers[p])==null?void 0:c.hashCode)??0;let m=s.values[g];m||(m=new C9,s.values[g]=m),s=m}for(const p of e.shaderProcessingContext.textureNames){const g=((h=(u=i.textures[p])==null?void 0:u.texture)==null?void 0:h.uniqueId)??0;let m=s.values[g];m||(m=new C9,s.values[g]=m),s=m}n=s.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,n)return t.bindGroups=n,vs._NumBindGroupsLookupCurrentFrame++,n;n=[],t.bindGroups=n,a||(s.bindGroups=n),vs.NumBindGroupsCreatedTotal++,vs._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let p=0;pE==="texture"?"":P)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[y].resource=this._cacheSampler.getSampler(A,!1,C.hashCode,A.label)}else ge.Error(`Sampler "${b}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(A,E)=>A==="texture"||A==="sampler"?"":E)}`,50)}else if(v.texture||v.storageTexture){const C=i.textures[b];if(C){if(this._engine.dbgSanityChecks&&C.texture===null){ge.Error(`Trying to bind a null texture! entry=${JSON.stringify(v)}, bindingInfo=${JSON.stringify(C,(E,P)=>E==="texture"?"":P)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const A=C.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!A||v.texture&&!A.view||v.storageTexture&&!A.viewForWriting)){ge.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(v)}, name=${b}, bindingInfo=${JSON.stringify(C,(E,P)=>E==="texture"?"":P)}, isReady=${(d=C.texture)==null?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[y].resource=v.storageTexture?A.viewForWriting:A.view}else ge.Error(`Texture "${b}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(A,E)=>A==="texture"||A==="sampler"?"":E)}`,50)}else if(v.externalTexture){const C=i.textures[b];if(C){if(this._engine.dbgSanityChecks&&C.texture===null){ge.Error(`Trying to bind a null external texture! entry=${JSON.stringify(v)}, name=${b}, bindingInfo=${JSON.stringify(C,(E,P)=>E==="texture"?"":P)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const A=C.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!A){ge.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(v)}, name=${b}, bindingInfo=${JSON.stringify(C,(E,P)=>E==="texture"?"":P)}, isReady=${(f=C.texture)==null?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}m[y].resource=this._device.importExternalTexture({source:A})}else ge.Error(`Texture "${b}" could not be bound. entry=${JSON.stringify(v)}, materialContext=${JSON.stringify(i,(A,E)=>A==="texture"||A==="sampler"?"":E)}`,50)}else if(v.buffer){const C=t.buffers[b];if(C){const A=C.underlyingResource;m[y].resource.buffer=A,m[y].resource.size=C.capacity}else ge.Error(`Can't find buffer "${b}". entry=${JSON.stringify(v)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const _=o[p];n[p]=this._device.createBindGroup({layout:_,entries:m})}return n}}vs.NumBindGroupsCreatedTotal=0;vs.NumBindGroupsCreatedLastFrame=0;vs.NumBindGroupsLookupLastFrame=0;vs.NumBindGroupsNoLookupLastFrame=0;vs._Cache=new C9;vs._NumBindGroupsCreatedCurrentFrame=0;vs._NumBindGroupsLookupCurrentFrame=0;vs._NumBindGroupsNoLookupCurrentFrame=0;const txt="clearQuadVertexShader",ixt=`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 } `;me.ShadersStoreWGSL[txt]=ixt;const rxt="clearQuadPixelShader",nxt=`uniform color: vec4f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;} `;me.ShadersStoreWGSL[rxt]=nxt;class sxt{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 S0(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,n,s=1){let a,o=null,l;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let m=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:Nn.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!n&&!!this._depthTextureFormat&&Nn.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(n?255:0),this._cacheRenderPipeline.setStencilCompare(n?519:512),this._cacheRenderPipeline.setStencilPassOp(n?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const u=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),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 g=this._bindGroups[p];if(!g){const m=h.bindGroupLayouts[0];g=this._bindGroups[p]=[],g.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${p}`,layout:m[0],entries:[]})),_f._SimplifiedKnownBindings||g.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${p}`,layout:m[1],entries:[]})),g.push(this._device.createBindGroup({label:`clearQuadBindGroup${_f._SimplifiedKnownBindings?1:2}-${p}`,layout:m[_f._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 m=0;m{const s=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,s},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==n)return null;throw s})}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 n=new BigUint64Array(t.getMappedRange()),s=Number(n[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},n=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw n})}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 n=new BigUint64Array(t.getMappedRange()),s=Number(n[1]-n[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,s},n=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw n})}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(n=>{t._addDuration(i,n!==null&&n>0?n:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class oxt{constructor(e,t,i,n=2,s){this._count=n,this._querySet=new xUe(e,n,"timestamp",t,i,!0,s)}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 lxt{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,n=50,s=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=s,this._allocateNewIndices(n)}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 Ad{async initTwgsl(e){if(!Ad._Twgsl)return e=e||{},e={...Ad._TWgslDefaultOptions,...e},e.twgsl?(Ad._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ie.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Ad._Twgsl=await self.twgsl(Ie.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Ad._Twgsl.convertSpirV2WGSL(e,Ad.DisableUniformityAnalysis||t);return Ad.ShowWGSLShaderCode&&(ge.Log(i),ge.Log("***********************************************")),Ad.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); `+i:i}}Ad._TWgslDefaultOptions={jsPath:`${Ie._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ie._DefaultCdnUrl}/twgsl/twgsl.wasm`};Ad.ShowWGSLShaderCode=!1;Ad.DisableUniformityAnalysis=!1;Ad._Twgsl=null;class cxt{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 uxt extends d_e{constructor(e){super(e)}}const ZMe={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},qMe={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},hxt=new at;class gr extends Qe{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 O1e(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return ge.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 j1e:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new gr(e,t);return new Promise(n=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>n(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 P1e,this._name="WebGPU",this._drawCalls=new zo,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,ge.Log(`Babylon.js v${Qe.Version} - ${this.description} engine`),!navigator.gpu){ge.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 Tyt,this._shaderProcessorWGSL=new kyt}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 n;this._glslang=i,this._tintWASM=new Ad,this._tintWASM.initTwgsl(this._twgslOptions??((n=this._options)==null?void 0:n.twgslOptions)).then(()=>{this._glslangAndTintAreFullyLoaded=!0,e()})})})),this._workingGlslangAndTintPromise}initAsync(e,t){return this.uniqueId=gr._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,navigator.gpu.requestAdapter(this._options).then(i=>{var n;if(i){this._adapter=i,this._adapterSupportedExtensions=[],(n=this._adapter.features)==null||n.forEach(o=>this._adapterSupportedExtensions.push(o)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(o=>{this._adapterInfo=o});const s=this._options.deviceDescriptor??{},a=(s==null?void 0:s.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);s.requiredFeatures=l}if(this._options.setMaximumLimits&&!s.requiredLimits){s.requiredLimits={};for(const o in this._adapterSupportedLimits)o==="minSubgroupSize"||o==="maxSubgroupSize"||(s.requiredLimits[o]=this._adapterSupportedLimits[o])}return s.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(s)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(i=>{var s,a;this._device=i,this._deviceEnabledExtensions=[],(s=this._device.features)==null||s.forEach(o=>this._deviceEnabledExtensions.push(o)),this._deviceLimits=i.limits;let n=-1;this._device.addEventListener("uncapturederror",o=>{++n{this._isDisposed||(this._contextWasLost=!0,ge.Warn("WebGPU context lost. "+o),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var p,g;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??((g=this._options)==null?void 0:g.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 CZ(this,this._device),this._textureHelper=new Yyt(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new ix(this._device),this._cacheBindGroups=new vs(this._device,this._cacheSampler,this),this._timestampQuery=new axt(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new lxt(this,this._device,this._bufferManager):void 0,this._bundleList=new y_e(this._device),this._snapshotRendering=new cxt(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),ts.Uniform|ts.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),ts.Uniform|ts.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,ge.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 ee(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new S0(this._device,this._emptyVertexBuffer),this._depthCullingState=new ext(this._cacheRenderPipeline),this._stencilStateComposer=new Jyt(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 sxt(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 ge.Error("A fatal error occurred during WebGPU creation/initialization."),i})}_initGlslang(e){return e=e||{},e={...gr._GlslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ie.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(Ie.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,supportIBLShadows:!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 JY],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 s={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(s),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new at(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new at(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 n={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:n}}_sharedInit(e){super._sharedInit(e),w1e(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 N1e(this,e,t,i)}_createImageBitmapFromSource(e,t){return L1e(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&F1e(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&B1e()}enterPointerlock(){this._renderingCanvas&&JJ(this._renderingCanvas)}exitPointerlock(){k1e()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){S0.ResetCache(),vs.ResetCache();const t=n=>{var s;for(const a of n){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)(s=o._materialContext)==null||s.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const n of this._uniformBuffers)n.name.indexOf("leftOver")<0&&i.push(n);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,s=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,n,s)}_compilePipelineStageDescriptor(e,t,i,n){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,a=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o=`#version 450 `,l=n===0?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),c=n===0?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),u=this._createPipelineStageDescriptor(l,c,n,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),u}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Kv(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Ayt(e,this)}createMaterialContext(){return new Aee}createDrawContext(){return new sV(this._bufferManager)}async _preparePipelineContext(e,t,i,n,s,a,o,l,c,u,h){const d=e,f=d.shaderProcessingContext.shaderLanguage;f===0&&!this._glslangAndTintAreFullyLoaded&&await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(ge.Log(["defines",l]),ge.Log(t),ge.Log(i),ge.Log("***********************************************")),d.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:a},n?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),n=e;for(let s=0;s0,a.is3D=c>0,a._cachedWrapU=0,a._cachedWrapV=0,a._useSRGBBuffer=s.useSRGBBuffer,a.label=s.label,this._internalTexturesCache.push(a),i||this._textureHelper.createGPUTextureForInternalTexture(a,o,l,u||1,s.creationFlags),a}createTexture(e,t,i,n,s=3,a=null,o=null,l=null,c=null,u=null,h=null,d,f,p,g){return this._createTextureBase(e,t,i,n,s,a,o,(m,_,y,v,x,b,C,A)=>{var P;const E=v;if(m.baseWidth=E.width,m.baseHeight=E.height,m.width=E.width,m.height=E.height,m.format=m.format!==-1?m.format:u??5,m.type=m.type!==-1?m.type:0,m._creationFlags=p??0,A(m.width,m.height,E,_,m,()=>{}),(P=m._hardwareTexture)!=null&&P.underlyingResource)!b&&!C&&this._generateMipmaps(m,this._uploadEncoder);else{const w=this._textureHelper.createGPUTextureForInternalTexture(m,E.width,E.height,void 0,p);Nn.IsImageBitmap(E)&&(this._textureHelper.updateTexture(E,m,E.width,E.height,m.depth,w.format,0,0,x,!1,0,0),!b&&!C&&this._generateMipmaps(m,this._uploadEncoder))}y&&y.removePendingData(m),m.isReady=!0,m.onLoadedObservable.notifyObservers(m),m.onLoadedObservable.clear()},()=>!1,l,c,u,h,d,f,g)}wrapWebGPUTexture(e){const t=new JY(e),i=new _n(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,n=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&n!==null&&(e._cachedWrapR=n)}updateTextureDimensions(e,t,i,n=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===n)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,n,s)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const a=i+"Sampler";this._currentMaterialContext.setSampler(a,t)}}}createPrefilteredCubeTexture(e,t,i,n,s=null,a=null,o,l=null,c=!0){const u=h=>{if(!h){s&&s(null);return}const d=h.texture;c?h.info.sphericalPolynomial&&(d._sphericalPolynomial=h.info.sphericalPolynomial):d._sphericalPolynomial=new wg,d._source=9,s&&s(d)};return this.createCubeTexture(e,t,null,!1,u,a,o,l,c,i,n)}setTexture(e,t,i,n){this._setTexture(e,i,!1,!1,n,n)}setTextureArray(e,t,i,n){for(let s=0;s{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),s(c)},l=>{this.isDisposed?s(new Uint8Array):a(l)})};n?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce(()=>{o()})})}readFromStorageBuffer(e,t,i,n,s){i=i||e.capacity;const a=this._bufferManager.createRawBuffer(i,ts.MapRead|ts.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,a,0,i),this._readFromGPUBuffer(a,i,n,s)}readFromMultipleStorageBuffers(e,t,i,n,s){i=i||e[0].capacity;const a=this._bufferManager.createRawBuffer(i*e.length,ts.MapRead|ts.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let o=0;o0;for(const s in e){const a=e[s],o=i[s],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&&n?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,g=p._texture._hardwareTexture;d!==void 0&&n?(u===0&&(f[d++].resource=this._cacheSampler.getSampler(p._texture)),f[d].resource=g.view):(a.indexInGroupEntries=f.length,u===0&&f.push({binding:c-1,resource:this._cacheSampler.getSampler(p._texture)}),f.push({binding:c,resource:g.view}));break}case 1:{const p=h,g=p._texture._hardwareTexture;g.textureAdditionalUsages&8||ge.Error(`computeDispatch: The texture (name=${p.name}, uniqueId=${p.uniqueId}) is not a storage texture!`,50),d!==void 0&&n?f[d].resource=g.viewForWriting:(a.indexInGroupEntries=f.length,f.push({binding:c,resource:g.viewForWriting}));break}case 6:{const g=h.underlyingResource;d!==void 0&&n?f[d].resource=this._device.importExternalTexture({source:g}):(a.indexInGroupEntries=f.length,f.push({binding:c,resource:this._device.importExternalTexture({source:g})}));break}case 2:case 3:case 7:{const p=u===7?h:h.getBuffer(),g=p.underlyingResource;d!==void 0&&n?(f[d].resource.buffer=g,f[d].resource.size=p.capacity):(a.indexInGroupEntries=f.length,f.push({binding:c,resource:{buffer:g,offset:0,size:p.capacity}}));break}}}for(let s=0;s0&&d.dispatchWorkgroups(i,n,s),d.end(),c&&(this._timestampQuery.endPass(this._timestampIndex,c),this._timestampIndex+=2)};gr.prototype.releaseComputeEffects=function(){for(const r in this._compiledComputeEffects){const e=this._compiledComputeEffects[r].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};gr.prototype._prepareComputePipelineContext=function(r,e,t,i,n){const s=r;this.dbgShowShaderCode&&(ge.Log(i),ge.Log(e)),s.sources={compute:e,rawCompute:t},s.stage=this._createComputePipelineStageDescriptor(e,i,n)};gr.prototype._releaseComputeEffect=function(r){this._compiledComputeEffects[r._key]&&(delete this._compiledComputeEffects[r._key],this._deleteComputePipelineContext(r.getPipelineContext()))};gr.prototype._rebuildComputeEffects=function(){for(const r in this._compiledComputeEffects){const e=this._compiledComputeEffects[r];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};gr.prototype._executeWhenComputeStateIsCompiled=function(r,e){r.stage.module.getCompilationInfo().then(t=>{const i={numErrors:0,messages:[]};for(const n of t.messages)n.type==="error"&&i.numErrors++,i.messages.push({type:n.type,text:n.message,line:n.lineNum,column:n.linePos,length:n.length,offset:n.offset});e(i)})};gr.prototype._deleteComputePipelineContext=function(r){r&&r.dispose()};gr.prototype._createComputePipelineStageDescriptor=function(r,e,t){return e?e="//"+e.split(` `).join(` //`)+` `:e="",{module:this._device.createShaderModule({code:e+r}),entryPoint:t}};gr.prototype._createDepthStencilCubeTexture=function(r,e){const t=new _n(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,r,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const n=t._hardwareTexture;return t.type=Nn.GetTextureTypeFromFormat(n.format),this._internalTexturesCache.push(t),t};gr.prototype.createCubeTexture=function(r,e,t,i,n=null,s=null,a,o=null,l=!1,c=0,u=0,h=null,d,f=!1,p=null){return this.createCubeTextureBase(r,e,t,!!i,n,s,a,o,l,c,u,h,null,(g,m)=>{const _=m,y=_[0].width,v=y;this._setCubeMapTextureParams(g,!i),g.format=a??-1;const x=this._textureHelper.createGPUTextureForInternalTexture(g,y,v);this._textureHelper.updateCubeTextures(_,x.underlyingResource,y,v,x.format,!1,!1,0,0),i||this._generateMipmaps(g,this._uploadEncoder),g.isReady=!0,g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear(),n&&n()},!!f,p)};gr.prototype._setCubeMapTextureParams=function(r,e,t){r.samplingMode=e?3:2,r._cachedWrapU=0,r._cachedWrapV=0,t&&(r._maxLodLevel=t)};gr.prototype.generateMipMapsForCubemap=function(r){var e;r.generateMipMaps&&((e=r._hardwareTexture)!=null&&e.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(r),this._generateMipmaps(r))};gr.prototype._debugPushGroup=function(r,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(r):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(r):this._pendingDebugCommands.push(["push",r]))};gr.prototype._debugPopGroup=function(r){this._options.enableGPUDebugMarkers&&(r===0||r===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};gr.prototype._debugInsertMarker=function(r,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(r):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(r):this._pendingDebugCommands.push(["insert",r]))};gr.prototype._debugFlushPendingCommands=function(){for(let r=0;r{e==null||e.removePendingData(d),c&&g&&c(g.status+" "+g.statusText,m)},p=g=>{const m=d.width,_=a(g);if(_){if(o){const y=i===4,v=o(_),x=d._hardwareTexture,b=[0,1,2,3,4,5];for(let C=0;C>C,E=[];for(let P=0;P<6;P++){let w=v[C][b[P]];y&&(w=aV(w,A,A,n)),E.push(new Uint8Array(w.buffer,w.byteOffset,w.byteLength))}this._textureHelper.updateCubeTextures(E,x.underlyingResource,A,A,x.format,h,!1,0,0)}}else this.updateRawCubeTexture(d,_,i,n,h);d.isReady=!0,e==null||e.removePendingData(d),l&&l()}};return this._loadFile(r,g=>{p(g)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};gr.prototype.createRawTexture3D=function(r,e,t,i,n,s,a,o,l=null,c=0,u=0){const d=new _n(this,10);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=n,d.type=c,d.generateMipMaps=s,d.samplingMode=o,d.is3D=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=r),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,u),this.updateRawTexture3D(d,r,n,a,l,c),this._internalTexturesCache.push(d),d};gr.prototype.updateRawTexture3D=function(r,e,t,i,n=null,s=0){if(this._doNotHandleContextLost||(r._bufferView=e,r.format=t,r.invertY=i,r._compression=n),e){const a=r._hardwareTexture;t===4&&(e=aV(e,r.width,r.height,s));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,r,r.width,r.height,r.depth,a.format,0,0,i,!1,0,0),r.generateMipMaps&&this._generateMipmaps(r,this._uploadEncoder)}r.isReady=!0};gr.prototype.createRawTexture2DArray=function(r,e,t,i,n,s,a,o,l=null,c=0,u=0){const d=new _n(this,11);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=n,d.type=c,d.generateMipMaps=s,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=r),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,u),this.updateRawTexture2DArray(d,r,n,a,l,c),this._internalTexturesCache.push(d),d};gr.prototype.updateRawTexture2DArray=function(r,e,t,i,n=null,s=0){if(this._doNotHandleContextLost||(r._bufferView=e,r.format=t,r.invertY=i,r._compression=n),e){const a=r._hardwareTexture;t===4&&(e=aV(e,r.width,r.height,s));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,r,r.width,r.height,r.depth,a.format,0,0,i,!1,0,0),r.generateMipMaps&&this._generateMipmaps(r,this._uploadEncoder)}r.isReady=!0};function aV(r,e,t,i){let n,s=1;i===1?n=new Float32Array(e*t*4):i===2?(n=new Uint16Array(e*t*4),s=15360):i===7?n=new Uint32Array(e*t*4):n=new Uint8Array(e*t*4);for(let a=0;a0,r.is3D=c>0,r.depth=l||c,r.isReady=!0,r.samples=s,r.generateMipMaps=!1,r.samplingMode=i?2:1,r.type=1,r._comparisonFunction=n,r._cachedWrapU=0,r._cachedWrapV=0};gr.prototype.updateRenderTargetTextureSampleCount=function(r,e){return!r||!r.texture||r.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(r.texture,e),r._depthStencilTexture&&(this._textureHelper.createMSAATexture(r._depthStencilTexture,e),r._depthStencilTexture.samples=e),r._samples=e,r.texture.samples=e),e};gr.prototype.createRenderTargetCubeTexture=function(r,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,r),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 n=new _n(this,5);return n.width=r,n.height=r,n.depth=0,n.isReady=!0,n.isCube=!0,n.samples=i.samples,n.generateMipMaps=i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n.format=i.format,this._internalTexturesCache.push(n),t.setTextures(n),(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&&(n.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(n),e&&e.createMipMaps&&!i.generateMipMaps&&(n.generateMipMaps=!1),t};gr.prototype.setDepthStencilTexture=function(r,e,t,i){!t||!t.depthStencilTexture?this._setTexture(r,null,void 0,void 0,i):this._setTexture(r,t,!1,!0,i)};function fxt(r){return!!(r&&r.underlyingResource!==void 0)}gr.prototype.updateVideoTexture=function(r,e,t){var n;if(!r||r._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=r._hardwareTexture;if((n=r._hardwareTexture)!=null&&n.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(r)),fxt(e)){if(e.isReady()){try{this._textureHelper.copyVideoToTexture(e,r,i.format,!t),r.generateMipMaps&&this._generateMipmaps(r)}catch{}r.isReady=!0}}else e&&this.createImageBitmap(e).then(s=>{this._textureHelper.updateTexture(s,r,r.width,r.height,r.depth,i.format,0,0,!t,!1,0,0),r.generateMipMaps&&this._generateMipmaps(r),r.isReady=!0}).catch(()=>{r.isReady=!0})};class pxt{static async CreateAsync(e,t){return await gr.IsSupportedAsync?gr.CreateAsync(e,t):Vt.IsSupported?new Vt(e,void 0,t):new Jke(t)}}class Mp{}Mp.COPY=1;Mp.CUT=2;Mp.PASTE=3;class eQ{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return Mp.COPY;case 86:return Mp.PASTE;case 88:return Mp.CUT;default:return-1}}}class dp extends Aa{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Pe.Gray(),i=Tn.DefaultUtilityLayer,n=null,s=1,a=Pe.Yellow(),o=Pe.Gray()){var b,C,A,E,P,w,M;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ce,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new O(0,0,0),this._incrementalStartupValue=O.Zero(),this._parent=n,this._coloredMaterial=new ct("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Pe(.1,.1,.1)),this._hoverMaterial=new ct("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._disableMaterial=new ct("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Re("axis",i.utilityLayerScene);const{arrowMesh:l,arrowTail:c}=this._createGizmoMesh(this._gizmoMesh,s),u=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Aa.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},g=()=>{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 Kl({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let m=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()),D=this._tmpVector;let k=!1,z=0;if(this.uniformScaling?D.setAll(.57735):D.copyFrom(e),this.snapDistance==0)D.scaleToRef(I,D);else{m+=I,_+=I;const U=this.incrementalSnap?_:m;Math.abs(U)>this.snapDistance?(z=Math.floor(Math.abs(U)/this.snapDistance),U<0&&(z*=-1),m=m%this.snapDistance,D.scaleToRef(this.snapDistance*z,D),k=!0):D.scaleInPlace(0)}D.addInPlaceFromFloats(1,1,1),D.x=Math.abs(D.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,oe.Quaternion[0],oe.Vector3[2],Aa.PreserveScaling?W:void 0),D.addInPlace(this._incrementalStartupValue),D.addInPlaceFromFloats(-1,-1,-1),D.x=Math.abs(D.x)*(this._incrementalStartupValue.x>0?1:-1),D.y=Math.abs(D.y)*(this._incrementalStartupValue.y>0?1:-1),D.z=Math.abs(D.z)*(this._incrementalStartupValue.z>0?1:-1),pe.ComposeToRef(D,oe.Quaternion[0],oe.Vector3[2],oe.Matrix[1])):(pe.ScalingToRef(D.x,D.y,D.z,oe.Matrix[2]),oe.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),oe.Matrix[1])),oe.Matrix[1].decompose(oe.Vector3[1],void 0,void 0,Aa.PreserveScaling?W:void 0);const K=1e5;Math.abs(oe.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,Aa.PreserveScaling?R:void 0),m=0,_=0}),this.dragBehavior.onDragObservable.add(R=>p(R.dragDistance)),this.dragBehavior.onDragEndObservable.add(g),(A=(C=(b=n==null?void 0:n.uniformScaleGizmo)==null?void 0:b.dragBehavior)==null?void 0:C.onDragObservable)==null||A.add(R=>p(R.delta.y)),(w=(P=(E=n==null?void 0:n.uniformScaleGizmo)==null?void 0:E.dragBehavior)==null?void 0:P.onDragEndObservable)==null||w.add(g);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 D,k,z,W;if(this._customMeshSet)return;let I=(D=this._parent)==null?void 0:D.getAxisCache(this._gizmoMesh);if(this._isHovered=!!I&&I.colliderMeshes.indexOf((k=R==null?void 0:R.pickInfo)==null?void 0:k.pickedMesh)!=-1,I=(z=this._parent)==null?void 0:z.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!!I&&I.colliderMeshes.indexOf((W=R==null?void 0:R.pickInfo)==null?void 0:W.pickedMesh)!=-1),!this._parent){const K=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,K)}}),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 n=jh("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=zu("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return n.scaling.scaleInPlace(.1),n.material=this._coloredMaterial,n.rotation.x=Math.PI/2,n.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.275/2,s.rotation.x=Math.PI/2,i&&(n.visibility=0,s.visibility=0),e.addChild(n),e.addChild(s),{arrowMesh:n,arrowTail:s}}_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)}}dp.MinimumAbsoluteScale=Ki;class x_e extends Aa{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let n=0;n<3;n++)for(let s=0;s<3;s++)for(let a=0;a<3;a++){const o=(n===1?1:0)+(s===1?1:0)+(a===1?1:0);if(!(o===1||o===3)){if(t[i]){const l=new O(n-1,s-1,a-1);l.multiplyInPlace(this._axisFactor),t[i].setEnabled(l.lengthSquared()>Ki)}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 Pe(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(t=>{t.color&&(t.color=e)})}constructor(e=Pe.Gray(),t=Tn.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new O(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateAnchorsDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new Oe,this._tmpVector=new O(0,0,0),this._tmpRotationMatrix=new pe,this._incrementalStartupValue=O.Zero(),this._incrementalAnchorStartupValue=O.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 Ce,this.onScaleBoxDragObservable=new Ce,this.onScaleBoxDragEndObservable=new Ce,this.onRotationSphereDragObservable=new Ce,this.onRotationSphereDragEndObservable=new Ce,this.scalePivot=null,this._axisFactor=new O(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new O,this._dragMesh=null,this._pointerDragBehavior=new Kl,this._cornerMesh=null,this.updateScale=!1,this._anchorMesh=new Yt("anchor",t.utilityLayerScene),this._coloredMaterial=new ct("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new ct("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Yt("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new Oe;const i=[];i.push(zs("lines",{points:[new O(0,0,0),new O(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,0,0),new O(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,0,0),new O(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(this._boundingDimensions.x,0,0),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(this._boundingDimensions.x,0,0),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,this._boundingDimensions.y,0),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,this._boundingDimensions.y,0),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,0,this._boundingDimensions.z),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(0,0,this._boundingDimensions.z),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(zs("lines",{points:[new O(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new O(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach(s=>{s.color=e,s.position.addInPlace(new O(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),s.isPickable=!1,this._lineBoundingBox.addChild(s)}),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateAnchorsParent=new Yt("",t.utilityLayerScene),this._rotateAnchorsParent.rotationQuaternion=new Oe;for(let s=0;s<12;s++){const a=jh("",{width:.4,height:.4,depth:1.6},t.utilityLayerScene);a.rotationQuaternion=new Oe,a.material=this._coloredMaterial,a.isNearGrabbable=!0;const o=new Kl({});o.moveAttached=!1,o.updateDragPlane=!1,a.addBehavior(o);const l=new O(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)){ge.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}Bn._RemoveAndStorePivotPoint(this.attachedMesh);const f=l,p=h.dragPlaneNormal.scale(O.Dot(h.dragPlaneNormal,f)),g=f.subtract(p).normalizeToNew();let m=O.Dot(g,h.delta)<0?Math.abs(h.delta.length()):-Math.abs(h.delta.length());if(m=m/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=Oe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=Oe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),c+=m,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*_;m=y-u,u=y}s>=8?Oe.RotationYawPitchRollToRef(0,0,m,this._tmpQuaternion):s>=4?Oe.RotationYawPitchRollToRef(m,0,0,this._tmpQuaternion):Oe.RotationYawPitchRollToRef(0,m,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(),Bn._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 Yt("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new Oe;for(let s=0;s<3;s++)for(let a=0;a<3;a++)for(let o=0;o<3;o++){const l=(s===1?1:0)+(a===1?1:0)+(o===1?1:0);if(l===1||l===3)continue;const c=l===2?jh("",{size:1},t.utilityLayerScene):this._getCornerMesh(t);l===0&&(c.rotationQuaternion=Oe.FromEulerAngles(a*.25*Math.PI,(o+3*s-s*o)*.25*Math.PI,0)),c.material=this._coloredMaterial,c._internalMetadata=l===2,c.isNearGrabbable=!0;const u=new O(s-1,a-1,o-1).normalize(),h=new Kl({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 g=this.attachedMesh.parent;if(g&&g.scaling&&g.scaling.isNonUniformWithinEpsilon(.001)){ge.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");return}Bn._RemoveAndStorePivotPoint(this.attachedMesh);let m=p.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(d+=m,this.scalingSnapDistance>0){const v=Math.floor(Math.abs(d)/this.scalingSnapDistance)*(d<0?-1:1),x=this.scalingSnapDistance*v;m=x-f,f=x}const _=new O(m,m,m),y=new O(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),O.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),O.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 n=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add(s=>{n[s.event.pointerId]?s.pickInfo&&s.pickInfo.pickedMesh!=n[s.event.pointerId]&&(n[s.event.pointerId].material=this._coloredMaterial,delete n[s.event.pointerId],this._isHovered=!1):this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(a=>{s.pickInfo&&s.pickInfo.pickedMesh==a&&(n[s.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=jh("",{width:.4,height:.4,depth:1.6},e.utilityLayerScene);t.position.z=.6;const i=jh("",{width:.4,height:1.6,depth:.4},e.utilityLayerScene);i.position.y=.6;const n=jh("",{width:1.6,height:.4,depth:.4},e.utilityLayerScene);return n.position.x=.6,this._cornerMesh=Re.MergeMeshes([n,i,t],!0),this._cornerMesh}return this._cornerMesh.clone()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Bn._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Bn._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){Bn._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=Oe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=Oe.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),Bn._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 n=0;n<2;n++){const s=t*4+i*2+n;if(t==0&&e[s].position.set(0,this._boundingDimensions.y*(i-.5),this._boundingDimensions.z*(n-.5)),t==1&&e[s].position.set(this._boundingDimensions.x*(i-.5),0,this._boundingDimensions.z*(n-.5)),t==2&&e[s].position.set(this._boundingDimensions.x*(i-.5),this._boundingDimensions.y*(n-.5),0),t===0?Oe.FromEulerAnglesToRef(0,Math.PI*.5,0,e[s].rotationQuaternion):t===1&&Oe.FromEulerAnglesToRef(Math.PI*.5,0,0,e[s].rotationQuaternion),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const a=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[s].scaling.set(a,a,a)}else this.fixedDragMeshBoundsSize?e[s].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[s].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 n=0;n<3;n++)for(let s=0;s<3;s++){const a=(i===1?1:0)+(n===1?1:0)+(s===1?1:0);if(!(a===1||a===3)){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(n/2),this._boundingDimensions.z*(s/2)),e[t].position.addInPlace(new O(-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 n=e;t&&i._internalMetadata===!0&&(n=!1),i.setEnabled(n)})}_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=jh("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new Oe,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=Oe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),n=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const s=jh("box",{size:1},e.getScene()),a=e.getHierarchyBoundingVectors();return a.max.subtractToRef(a.min,s.scaling),s.scaling.y===0&&(s.scaling.y=Ki),s.scaling.x===0&&(s.scaling.x=Ki),s.scaling.z===0&&(s.scaling.z=Ki),s.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(s),e.rotationQuaternion.copyFrom(n),e.position.copyFrom(i),e.removeChild(s),s.addChild(e),s.visibility=0,s}setCustomMesh(){ge.Error("Custom meshes are not supported on this gizmo")}}class O0 extends Aa{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=Pe.Gray(),i=Tn.DefaultUtilityLayer,n=32,s=null,a=!1,o=1,l=Pe.Yellow(),c=Pe.Gray()){var C;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ce,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new O,this._parent=s,this._coloredMaterial=new ct("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Pe(.1,.1,.1)),this._hoverMaterial=new ct("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=l,this._hoverMaterial.specularColor=l,this._disableMaterial=new ct("",i.utilityLayerScene),this._disableMaterial.diffuseColor=c,this._disableMaterial.alpha=.4,this._gizmoMesh=new Re("",i.utilityLayerScene);const{rotationMesh:u,collider:h}=this._createGizmoMesh(this._gizmoMesh,o,n);this._rotationDisplayPlane=U_("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=Math.PI*.5,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Sr.ShadersStore.rotationGizmoVertexShader=O0._RotationGizmoVertexShader,Sr.ShadersStore.rotationGizmoFragmentShader=O0._RotationGizmoFragmentShader,this._rotationShaderMaterial=new ua("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,Aa.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Kl({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=O0.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const d=new O,f=new pe,p=new O;let g=new O;this.dragBehavior.onDragStartObservable.add(A=>{this.attachedNode&&(d.copyFrom(A.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(f),O.TransformCoordinatesToRef(A.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(A.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});const m={snapDistance:0};let _=0;const y=new pe,v=new Oe;this.dragBehavior.onDragObservable.add(A=>{if(this.attachedNode){const E=new O(1,1,1),P=new Oe(0,0,0,1),w=new O(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(E,P,w),!(Math.abs(Math.abs(E.x)-Math.abs(E.y))<=Ki&&Math.abs(Math.abs(E.x)-Math.abs(E.z))<=Ki)&&this.updateGizmoRotationToMatchAttachedMesh){ge.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}P.normalize();const R=this.updateGizmoPositionToMatchAttachedMesh?w:this._rootMesh.absolutePosition,I=A.dragPlanePoint.subtract(R).normalize(),D=d.subtract(R).normalize(),k=O.Cross(I,D),z=O.Dot(I,D);let W=Math.atan2(k.length(),z)*this.sensitivity;p.copyFrom(e),g.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(P.toRotationMatrix(f),g=O.TransformCoordinates(p,f));let K=!1;if(i.utilityLayerScene.activeCamera){const G=i.utilityLayerScene.activeCamera.position.subtract(R).normalize();O.Dot(G,g)>0&&(p.scaleInPlace(-1),g.scaleInPlace(-1),K=!0)}O.Dot(g,k)>0&&(W=-W),oe.Vector3[0].set(W,0,0),this.dragBehavior.validateDrag(oe.Vector3[0])||(W=0);let j=!1;if(this.snapDistance!=0)if(_+=W,Math.abs(_)>this.snapDistance){let G=Math.floor(Math.abs(_)/this.snapDistance);_<0&&(G*=-1),_=_%this.snapDistance,W=this.snapDistance*G,j=!0}else W=0;const B=Math.sin(W/2);if(v.set(p.x*B,p.y*B,p.z*B,Math.cos(W/2)),y.determinant()>0){const G=new O;v.toEulerAnglesToRef(G),Oe.RotationYawPitchRollToRef(G.y,-G.x,-G.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)P.multiplyToRef(v,P),P.normalize(),pe.ComposeToRef(E,P,w,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(oe.Matrix[0]);const G=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(oe.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(G)}d.copyFrom(A.dragPlanePoint),j&&(m.snapDistance=W,this.onSnapObservable.notifyObservers(m)),this._angles.y+=W,this.angle+=K?-W:W,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[h],gizmoMeshes:[u],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};(C=this._parent)==null||C.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(A=>{var E;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=O0.MaxDragAngle,this._isHovered=b.colliderMeshes.indexOf((E=A==null?void 0:A.pickInfo)==null?void 0:E.pickedMesh)!=-1,!this._parent)){const P=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,P)}}),this.dragBehavior.onEnabledObservable.add(A=>{this._setGizmoMeshMaterial(b.gizmoMeshes,A?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){const n=Pg("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);n.visibility=0;const s=Pg("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,n.rotation.x=Math.PI/2,e.addChild(s,Aa.PreserveScaling),e.addChild(n,Aa.PreserveScaling),{rotationMesh:s,collider:n}}_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()}}O0.MaxDragAngle=Math.PI*9/20;O0._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; }`;O0._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 b_e extends Aa{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&&ge.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=Tn.DefaultUtilityLayer,t=32,i=!1,n=1,s,a){super(e),this.onDragStartObservable=new Ce,this.onDragObservable=new Ce,this.onDragEndObservable=new Ce,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=a&&a.xOptions&&a.xOptions.color?a.xOptions.color:Pe.Red().scale(.5),l=a&&a.yOptions&&a.yOptions.color?a.yOptions.color:Pe.Green().scale(.5),c=a&&a.zOptions&&a.zOptions.color?a.zOptions.color:Pe.Blue().scale(.5);this.xGizmo=new O0(new O(1,0,0),o,e,t,this,i,n),this.yGizmo=new O0(new O(0,1,0),l,e,t,this,i,n),this.zGizmo=new O0(new O(0,0,1),c,e,t,this,i,n),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,s?s.addToAxisCache(this._gizmoAxisCache):Aa.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(){ge.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 a5 extends Aa{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new Yt("plane",e),n=U_("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return n.material=t,n.parent=i,i}constructor(e,t=Pe.Gray(),i=Tn.DefaultUtilityLayer,n=null,s=Pe.Yellow(),a=Pe.Gray()){var d;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new Ce,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=n,this._coloredMaterial=new ct("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Pe(.1,.1,.1)),this._hoverMaterial=new ct("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=s,this._disableMaterial=new ct("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a,this._disableMaterial.alpha=.4,this._gizmoMesh=a5._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 O,c={snapDistance:0};this.dragBehavior=new Kl({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(oe.Vector3[0]),oe.Vector3[0].addToRef(f.delta,oe.Vector3[0]),this.dragBehavior.validateDrag(oe.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(oe.Vector3[0]),oe.Vector3[0].addToRef(l,oe.Vector3[0]),this.dragBehavior.validateDrag(oe.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 g=h.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(h.gizmoMeshes,g)}}),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 Eee extends Aa{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=Tn.DefaultUtilityLayer,t=1,i,n){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ce,this.onDragObservable=new Ce,this.onDragEndObservable=new Ce,this._planarGizmoEnabled=!1,this.xGizmo=new hp(new O(1,0,0),Pe.Red().scale(.5),e,this,t),this.yGizmo=new hp(new O(0,1,0),Pe.Green().scale(.5),e,this,t),this.zGizmo=new hp(new O(0,0,1),Pe.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new a5(new O(1,0,0),Pe.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new a5(new O(0,1,0),Pe.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new a5(new O(0,0,1),Pe.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=n==null?void 0:n.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):Aa.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(){ge.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 C_e extends Aa{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=Tn.DefaultUtilityLayer,t=1,i,n){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new Ce,this.onDragObservable=new Ce,this.onDragEndObservable=new Ce,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new dp(new O(1,0,0),Pe.Red().scale(.5),e,this,t),this.yGizmo=new dp(new O(0,1,0),Pe.Green().scale(.5),e,this,t),this.zGizmo=new dp(new O(0,0,1),Pe.Blue().scale(.5),e,this,t),this.additionalTransformNode=n==null?void 0:n.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach(s=>{s.dragBehavior.onDragStartObservable.add(()=>{this.onDragStartObservable.notifyObservers({})}),s.dragBehavior.onDragObservable.add(()=>{this.onDragObservable.notifyObservers({})}),s.dragBehavior.onDragEndObservable.add(()=>{this.onDragEndObservable.notifyObservers({})})}),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):Aa.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new ct("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Pe.Gray(),this._hoverMaterial=new ct("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Pe.Yellow(),this._disableMaterial=new ct("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Pe.Gray(),this._disableMaterial.alpha=.4;const e=new dp(new O(0,1,0),Pe.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=sE("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=sE("",{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)})):ge.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&&ge.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 mxt{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=Tn.DefaultUtilityLayer,n=Tn.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new Ce,this.onAttachedToNodeObservable=new Ce,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Pe.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new p9e,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=n,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const s=this._attachToMeshPointerObserver(e),a=Aa.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[s,a]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add(i=>{if(this.usePointerToAttachGizmos&&i.type==Wt.POINTERDOWN)if(i.pickInfo&&i.pickInfo.pickedMesh){if(this.enableAutoPicking){let n=i.pickInfo.pickedMesh;if(this.attachableMeshes==null)for(;n&&n.parent!=null;)n=n.parent;else{let s=!1;this.attachableMeshes.forEach(a=>{n&&(n==a||n.isDescendantOf(a))&&(n=a,s=!0)}),s||(n=null)}n instanceof vr?this._attachedMesh!=n&&this.attachToMesh(n):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 Eee(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 b_e(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 C_e(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 x_e(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 n=this.gizmos[i];n&&n.dispose()}this._defaultKeepDepthUtilityLayer!==Tn._DefaultKeepDepthUtilityLayer&&((e=this._defaultKeepDepthUtilityLayer)==null||e.dispose()),this._defaultUtilityLayer!==Tn._DefaultUtilityLayer&&((t=this._defaultUtilityLayer)==null||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class nb extends Dr{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=pe.Identity(),this._projectionMatrix=pe.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=O.Zero()),O.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=O.Zero()),O.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=O.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=O.Cross(this.direction,go.Y),t=O.Cross(e,this.direction);return O.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=O.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=pe.Identity()),pe.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=oe.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),O.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(O.Dot(t,O.Up()))===1&&(t.z=1e-13);const n=oe.Vector3[1];return i.addToRef(t,n),pe.LookAtLHToRef(i,n,O.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}V([ta()],nb.prototype,"position",null);V([ta()],nb.prototype,"direction",null);V([Q()],nb.prototype,"shadowMinZ",null);V([Q()],nb.prototype,"shadowMaxZ",null);Dn.AddNodeConstructor("Light_Type_1",(r,e)=>()=>new qc(r,O.Zero(),e));class qc extends nb{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 Dr.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&&pe.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 n=this.getScene().activeCamera;if(!n)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const u=O.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 s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:n.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:n.maxZ,c=this.getScene().getEngine().useReverseDepthBuffer;pe.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*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}}V([Q()],qc.prototype,"shadowFrustumSize",null);V([Q()],qc.prototype,"shadowOrthoScale",null);V([Q()],qc.prototype,"autoUpdateExtends",void 0);V([Q()],qc.prototype,"autoCalcShadowZBounds",void 0);V([Q("orthoLeft")],qc.prototype,"_orthoLeft",void 0);V([Q("orthoRight")],qc.prototype,"_orthoRight",void 0);V([Q("orthoTop")],qc.prototype,"_orthoTop",void 0);V([Q("orthoBottom")],qc.prototype,"_orthoBottom",void 0);xe("BABYLON.DirectionalLight",qc);function Jk(r,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=bu("",{slice:.5,diameter:e.diameter,segments:e.segments},t),n=lD("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);n.rotation.x=-Math.PI/2,n.parent=i;const s=Re.MergeMeshes([n,i],!0);return s.name=r,s}const gxt={CreateHemisphere:Jk};Re.CreateHemisphere=(r,e,t,i)=>Jk(r,{segments:e,diameter:t},i);Dn.AddNodeConstructor("Light_Type_2",(r,e)=>()=>new Nc(r,O.Zero(),O.Zero(),0,0,e));class Nc extends nb{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()&&(Nc._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):Nc._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,n,s,a){super(e,a),this._innerAngle=0,this._projectionTextureMatrix=pe.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=O.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=O.Zero(),this._projectionTextureViewLightMatrix=pe.Zero(),this._projectionTextureProjectionLightMatrix=pe.Zero(),this._projectionTextureScalingMatrix=pe.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=n,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Dr.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:n.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;pe.PerspectiveFovLHToRef(s,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),pe.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),n=-i*t,s=1/Math.tan(this._angle/2);pe.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof be){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;pe.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=O.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=O.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=O.Normalize(this.transformedDirection):i=O.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())}}V([Q()],Nc.prototype,"angle",null);V([Q()],Nc.prototype,"innerAngle",null);V([Q()],Nc.prototype,"shadowAngleScale",null);V([Q()],Nc.prototype,"exponent",void 0);V([Q()],Nc.prototype,"projectionTextureLightNear",null);V([Q()],Nc.prototype,"projectionTextureLightFar",null);V([Q()],Nc.prototype,"projectionTextureUpDirection",null);V([ki("projectedLightTexture")],Nc.prototype,"_projectionTexture",void 0);xe("BABYLON.SpotLight",Nc);class b0 extends Aa{constructor(e=Tn.DefaultUtilityLayer){super(e),this._cachedPosition=new O,this._cachedForward=new O(0,0,1),this._pointerObserver=null,this.onClickedObservable=new Ce,this._light=null,this.attachedMesh=new Re("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Yt("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new ct("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Pe(.5,.5,.5),this._material.specularColor=new Pe(.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))},Wt.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){ge.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 Tp?this._lightMesh=b0._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof qc?this._lightMesh=b0._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Nc?this._lightMesh=b0._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=b0._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 Oe,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(oe.Vector3[0]),e=oe.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 O(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(O.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new O(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else O.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 Re("hemisphereLight",e),i=Jk(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;const n=this._CreateLightLines(3,e);return n.parent=t,t.scaling.scaleInPlace(b0._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Re("pointLight",e),i=bu(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;const n=this._CreateLightLines(5,e);return n.parent=t,t.scaling.scaleInPlace(b0._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Re("spotLight",e),i=bu(t.name,{segments:10,diameter:1},e);i.parent=t;const n=Jk(t.name,{segments:10,diameter:2},e);n.parent=t,n.rotation.x=-Math.PI/2;const s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(b0._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Re("directionalLight",e),i=new Re(t.name,e);i.parent=t;const n=bu(t.name,{diameter:1.2,segments:10},e);n.parent=i;const s=zu(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=1.25;let o=s.clone(t.name);o.scaling.y=.5,o.position.x+=-1.25;const l=zu(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(b0._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}b0._Scale=.007;b0._CreateLightLines=(r,e)=>{const i=new Re("root",e);i.rotation.x=Math.PI/2;const n=new Re("linePivot",e);n.parent=i;const s=zu("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},e);if(s.position.y=s.scaling.y/2+1.2,s.parent=n,r<2)return n;for(let o=0;o<4;o++){const l=n.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(r<3)return i;for(let o=0;o<4;o++){const l=n.clone("linePivotClone");l.rotation.z=Math.PI/2,l.rotation.y=Math.PI/2*o}if(r<4)return i;for(let o=0;o<4;o++){const l=n.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(r<5)return i;const a=n.clone("linePivotClone");return a.rotation.z=Math.PI,i};class o5 extends Aa{constructor(e=Tn.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new Ce,this._camera=null,this._invProjection=new pe,this._material=new ct("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Pe(.5,.5,.5),this._material.specularColor=new Pe(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(n=>{this._camera&&(this._isHovered=!!(n.pickInfo&&this._rootMesh.getChildMeshes().indexOf(n.pickInfo.pickedMesh)!=-1),this._isHovered&&n.event.button===0&&this.onClickedObservable.notifyObservers(this._camera))},Wt.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=o5._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(s=>{s.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 at(1,1,1,1);this._cameraLinesMesh=o5._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([je(()=>Promise.resolve().then(()=>aPt),void 0),je(()=>Promise.resolve().then(()=>cPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>QIt),void 0),je(()=>Promise.resolve().then(()=>JIt),void 0)])),super._gatherImports(e,t)}updateEffect(e=null,t=null,i=null,n,s,a){this._updateParameters(s,a)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let s=[],a=[],o=0;for(let m=0;m0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,n=-(e*e/(2*t*t));return 1/i*Math.exp(n)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,n){return ot.Parse(()=>new Dl(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,n)}}V([Q("kernel")],Dl.prototype,"_kernel",void 0);V([Q("packedFloat")],Dl.prototype,"_packedFloat",void 0);V([Cz()],Dl.prototype,"direction",void 0);xe("BABYLON.BlurPostProcess",Dl);class Hv extends vn{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,n,s=0,a=be.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,n,!0,s,!1,a,o),this.mirrorPlane=new Dc(0,1,0,1),this._transformMatrix=pe.Zero(),this._mirrorMatrix=pe.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()),pe.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=O.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 Dl("horizontal blur",new Ne(1,0),this._blurKernelX,this._blurRatio,null,be.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 Dl("vertical blur",new Ne(0,1),this._blurKernelY,this._blurRatio,null,be.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 Hv(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()}}be._CreateMirror=(r,e,t,i)=>new Hv(r,e,t,i);const eRe=.8;class Za extends Cn{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(pe.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let n="";return e.forEach(s=>n+=s),new Za(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const a=new Za(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=s,a}constructor(e,t,i=null,n=!1,s=null,a=null,o=null,l=5,c=!1,u=null,h=!1,d=eRe,f=0,p,g){var y;super(t),this.onLoadObservable=new Ce,this.boundingBoxPosition=O.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new pe,this._buffer=null,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=pe.Identity(),this.coordinatesMode=be.CUBIC_MODE;let m=null,_=null;i!==null&&!Array.isArray(i)?(m=i.extensions??null,this._noMipmap=i.noMipmap??!1,s=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??eRe,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,a=i.onLoad??null,o=i.onError??null):(this._noMipmap=n,this._format=l,this._createPolynomials=h,m=i,this._loaderOptions=p,this._useSRGBBuffer=g,this._lodScale=d,this._lodOffset=f),!(!e&&!s)&&this.updateURL(e,u,a,c,o,m,(y=this.getScene())==null?void 0:y.useDelayedTextureLoading,s,_)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,n=!1,s=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=n,n&&(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 g=0;go.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!((a=this.getScene())!=null&&a.useRightHandedSystem)))return;const t=oe.Vector3[0],i=oe.Quaternion[0],n=oe.Vector3[1];this._textureMatrix.decompose(t,i,n),i.z*=-1,i.w*=-1,pe.ComposeToRef(t,i,n,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(),n=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const s=()=>{var l;this.onLoadObservable.notifyObservers(this),n&&(n.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),be.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ie.SetImmediate(()=>s()):this._texture.onLoadedObservable.add(()=>s()):(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 n=ot.Parse(()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new Za(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=O.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=O.FromArray(e.boundingBoxSize)),e.animations)for(let s=0;s{const i=new Za(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}V([Q()],Za.prototype,"url",void 0);V([ta()],Za.prototype,"boundingBoxPosition",void 0);V([ta()],Za.prototype,"boundingBoxSize",null);V([Q("rotationY")],Za.prototype,"rotationY",null);V([Q("files")],Za.prototype,"_files",void 0);V([Q("forcedExtension")],Za.prototype,"_forcedExtension",void 0);V([Q("extensions")],Za.prototype,"_extensions",void 0);V([DJ("textureMatrix")],Za.prototype,"_textureMatrix",void 0);V([DJ("textureMatrixRefraction")],Za.prototype,"_textureMatrixRefraction",void 0);be._CubeTextureParser=Za.Parse;xe("BABYLON.CubeTexture",Za);class _xt extends Kn{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 Qr extends Va{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=Qr.StandardReflectance0*t,this.reflectionReflectance90=Qr.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=Qr.StandardReflectance0+(1-Qr.StandardReflectance0)*t,this.reflectionReflectance90=Qr.StandardReflectance90+(1-Qr.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=Pe.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=O.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 Go(16),this._reflectionControls=It.Zero(),this._white=Pe.White(),this._primaryShadowColor=Pe.Black(),this._primaryHighlightColor=Pe.Black(),this._shadersLoaded=!1;const n=this.getScene().getEngine();n.isWebGPU&&!i&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new Ci(n,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 n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new _xt);const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(Xu(s,e,a,!1,this._maxSimultaneousLights),a._needNormals=!0,rD(s,a),a._areTexturesDirty){if(a._needUVs=!1,s.texturesEnabled){if(s.getEngine().getCaps().textureLOD&&(a.TEXTURELODSUPPORT=!0),this._diffuseTexture&<.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Is(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&<.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===be.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 be.EXPLICIT_MODE:a.REFLECTIONMAP_EXPLICIT=!0;break;case be.PLANAR_MODE:a.REFLECTIONMAP_PLANAR=!0;break;case be.PROJECTION_MODE:a.REFLECTIONMAP_PROJECTION=!0;break;case be.SKYBOX_MODE:a.REFLECTIONMAP_SKYBOX=!0;break;case be.SPHERICAL_MODE:a.REFLECTIONMAP_SPHERICAL=!0;break;case be.EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case be.FIXED_EQUIRECTANGULAR_MODE:a.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case be.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case be.CUBIC_MODE:case be.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),Tu(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),a),Mu(s,o,this,a,i,null,t.getRenderingMesh().hasThinInstances),xo(e,a,!1,!0,!1)&&e&&!s.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(ee.NormalKind)&&(e.createNormals(!0),ge.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();const l=new ha;a.FOG&&l.addFallback(0,"FOG"),a.POINTSIZE&&l.addFallback(1,"POINTSIZE"),a.MULTIVIEW&&l.addFallback(0,"MULTIVIEW"),Bl(a,l,this._maxSimultaneousLights);const c=[ee.PositionKind];a.NORMAL&&c.push(ee.NormalKind),a.UV1&&c.push(ee.UVKind),a.UV2&&c.push(ee.UV2Kind),Ch(c,e,a,l),Do(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"];Yo(u);const h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];Gr&&(Gr.PrepareUniforms(u,a),Gr.PrepareSamplers(h,a)),Qo({uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:a,maxSimultaneousLights:this._maxSimultaneousLights});const f=a.toString(),p=s.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([je(()=>Promise.resolve().then(()=>VCt),void 0),je(()=>Promise.resolve().then(()=>eAt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>gAt),void 0),je(()=>Promise.resolve().then(()=>DAt),void 0)]),this._shadersLoaded=!0}},o);t.setEffect(p,a,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),n._wasPreviouslyReady=!0,n._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 n=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e),rc(t,this._activeEffect);const o=this._mustRebind(n,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)&&(n.texturesEnabled&&(this._diffuseTexture&<.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Ps(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&<.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),s.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),n.texturesEnabled&&(this._diffuseTexture&<.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&<.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):s.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),s.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))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),wo(this._activeEffect,this,n),n.bindEyePosition(a)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(a,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(n.lightsEnabled&&$u(n,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(a),ic(n,t,this._activeEffect,!0),this._useLogarithmicDepth&&Xo(s,a,n),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 ot.Clone(()=>new Qr(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return ot.Parse(()=>new Qr(e.name,t),e,t,i)}}Qr.StandardReflectance0=.05;Qr.StandardReflectance90=.5;V([qr()],Qr.prototype,"_primaryColor",void 0);V([Ke("_markAllSubMeshesAsLightsDirty")],Qr.prototype,"primaryColor",void 0);V([qr()],Qr.prototype,"__perceptualColor",void 0);V([Q()],Qr.prototype,"_primaryColorShadowLevel",void 0);V([Q()],Qr.prototype,"_primaryColorHighlightLevel",void 0);V([Ke("_markAllSubMeshesAsLightsDirty")],Qr.prototype,"primaryColorHighlightLevel",null);V([ki()],Qr.prototype,"_reflectionTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionTexture",void 0);V([Q()],Qr.prototype,"_reflectionBlur",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionBlur",void 0);V([ki()],Qr.prototype,"_diffuseTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"diffuseTexture",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"shadowLights",void 0);V([Q()],Qr.prototype,"_shadowLevel",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"shadowLevel",void 0);V([ta()],Qr.prototype,"_sceneCenter",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"sceneCenter",void 0);V([Q()],Qr.prototype,"_opacityFresnel",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"opacityFresnel",void 0);V([Q()],Qr.prototype,"_reflectionFresnel",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionFresnel",void 0);V([Q()],Qr.prototype,"_reflectionFalloffDistance",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionFalloffDistance",void 0);V([Q()],Qr.prototype,"_reflectionAmount",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionAmount",void 0);V([Q()],Qr.prototype,"_reflectionReflectance0",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionReflectance0",void 0);V([Q()],Qr.prototype,"_reflectionReflectance90",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"reflectionReflectance90",void 0);V([Q()],Qr.prototype,"_useRGBColor",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"useRGBColor",void 0);V([Q()],Qr.prototype,"_enableNoise",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"enableNoise",void 0);V([Q()],Qr.prototype,"_maxSimultaneousLights",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],Qr.prototype,"maxSimultaneousLights",void 0);V([Q()],Qr.prototype,"_shadowOnly",void 0);V([Ke("_markAllSubMeshesAsLightsDirty")],Qr.prototype,"shadowOnly",void 0);V([Yge()],Qr.prototype,"_imageProcessingConfiguration",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],Qr.prototype,"enableGroundProjection",void 0);V([Q()],Qr.prototype,"projectedGroundRadius",void 0);V([Q()],Qr.prototype,"projectedGroundHeight",void 0);xe("BABYLON.BackgroundMaterial",Qr);class Vx{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Pe(.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 Pe(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:O.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,n)=>{this.onErrorObservable.notifyObservers({message:i,exception:n})},this._options={...Vx._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new Ce,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 at(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 Cn){this._scene.environmentTexture=this._options.environmentTexture;return}const e=Za.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Re("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 n=this._scene.getWorldExtends(a=>a!==this._ground&&a!==this._rootMesh&&a!==this._skybox),s=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof mn&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const a=s.length();a>e&&(e=a*2,t=e),e*=1.1,t*=1.5,i=n.min.add(s.scale(.5)),i.y=n.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=U_("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 Qr("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 Cn){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new be(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=be.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Hv("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,be.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Dc(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let n=0;n{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Qr("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 Cn){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new Za(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=be.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)}}Vx._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";Vx._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";Vx._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Yh extends Yt{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=be.CLAMP_ADDRESSMODE,this._texture.wrapV=be.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=be.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=be.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,n,s=null){super(e,n),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Yh.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new Ce,this.onLoadObservable=new Ce,n=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)||(n.activeCamera?n.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=bu(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Re.BACKSIDE},n);const a=this._material=new Qr(e+"_material",n);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const o=this._initTexture(t,n,i);if(this.texture=o,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=bu("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:Re.BACKSIDE},n),this._halfDomeMask.rotate(go.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&&n.activeCamera){const l=n.activeCamera,c=O.Forward(),u=O.TransformNormal(c,l.getViewMatrix());u.normalize(),this.rotation.y=Math.acos(O.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 Yh.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Yh.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(n=>{let s=n.isRightCamera;this._crossEye&&(s=!s),s?this._texture.uOffset=t:this._texture.uOffset=i});break}case Yh.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)}}Yh.MODE_MONOSCOPIC=0;Yh.MODE_TOPBOTTOM=1;Yh.MODE_SIDEBYSIDE=2;class lw extends Yh{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 be(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(n,s)=>{this.onLoadErrorObservable.notifyObservers(n||"Unknown error occured"),this.onError&&this.onError(n,s)})}}lw.MODE_MONOSCOPIC=Yh.MODE_MONOSCOPIC;lw.MODE_TOPBOTTOM=Yh.MODE_TOPBOTTOM;lw.MODE_SIDEBYSIDE=Yh.MODE_SIDEBYSIDE;const vxt="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 yxt=0;const oV=r=>{if(!r.environmentBRDFTexture){const e=r.useDelayedTextureLoading;r.useDelayedTextureLoading=!1;const t=r._blockEntityCollection;r._blockEntityCollection=!1;const i=be.CreateFromBase64String(vxt,"EnvironmentBRDFTexture"+yxt++,r,!0,!1,be.BILINEAR_SAMPLINGMODE);r._blockEntityCollection=t;const n=r.getEngine().getLoadedTexturesCache(),s=n.indexOf(i.getInternalTexture());s!==-1&&n.splice(s,1),i.isRGBD=!0,i.wrapU=be.CLAMP_ADDRESSMODE,i.wrapV=be.CLAMP_ADDRESSMODE,r.environmentBRDFTexture=i,r.useDelayedTextureLoading=e,Zk.ExpandRGBDTexture(i);const a=r.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=r.onBeforeRenderObservable.add(()=>{i.isReady()&&(r.onBeforeRenderObservable.remove(o),Zk.ExpandRGBDTexture(i))})});r.onDisposeObservable.add(()=>{r.getEngine().onContextRestoredObservable.remove(a)})}return r.environmentBRDFTexture},xxt={GetEnvironmentBRDFTexture:oV};class bxt extends Kn{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 du extends Yu{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new bxt,t),this._useEnergyConservation=du.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=du.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=du.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=du.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=du.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=du.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=du.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=du.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"}}du.DEFAULT_USE_ENERGY_CONSERVATION=!0;du.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;du.DEFAULT_USE_SPHERICAL_HARMONICS=!0;du.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],du.prototype,"useEnergyConservation",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],du.prototype,"useSmithVisibilityHeightCorrelated",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],du.prototype,"useSphericalHarmonics",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],du.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);class CUe extends Kn{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 Ll extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new CUe,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Ll._DefaultIndexOfRefraction,this.indexOfRefraction=Ll._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=Pe.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 n=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&<.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&<.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&<.ClearCoatBumpTextureEnabled&&!n&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&<.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&<.ClearCoatTextureEnabled?Is(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&<.ClearCoatTextureEnabled?Is(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&<.ClearCoatBumpTextureEnabled?Is(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Ll._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&<.ClearCoatTintTextureEnabled?(Is(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,n){var u,h,d,f;if(!this._isEnabled)return;const s=n.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)&<.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&&Ps(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ps(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&<.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Ps(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&<.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Ps(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const p=1-this._indexOfRefraction,g=1+this._indexOfRefraction,m=Math.pow(-p/g,2),_=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",m,_,p,g),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&<.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&<.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&<.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&<.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,n,s;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(n=this._bumpTexture)==null||n.dispose(),(s=this._tintTexture)==null||s.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"}]}}}Ll._DefaultIndexOfRefraction=1.5;V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"isEnabled",void 0);V([Q()],Ll.prototype,"intensity",void 0);V([Q()],Ll.prototype,"roughness",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"indexOfRefraction",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"texture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"useRoughnessFromMainTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"textureRoughness",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"remapF0OnInterfaceChange",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"bumpTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"isTintEnabled",void 0);V([qr()],Ll.prototype,"tintColor",void 0);V([Q()],Ll.prototype,"tintColorAtDistance",void 0);V([Q()],Ll.prototype,"tintThickness",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Ll.prototype,"tintTexture",void 0);class AUe extends Kn{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 Cu extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new AUe,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Cu._DefaultMinimumThickness,this.maximumThickness=Cu._DefaultMaximumThickness,this.indexOfRefraction=Cu._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&<.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&<.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&<.IridescenceTextureEnabled?Is(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&<.IridescenceTextureEnabled?Is(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 n,s,a,o;if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&<.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",((n=this._texture)==null?void 0:n.coordinatesIndex)??0,((s=this._texture)==null?void 0:s.level)??0,((a=this._thicknessTexture)==null?void 0:a.coordinatesIndex)??0,((o=this._thicknessTexture)==null?void 0:o.level)??0),this._texture&&Ps(this._texture,e,"iridescence"),this._thicknessTexture&&Ps(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&<.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&<.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"}]}}}Cu._DefaultMinimumThickness=100;Cu._DefaultMaximumThickness=400;Cu._DefaultIndexOfRefraction=1.3;V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Cu.prototype,"isEnabled",void 0);V([Q()],Cu.prototype,"intensity",void 0);V([Q()],Cu.prototype,"minimumThickness",void 0);V([Q()],Cu.prototype,"maximumThickness",void 0);V([Q()],Cu.prototype,"indexOfRefraction",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Cu.prototype,"texture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Cu.prototype,"thicknessTexture",void 0);class SUe extends Kn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class sb extends Yu{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 SUe,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new Ne(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&<.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(ee.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&<.AnisotropicTextureEnabled?Is(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&<.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Ps(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&<.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)}}V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],sb.prototype,"isEnabled",void 0);V([Q()],sb.prototype,"intensity",void 0);V([Cz()],sb.prototype,"direction",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],sb.prototype,"texture",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],sb.prototype,"legacy",void 0);class EUe extends Kn{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 em extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new EUe,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Pe.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&<.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&<.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&<.SheenTextureEnabled?(Is(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&<.SheenTextureEnabled?Is(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,n){var o,l,c,u;if(!this._isEnabled)return;const s=n.materialDefines,a=this._material.isFrozen;(!e.useUbo||!a||!e.isSync)&&((this._texture||this._textureRoughness)&<.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&&Ps(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ps(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&<.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&<.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"}]}}}V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"isEnabled",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"linkSheenWithAlbedo",void 0);V([Q()],em.prototype,"intensity",void 0);V([qr()],em.prototype,"color",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"texture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"useRoughnessFromMainTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"roughness",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"textureRoughness",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],em.prototype,"albedoScaling",void 0);class TUe extends Kn{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 da extends Yu{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 TUe,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=Pe.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Pe.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&<.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&<.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking()||this._translucencyIntensityTexture&<.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&<.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&<.ThicknessTextureEnabled&&Is(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&<.RefractionIntensityTextureEnabled&&Is(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&<.TranslucencyIntensityTextureEnabled&&Is(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&<.TranslucencyColorTextureEnabled&&Is(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&<.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,n){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled))if(this.maximumThickness===0&&this.minimumThickness===0)e.updateFloat2("vThicknessParam",0,0);else{n.getRenderingMesh().getWorldMatrix().decompose(oe.Vector3[0]);const s=Math.max(Math.abs(oe.Vector3[0].x),Math.abs(oe.Vector3[0].y),Math.abs(oe.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=n.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,l=s.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&<.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Ps(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&<.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Ps(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&<.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),Ps(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&<.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Ps(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&<.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,Xt.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&<.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&<.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&<.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&<.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&<.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){lt.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!!(lt.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"}]}}}V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"isRefractionEnabled",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"isTranslucencyEnabled",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"isDispersionEnabled",void 0);V([Q(),Ke("_markScenePrePassDirty")],da.prototype,"isScatteringEnabled",void 0);V([Q()],da.prototype,"_scatteringDiffusionProfileIndex",void 0);V([Q()],da.prototype,"refractionIntensity",void 0);V([Q()],da.prototype,"translucencyIntensity",void 0);V([Q()],da.prototype,"useAlbedoToTintRefraction",void 0);V([Q()],da.prototype,"useAlbedoToTintTranslucency",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"thicknessTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"refractionTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"indexOfRefraction",void 0);V([Q()],da.prototype,"_volumeIndexOfRefraction",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"volumeIndexOfRefraction",null);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"invertRefractionY",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"linkRefractionWithTransparency",void 0);V([Q()],da.prototype,"minimumThickness",void 0);V([Q()],da.prototype,"maximumThickness",void 0);V([Q()],da.prototype,"useThicknessAsDepth",void 0);V([qr()],da.prototype,"tintColor",void 0);V([Q()],da.prototype,"tintColorAtDistance",void 0);V([Q()],da.prototype,"dispersion",void 0);V([qr()],da.prototype,"diffusionDistance",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"useMaskFromThicknessTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"refractionIntensityTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"translucencyIntensityTexture",void 0);V([qr()],da.prototype,"translucencyColor",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"translucencyColorTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],da.prototype,"useGltfStyleTextures",void 0);const OI={effect:null,subMesh:null};class ide extends Kn{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_NDC_DEPTH=!1,this.PREPASS_NDC_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_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 an extends Va{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 It(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=an.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=Pe.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Pe(0,0,0),this._albedoColor=new Pe(1,1,1),this._reflectivityColor=new Pe(1,1,1),this._reflectionColor=new Pe(1,1,1),this._emissiveColor=new Pe(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=an.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 Go(16),this._globalAmbientColor=new Pe(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 n=this.getScene().getEngine();n.isWebGPU&&!i&&!an.ForceGLSL&&(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new Ci(n,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.brdf=new du(this),this.clearCoat=new Ll(this),this.iridescence=new Cu(this),this.anisotropy=new sb(this),this.sheen=new em(this),this.subSurface=new da(this),this.detailMap=new z_(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=oV(this.getScene()),this.prePassConfiguration=new vZ}get hasRenderTargetTextures(){return lt.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===an.PBRMATERIAL_OPAQUE||this._transparencyMode===an.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===an.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==an.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 n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new ide(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&<.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&<.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&<.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const f=this._getReflectionTexture();if(f&<.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&<.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&<.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(lt.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&<.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&<.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(ee.NormalKind)&&(e.createNormals(!0),ge.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const l=t.effect,c=s._areLightsDisposed;let u=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),h=!1;if(u)if(this._onEffectCreatedObservable&&(OI.effect=u,OI.subMesh=t,this._onEffectCreatedObservable.notifyObservers(OI)),this.allowShaderHotSwapping&&l&&!u.isReady()){if(u=l,s.markAsUnprocessed(),h=this.isFrozen,c)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(u,s,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(s._renderId=a.getRenderId(),n._wasPreviouslyReady=!h,n._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,s=null,a=null,o){if(this._prepareDefines(e,t,s,a,o),!t.isDirty)return null;t.markAsProcessed();const c=this.getScene().getEngine(),u=new ha;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=Bl(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=[ee.PositionKind];t.NORMAL&&d.push(ee.NormalKind),t.TANGENT&&d.push(ee.TangentKind);for(let b=1;b<=6;++b)t["UV"+b]&&d.push(`uv${b===1?"":b}`);t.VERTEXCOLOR&&d.push(ee.ColorKind),Ch(d,e,t,u),Do(d,t),Iz(d,e,t),iD(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"],g=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],m=["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=g,this._eventInfo.uniformBuffersNames=m,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(128,this._eventInfo),vZ.AddUniforms(p),Yo(p),Gr&&(Gr.PrepareUniforms(p,t),Gr.PrepareSamplers(g,t)),Qo({uniformsNames:p,uniformBuffersNames:m,samplers:g,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const y={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,p,m,g,t,d,y));const v=t.toString(),x=c.createEffect(f,{attributes:d,uniformsNames:p,uniformBuffersNames:m,samplers:g,defines:v,fallbacks:u,onCompiled:i,onError:n,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([je(()=>Promise.resolve().then(()=>dKe),void 0),je(()=>Promise.resolve().then(()=>EKe),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>IKe),void 0),je(()=>Promise.resolve().then(()=>GKe),void 0)]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,n=null,s=!1){const a=this.getScene(),o=a.getEngine();Xu(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,rD(a,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Dz(a,t,this.canRenderToMRT&&!l),jJ(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&<.DiffuseTextureEnabled?(Is(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&<.AmbientTextureEnabled?(Is(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&<.OpacityTextureEnabled?(Is(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const c=this._getReflectionTexture();if(c&<.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===be.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 be.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case be.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case be.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case be.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case be.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case be.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case be.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case be.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case be.CUBIC_MODE:case be.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!c.boundingBoxSize;break}c.coordinatesMode!==be.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&<.LightmapTextureEnabled?(Is(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&<.EmissiveTextureEnabled?(Is(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,lt.SpecularTextureEnabled?(this._metallicTexture?(Is(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?(Is(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?(Is(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Is(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Is(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&<.BumpTextureEnabled&&!this._disableBumpMap?(Is(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&<.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&<.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===an.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===an.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&&(Tu(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(ee.NormalKind),t.DEBUGMODE=this._debugMode),Mu(a,o,this,t,!!i,n,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),xo(e,t,!0,!0,!0,this._transparencyMode!==an.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;const a=new ide(this._eventInfo.defineNames),o=this._prepareEffect(e,a,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(OI.effect=o,OI.subMesh=null,this._onEffectCreatedObservable.notifyObservers(OI)),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 n=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);const o=n.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,n,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=this._mustRebind(n,a,i,t.visibility);rc(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(n.texturesEnabled){if(this._albedoTexture&<.DiffuseTextureEnabled&&(u.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Ps(this._albedoTexture,u,"albedo")),this._ambientTexture&<.AmbientTextureEnabled&&(u.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Ps(this._ambientTexture,u,"ambient")),this._opacityTexture&<.OpacityTextureEnabled&&(u.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Ps(this._opacityTexture,u,"opacity")),c&<.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,Xt.Log2(p))}if(!s.USEIRRADIANCEMAP){const p=c.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&p)if(s.SPHERICAL_HARMONICS){const g=p.preScaledHarmonics;u.updateVector3("vSphericalL00",g.l00),u.updateVector3("vSphericalL1_1",g.l1_1),u.updateVector3("vSphericalL10",g.l10),u.updateVector3("vSphericalL11",g.l11),u.updateVector3("vSphericalL2_2",g.l2_2),u.updateVector3("vSphericalL2_1",g.l2_1),u.updateVector3("vSphericalL20",g.l20),u.updateVector3("vSphericalL21",g.l21),u.updateVector3("vSphericalL22",g.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&<.EmissiveTextureEnabled&&(u.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Ps(this._emissiveTexture,u,"emissive")),this._lightmapTexture&<.LightmapTextureEnabled&&(u.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Ps(this._lightmapTexture,u,"lightmap")),lt.SpecularTextureEnabled&&(this._metallicTexture?(u.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Ps(this._metallicTexture,u,"reflectivity")):this._reflectivityTexture&&(u.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Ps(this._reflectivityTexture,u,"reflectivity")),this._metallicReflectanceTexture&&(u.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Ps(this._metallicReflectanceTexture,u,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(u.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Ps(this._reflectanceTexture,u,"reflectance")),this._microSurfaceTexture&&(u.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Ps(this._microSurfaceTexture,u,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&<.BumpTextureEnabled&&!this._disableBumpMap&&(u.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Ps(this._bumpTexture,u,"bump"),n._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),s.METALLICWORKFLOW){En.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,En.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,u.updateColor4("vReflectivityColor",En.Color3[0],1);const p=((h=this.subSurface)==null?void 0:h._indexOfRefraction)??1.5,g=1,m=Math.pow((p-g)/(p+g),2);this._metallicReflectanceColor.scaleToRef(m*this._metallicF0Factor,En.Color3[0]);const _=this._metallicF0Factor;u.updateColor4("vMetallicReflectanceFactors",En.Color3[0],_)}else u.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);u.updateColor3("vEmissiveColor",lt.EmissiveTextureEnabled?this._emissiveColor:Pe.BlackReadOnly),u.updateColor3("vReflectionColor",this._reflectionColor),!s.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*n.environmentIntensity,this._lightingInfos.w=this._specularIntensity,u.updateVector4("vLightingIntensity",this._lightingInfos),n.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),u.updateColor3("vAmbientColor",this._globalAmbientColor),u.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}n.texturesEnabled&&(this._albedoTexture&<.DiffuseTextureEnabled&&u.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&<.AmbientTextureEnabled&&u.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&<.OpacityTextureEnabled&&u.setTexture("opacitySampler",this._opacityTexture),c&<.ReflectionTextureEnabled&&(s.LODBASEDMICROSFURACE?u.setTexture("reflectionSampler",c):(u.setTexture("reflectionSampler",c._lodTextureMid||c),u.setTexture("reflectionSamplerLow",c._lodTextureLow||c),u.setTexture("reflectionSamplerHigh",c._lodTextureHigh||c)),s.USEIRRADIANCEMAP&&u.setTexture("irradianceSampler",c.irradianceTexture)),s.ENVIRONMENTBRDF&&u.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&<.EmissiveTextureEnabled&&u.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&<.LightmapTextureEnabled&&u.setTexture("lightmapSampler",this._lightmapTexture),lt.SpecularTextureEnabled&&(this._metallicTexture?u.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&u.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&u.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&u.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&u.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&<.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),wo(this._activeEffect,this,n),this.bindEyePosition(a)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(n.lightsEnabled&&!this._disableLighting&&$u(n,t,this._activeEffect,s,this._maxSimultaneousLights),(n.fogEnabled&&t.applyFog&&n.fogMode!==Ut.FOGMODE_NONE||c||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(a),ic(n,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&Np(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Xo(s,this._activeEffect,n)),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,n,s,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(),(n=this._ambientTexture)==null||n.dispose(),(s=this._opacityTexture)==null||s.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)}}an.PBRMATERIAL_OPAQUE=tt.MATERIAL_OPAQUE;an.PBRMATERIAL_ALPHATEST=tt.MATERIAL_ALPHATEST;an.PBRMATERIAL_ALPHABLEND=tt.MATERIAL_ALPHABLEND;an.PBRMATERIAL_ALPHATESTANDBLEND=tt.MATERIAL_ALPHATESTANDBLEND;an.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;an.LIGHTFALLOFF_PHYSICAL=0;an.LIGHTFALLOFF_GLTF=1;an.LIGHTFALLOFF_STANDARD=2;an.ForceGLSL=!1;V([Yge()],an.prototype,"_imageProcessingConfiguration",void 0);V([Ke("_markAllSubMeshesAsMiscDirty")],an.prototype,"debugMode",void 0);class ui extends an{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===an.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=an.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=an.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===an.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=an.LIGHTFALLOFF_GLTF:this._lightFalloff=an.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=ui.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Pe.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Pe(0,0,0),this.albedoColor=new Pe(1,1,1),this.reflectivityColor=new Pe(1,1,1),this.reflectionColor=new Pe(1,1,1),this.emissiveColor=new Pe(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=oV(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const n=ot.Clone(()=>new ui(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return n.id=e,n.name=e,this.stencil.copyTo(n.stencil),this._clonePlugins(n,i),n}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const n=ot.Parse(()=>new ui(e.name,t),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),tt._ParsePlugins(e,n,t,i),e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}ui.PBRMATERIAL_OPAQUE=an.PBRMATERIAL_OPAQUE;ui.PBRMATERIAL_ALPHATEST=an.PBRMATERIAL_ALPHATEST;ui.PBRMATERIAL_ALPHABLEND=an.PBRMATERIAL_ALPHABLEND;ui.PBRMATERIAL_ALPHATESTANDBLEND=an.PBRMATERIAL_ALPHATESTANDBLEND;ui.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=an.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"directIntensity",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"emissiveIntensity",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"environmentIntensity",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"specularIntensity",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"disableBumpMap",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"albedoTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"ambientTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"ambientTextureStrength",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ui.prototype,"opacityTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"reflectionTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"emissiveTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"reflectivityTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"metallicTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"metallic",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"roughness",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"metallicF0Factor",void 0);V([qr(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"metallicReflectanceColor",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"metallicReflectanceTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"reflectanceTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"microSurfaceTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"bumpTexture",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty",null)],ui.prototype,"lightmapTexture",void 0);V([qr("ambient"),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"ambientColor",void 0);V([qr("albedo"),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"albedoColor",void 0);V([qr("reflectivity"),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"reflectivityColor",void 0);V([qr("reflection"),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"reflectionColor",void 0);V([qr("emissive"),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"emissiveColor",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"microSurface",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useLightmapAsShadowmap",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ui.prototype,"useAlphaFromAlbedoTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ui.prototype,"forceAlphaTest",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesAndMiscDirty")],ui.prototype,"alphaCutOff",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useSpecularOverAlpha",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useRoughnessFromMetallicTextureGreen",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useMetallnessFromMetallicTextureBlue",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useAmbientInGrayScale",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);V([Q()],ui.prototype,"usePhysicalLightFalloff",null);V([Q()],ui.prototype,"useGLTFLightFalloff",null);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useRadianceOverAlpha",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useObjectSpaceNormalMap",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useParallax",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useParallaxOcclusion",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"parallaxScaleBias",void 0);V([Q(),Ke("_markAllSubMeshesAsLightsDirty")],ui.prototype,"disableLighting",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"forceIrradianceInFragment",void 0);V([Q(),Ke("_markAllSubMeshesAsLightsDirty")],ui.prototype,"maxSimultaneousLights",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"invertNormalMapX",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"invertNormalMapY",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"twoSidedLighting",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useAlphaFresnel",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useLinearAlphaFresnel",void 0);V([Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"environmentBRDFTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"forceNormalForward",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"enableSpecularAntiAliasing",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useHorizonOcclusion",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],ui.prototype,"useRadianceOcclusion",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],ui.prototype,"unlit",void 0);V([Q(),Ke("_markAllSubMeshesAsMiscDirty")],ui.prototype,"applyDecalMapAfterDetailMap",void 0);xe("BABYLON.PBRMaterial",ui);class MUe{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,n){const s=t.getEngine();let a,o=!1,l=1e3;if(Array.isArray(e))for(let c=0;c1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),_s.UploadDDSLevels(s,t,u,a,o,6,-1,c),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t):l=a.mipmapCount-1}else{const c=e;a=_s.GetDDSInfo(c),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new wg),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),_s.UploadDDSLevels(s,t,c,a,o,6),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t,!1):l=a.mipmapCount-1}s._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){const n=_s.GetDDSInfo(e),s=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&Math.max(n.width,n.height)>>n.mipmapCount-1===1;i(n.width,n.height,s,n.isFourCC,()=>{_s.UploadDDSLevels(t.getEngine(),t,e,n,s,1)})}}const Cxt=Object.freeze(Object.defineProperty({__proto__:null,_DDSTextureLoader:MUe},Symbol.toStringTag,{value:"Module"}));class RUe{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,s){if(Array.isArray(e))return;const a=xee(e);if(a){t.width=a.width,t.height=a.width;try{Cee(t,a),h_e(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()},o=>{s==null||s("Can not upload environment levels",o)})}catch(o){s==null||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}const Axt=Object.freeze(Object.defineProperty({__proto__:null,_ENVTextureLoader:RUe},Symbol.toStringTag,{value:"Module"}));class fh{constructor(e,t){if(this.data=e,this.isInvalid=!1,!fh.IsValid(e)){this.isInvalid=!0,ge.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=n.getUint32(0,!0)===67305985;if(this.glType=n.getUint32(1*i,a),this.glTypeSize=n.getUint32(2*i,a),this.glFormat=n.getUint32(3*i,a),this.glInternalFormat=n.getUint32(4*i,a),this.glBaseInternalFormat=n.getUint32(5*i,a),this.pixelWidth=n.getUint32(6*i,a),this.pixelHeight=n.getUint32(7*i,a),this.pixelDepth=n.getUint32(8*i,a),this.numberOfArrayElements=n.getUint32(9*i,a),this.numberOfFaces=n.getUint32(10*i,a),this.numberOfMipmapLevels=n.getUint32(11*i,a),this.bytesOfKeyValueData=n.getUint32(12*i,a),this.glType!==0){ge.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){ge.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){ge.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){ge.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=fh.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case fh.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case fh.TEX_2D:case fh.COMPRESSED_3D:case fh.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=fh.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,s=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}}fh.HEADER_LEN=12+13*4;fh.COMPRESSED_2D=0;fh.COMPRESSED_3D=1;fh.TEX_2D=2;fh.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 n=this._pendingActions.shift();n?this._execute(e,n):e.idle=!0})})}}class cD extends IUe{constructor(e,t,i=cD.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{n(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});const s=this._workerInfos.indexOf(e);s!==-1&&this._workerInfos.splice(s,1)},this._options.idleTimeElapsedBeforeRelease))})})}}cD.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var rde;(function(r){r[r.ETC1S=0]="ETC1S",r[r.UASTC4x4=1]="UASTC4x4"})(rde||(rde={}));var l5;(function(r){r[r.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",r[r.BC7_RGBA=1]="BC7_RGBA",r[r.BC3_RGBA=2]="BC3_RGBA",r[r.BC1_RGB=3]="BC1_RGB",r[r.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",r[r.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",r[r.ETC2_RGBA=6]="ETC2_RGBA",r[r.ETC1_RGB=7]="ETC1_RGB",r[r.RGBA32=8]="RGBA32",r[r.R8=9]="R8",r[r.RG8=10]="RG8"})(l5||(l5={}));var nde;(function(r){r[r.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",r[r.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",r[r.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",r[r.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",r[r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",r[r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",r[r.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",r[r.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",r[r.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",r[r.RGBA8Format=32856]="RGBA8Format",r[r.R8Format=33321]="R8Format",r[r.RG8Format=33323]="RG8Format"})(nde||(nde={}));function SZ(r,e){const t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;r&&(r.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=r.wasmUASTCToASTC),r.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=r.wasmUASTCToBC7),r.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=r.wasmUASTCToRGBA_UNORM),r.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=r.wasmUASTCToRGBA_SRGB),r.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=r.wasmUASTCToR8_UNORM),r.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=r.wasmUASTCToRG8_UNORM),r.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=r.jsMSCTranscoder),r.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=r.wasmMSCTranscoder),r.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=r.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 Sxt(r){typeof r>"u"&&typeof KTX2DECODER<"u"&&(r=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;i&&(i.jsDecoderModule&&typeof r>"u"&&(importScripts(i.jsDecoderModule),r=KTX2DECODER),SZ(i)),t.data.wasmBinaries&&SZ(void 0,{...t.data.wasmBinaries,jsDecoderModule:r}),e=new r.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{r.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{const n=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:i})});break}}}function Ext(r,e,t){return new Promise((i,n)=>{const s=o=>{r.removeEventListener("error",s),r.removeEventListener("message",a),n(o)},a=o=>{o.data.action==="init"&&(r.removeEventListener("error",s),r.removeEventListener("message",a),i(r))};r.addEventListener("error",s),r.addEventListener("message",a),r.postMessage({action:"init",urls:t,wasmBinaries:e})})}class PUe{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:[l5.BC1_RGB,l5.BC3_RGBA],yes:{transcodeFormat:l5.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class As{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(As._WorkerPoolPromise||As._DecoderModulePromise)return;const t={jsDecoderModule:Ie.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ie.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ie.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ie.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ie.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?As._WorkerPoolPromise=new Promise(i=>{const n=`${SZ}(${Sxt})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new cD(e,()=>Ext(new Worker(s),void 0,t)))}):typeof As._KTX2DecoderModule>"u"?As._DecoderModulePromise=Ie.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(As._KTX2DecoderModule=KTX2DECODER,As._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,As._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,SZ(t,As._KTX2DecoderModule),new As._KTX2DecoderModule.KTX2Decoder)):(As._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,As._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,As._DecoderModulePromise=Promise.resolve(new As._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=As.DefaultNumWorkers){var n;this._engine=e;const i=typeof t=="object"&&t.workerPool||As.WorkerPool;if(i)As._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?As._KTX2DecoderModule=(n=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:n.jsDecoderModule:typeof KTX2DECODER<"u"&&(As._KTX2DecoderModule=KTX2DECODER);const s=typeof t=="number"?t:t.numWorkers??As.DefaultNumWorkers;As._Initialize(s)}}_uploadAsync(e,t,i){const n=this._engine.getCaps(),s={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(As._WorkerPoolPromise)return As._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(g){l({message:g})}u()}};c.addEventListener("error",h),c.addEventListener("message",d),c.postMessage({action:"setDefaultDecoderOptions",options:As.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:s,options:i},[f.buffer])})}));if(As._DecoderModulePromise)return As._DecoderModulePromise.then(a=>(As.DefaultDecoderOptions.isDirty&&(As._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=As.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,l)=>{a.decode(e,n).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 s=!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,s=!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}}As.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};As.DefaultNumWorkers=As.GetDefaultNumWorkers();As.DefaultDecoderOptions=new PUe;function Txt(r){switch(r){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 wUe{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const s=t.getEngine(),a=new fh(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(fh.IsValid(e)){t._invertVScale=!t.invertY;const s=new fh(e,1),a=Txt(s.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,()=>{s.uploadLevels(t,t.generateMipMaps)},s.isInvalid)}else As.IsValid(e)?new As(t.getEngine())._uploadAsync(e,t,n).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{ge.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(ge.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}const Mxt=Object.freeze(Object.defineProperty({__proto__:null,_KTXTextureLoader:wUe},Symbol.toStringTag,{value:"Module"}));class cw extends ql{constructor(e,t,i){super(e,O.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=Oe.Identity(),this._referencedPosition=new O,this._trackingState=0,this.onXRCameraInitializedObservable=new Ce,this.onBeforeCameraTeleport=new Ce,this.onAfterCameraTeleport=new Ce,this.onTrackingStateChanged=new Ce,this.compensateOnFirstFrame=!0,this._rotate180=new Oe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new Oe,this.cameraRigMode=di.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 Yc(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Yc(.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,Oe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=oe.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),Oe.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 n=e.transform.position;this._referencedPosition.set(n.x,n.y,n.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,n)=>{var h;const s=this.rigCameras[n];!s.isLeftCamera&&!s.isRightCamera&&(i.eye==="right"?s._isRightCamera=!0:i.eye==="left"&&(s._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=oe.Matrix[0],t=oe.Matrix[1],i=oe.Matrix[2];pe.ComposeToRef(cw._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),pe.ComposeToRef(cw._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 n=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(n)}}}cw._ScaleReadOnly=O.One();class Tee{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 Ce,this.onStateChangedObservable=new Ce,this.state=3,this.sessionManager=new Xz(e),this.camera=new cw("webxr",e,this.sessionManager),this.featuresManager=new Ea(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new Tee(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(),n={}){var s,a,o,l;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(0),t!=="viewer"&&t!=="local"&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(t)),n=await this.featuresManager._extendXRSessionInitObject(n),e==="immersive-ar"&&t!=="unbounded"&&ge.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,n),await this.sessionManager.setReferenceSpaceTypeAsync(t);const c={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(ln.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=(s=this._nonVRCamera)==null?void 0:s.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=Qe.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 ge.Log(c),ge.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,n=e!=null&&e.preferredCameraIndex?e==null?void 0:e.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[n].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[n].absoluteRotation))};if(this._spectatorMode){if(n>=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 rb("webxr-spectator",O.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new Oe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===1&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(a),a()}else this.sessionManager.onXRFrameObservable.removeCallback(s),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 wd{constructor(e,t,i=-1,n=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=n,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new Ce,this.onButtonStateChangedObservable=new Ce}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 n=e.buttons[this._buttonIndex];if(!n)return;this._currentValue!==n.value&&(this.changes.value={current:n.value,previous:this._currentValue},t=!0,this._currentValue=n.value),this._touched!==n.touched&&(this.changes.touched={current:n.touched,previous:this._touched},t=!0,this._touched=n.touched),this._pressed!==n.pressed&&(this.changes.pressed={current:n.pressed,previous:this._pressed},t=!0,this._pressed=n.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))}}wd.BUTTON_TYPE="button";wd.SQUEEZE_TYPE="squeeze";wd.THUMBSTICK_TYPE="thumbstick";wd.TOUCHPAD_TYPE="touchpad";wd.TRIGGER_TYPE="trigger";var sde;(function(r){r[r.Clean=0]="Clean",r[r.Stop=1]="Stop",r[r.Sync=2]="Sync",r[r.NoSync=3]="NoSync"})(sde||(sde={}));function Rxt(r){return!!r.name}const DUe=new Ce,yx={};let Aae=!1;function A_e(){return yx[".babylon"]}function S_e(r){const e=yx[r];return e||(ge.Warn("Unable to find a plugin to load "+r+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),A_e())}function Ixt(r){return!!yx[r]}function Pxt(r){for(const e in yx){const t=yx[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(r))return yx[e]}return A_e()}function wxt(r){const e=r.indexOf("?");e!==-1&&(r=r.substring(0,e));const t=r.lastIndexOf("."),i=r.substring(t,r.length).toLowerCase();return S_e(i)}function Dxt(r){return r.substr(0,5)==="data:"?r.substr(5):null}function E_e(r,e,t){let n="Unable to load from "+(r.rawData?"binary data":r.url);return e?n+=`: ${e}`:t&&(n+=`: ${t}`),n}function T_e(r,e,t,i,n,s,a,o,l){var v,x,b,C;const c=Dxt(r.url);if(r.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const u=a?S_e(a):c?Pxt(r.url):wxt(r.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(r.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";const h=((b=(x=u.plugin).createPlugin)==null?void 0:b.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(DUe.notifyObservers(h),c&&(h.canDirectLoad&&h.canDirectLoad(r.url)||!Mz(r.url))){if(h.directLoad){const A=h.directLoad(e,c);A instanceof Promise?A.then(E=>{t(h,E)}).catch(E=>{n("Error in directLoad of _loadData: "+E,E)}):t(h,A)}else t(h,c);return h}const d=u.isBinary,f=(A,E)=>{if(e.isDisposed){n("Scene has been disposed");return}t(h,A,E)};let p=null,g=!1;(C=h.onDisposeObservable)==null||C.add(()=>{g=!0,p&&(p.abort(),p=null),s()});const m=()=>{if(g)return;const A=(E,P)=>{n(E==null?void 0:E.statusText,P)};if(!h.loadFile&&r.rawData)throw"Plugin does not support loading ArrayBufferView.";p=h.loadFile?h.loadFile(e,r.rawData||r.file||r.url,r.rootUrl,f,i,d,A,o):e._loadFile(r.file||r.url,f,i,!0,d,A)},_=e.getEngine();let y=_.enableOfflineSupport;if(y){let A=!1;for(const E of e.disableOfflineSupportExceptionRules)if(E.test(r.url)){A=!0;break}y=!A}return y&&Qe.OfflineProviderFactory?e.offlineProvider=Qe.OfflineProviderFactory(r.url,m,_.disableManifestCheck):m(),h}function M_e(r,e){let t,i,n=null,s=null;if(!e)t=r,i=Ie.GetFilename(r),r=Ie.GetFolderPath(r);else if(Rxt(e))t=`file:${e.name}`,i=e.name,n=e;else if(ArrayBuffer.isView(e))t="",i=Xh(),s=e;else if(e.startsWith("data:"))t=e,i="";else if(r){const a=e;if(a.substr(0,1)==="/")return Ie.Error("Wrong sceneFilename parameter"),null;t=r+a,i=a}else t=e,i=Ie.GetFilename(e),r=Ie.GetFolderPath(e);return{url:t,rootUrl:r,name:i,file:n,rawData:s}}function uD(r){if(typeof r.extensions=="string"){const e=r.extensions;yx[e.toLowerCase()]={plugin:r,isBinary:!1}}else{const e=r.extensions;Object.keys(e).forEach(t=>{yx[t.toLowerCase()]={plugin:r,isBinary:e[t].isBinary}})}}function OUe(r,e,t="",i=ei.LastCreatedScene,n=null,s=null,a=null,o=null,l="",c={}){if(!i)return ge.Error("No scene available to import mesh to"),null;const u=M_e(e,t);if(!u)return null;const h={};i.addPendingData(h);const d=()=>{i.removePendingData(h)},f=(m,_)=>{const y=E_e(u,m,_);a?a(i,y,new Q0(y,B_.SceneLoaderError,_)):ge.Error(y),d()},p=s?m=>{try{s(m)}catch(_){f("Error in onProgress callback: "+_,_)}}:void 0,g=(m,_,y,v,x,b,C,A)=>{if(i.importedMeshesFiles.push(u.url),n)try{n(m,_,y,v,x,b,C,A)}catch(E){f("Error in onSuccess callback: "+E,E)}i.removePendingData(h)};return T_e(u,i,(m,_,y)=>{if(m.rewriteRootURL&&(u.rootUrl=m.rewriteRootURL(u.rootUrl,y)),m.importMesh){const v=m,x=[],b=[],C=[];if(!v.importMesh(r,i,_,u.rootUrl,x,b,C,f))return;i.loadingPluginName=m.name,g(x,b,C,[],[],[],[],[])}else m.importMeshAsync(r,i,_,u.rootUrl,p,u.name).then(x=>{i.loadingPluginName=m.name,g(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 Oxt(r,e,t,i,n,s,a,o){return new Promise((l,c)=>{OUe(r,e,t,i,(u,h,d,f,p,g,m,_)=>{l({meshes:u,particleSystems:h,skeletons:d,animationGroups:f,transformNodes:p,geometries:g,lights:m,spriteManagers:_})},n,(u,h,d)=>{c(d||new Error(h))},s,a,o)})}function LUe(r,e="",t=ei.LastCreatedEngine,i=null,n=null,s=null,a=null,o="",l={}){return t?R_e(r,e,new Ut(t),i,n,s,a,o,l):(Ie.Error("No engine available"),null)}function Lxt(r,e,t){const{rootUrl:i="",onProgress:n,pluginExtension:s,name:a,pluginOptions:o}=t??{};return NUe(i,r,e,n,s,a,o)}function NUe(r,e,t,i,n,s,a){return new Promise((o,l)=>{LUe(r,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},n,s,a)})}function R_e(r,e="",t=ei.LastCreatedScene,i=null,n=null,s=null,a=null,o="",l={}){if(!t)return ge.Error("No scene available to append to"),null;const c=M_e(r,e);if(!c)return null;const u={};t.addPendingData(u);const h=()=>{t.removePendingData(u)};hl.ShowLoadingScreen&&!Aae&&(Aae=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),Aae=!1}));const d=(g,m)=>{const _=E_e(c,g,m);s?s(t,_,new Q0(_,B_.SceneLoaderError,m)):ge.Error(_),h()},f=n?g=>{try{n(g)}catch(m){d("Error in onProgress callback",m)}}:void 0,p=()=>{if(i)try{i(t)}catch(g){d("Error in onSuccess callback",g)}t.removePendingData(u)};return T_e(c,t,(g,m)=>{if(g.load){if(!g.load(t,m,c.rootUrl,d))return;t.loadingPluginName=g.name,p()}else g.loadAsync(t,m,c.rootUrl,f,c.name).then(()=>{t.loadingPluginName=g.name,p()}).catch(y=>{d(y.message,y)})},f,d,h,a,o,l)}async function Nxt(r,e,t){const{rootUrl:i="",onProgress:n,pluginExtension:s,name:a,pluginOptions:o}=t??{};await FUe(i,r,e,n,s,a,o)}function FUe(r,e,t,i,n,s,a){return new Promise((o,l)=>{R_e(r,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},n,s,a)})}function I_e(r,e="",t=ei.LastCreatedScene,i=null,n=null,s=null,a=null,o="",l={}){if(!t)return ge.Error("No scene available to load asset container to"),null;const c=M_e(r,e);if(!c)return null;const u={};t.addPendingData(u);const h=()=>{t.removePendingData(u)},d=(g,m)=>{const _=E_e(c,g,m);s?s(t,_,new Q0(_,B_.SceneLoaderError,m)):ge.Error(_),h()},f=n?g=>{try{n(g)}catch(m){d("Error in onProgress callback",m)}}:void 0,p=g=>{if(i)try{i(g)}catch(m){d("Error in onSuccess callback",m)}t.removePendingData(u)};return T_e(c,t,(g,m)=>{if(g.loadAssetContainer){const y=g.loadAssetContainer(t,m,c.rootUrl,d);if(!y)return;y.populateRootNodes(),t.loadingPluginName=g.name,p(y)}else g.loadAssetContainerAsync?g.loadAssetContainerAsync(t,m,c.rootUrl,f,c.name).then(y=>{y.populateRootNodes(),t.loadingPluginName=g.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 Fxt(r,e,t){const{rootUrl:i="",onProgress:n,pluginExtension:s,name:a,pluginOptions:o}=t??{};return BUe(i,r,e,n,s,a,o)}function BUe(r,e,t,i,n,s,a){return new Promise((o,l)=>{I_e(r,e,t,c=>{o(c)},i,(c,u,h)=>{l(h||new Error(u))},n,s,a)})}function kUe(r,e="",t=ei.LastCreatedScene,i=!0,n=0,s=null,a=null,o=null,l=null,c=null,u="",h={}){if(!t){ge.Error("No scene available to load animations to");return}if(i){for(const g of t.animatables)g.reset();t.stopAllAnimations(),t.animationGroups.slice().forEach(g=>{g.dispose()}),t.getNodes().forEach(g=>{g.animations&&(g.animations=[])})}else switch(n){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:ge.Error("Unknown animation group loading mode value '"+n+"'");return}const d=t.animatables.length;I_e(r,e,t,p=>{p.mergeAnimationsTo(t,t.animatables.slice(d),s),p.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),a&&a(t)},o,l,c,u,h)}async function Bxt(r,e,t){const{rootUrl:i="",overwriteAnimations:n,animationGroupLoadingMode:s,targetConverter:a,onProgress:o,pluginExtension:l,name:c,pluginOptions:u}=t??{};await UUe(i,r,e,n,s,a,o,l,c,u)}function UUe(r,e,t,i,n,s,a,o,l,c){return new Promise((u,h)=>{kUe(r,e,t,i,n,s,d=>{u(d)},a,(d,f,p)=>{h(p||new Error(f))},o,l,c)})}class bs{static get ForceFullSceneLoadingForIncremental(){return hl.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){hl.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return hl.ShowLoadingScreen}static set ShowLoadingScreen(e){hl.ShowLoadingScreen=e}static get loggingLevel(){return hl.loggingLevel}static set loggingLevel(e){hl.loggingLevel=e}static get CleanBoneMatrixWeights(){return hl.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){hl.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return A_e()}static GetPluginForExtension(e){return S_e(e).plugin}static IsPluginForExtensionAvailable(e){return Ixt(e)}static RegisterPlugin(e){uD(e)}static ImportMesh(e,t,i,n,s,a,o,l,c){return OUe(e,t,i,n,s,a,o,l,c)}static ImportMeshAsync(e,t,i,n,s,a,o){return Oxt(e,t,i,n,s,a,o)}static Load(e,t,i,n,s,a,o,l){return LUe(e,t,i,n,s,a,o,l)}static LoadAsync(e,t,i,n,s,a){return NUe(e,t,i,n,s,a)}static Append(e,t,i,n,s,a,o,l){return R_e(e,t,i,n,s,a,o,l)}static AppendAsync(e,t,i,n,s,a){return FUe(e,t,i,n,s,a)}static LoadAssetContainer(e,t,i,n,s,a,o,l){return I_e(e,t,i,n,s,a,o,l)}static LoadAssetContainerAsync(e,t,i,n,s,a){return BUe(e,t,i,n,s,a)}static ImportAnimations(e,t,i,n,s,a,o,l,c,u,h){kUe(e,t,i,n,s,a,o,l,c,u,h)}static ImportAnimationsAsync(e,t,i,n,s,a,o,l,c,u,h){return UUe(e,t,i,n,s,a,l,u,h)}}bs.NO_LOGGING=0;bs.MINIMAL_LOGGING=1;bs.SUMMARY_LOGGING=2;bs.DETAILED_LOGGING=3;bs.OnPluginActivatedObservable=DUe;class lT{constructor(e,t,i,n,s=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=n,this._doNotLoadControllerMesh=s,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 wd(o,c,u,h)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new Ce,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?ge.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,n)=>{const s=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)),s(a[0].meshes);return}}bs.ImportMesh("",t.path,t.filename,this.scene,a=>{this._controllerCache&&this._controllerCache.push({...t,meshes:a}),s(a)},null,(a,o)=>{ge.Log(o),ge.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),n(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 n=i?t*.5+.5:t;Oe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),O.LerpToRef(e.minMesh.position,e.maxMesh.position,n,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 Re(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=Oe.FromEulerAngles(0,Math.PI,0)}}class uw extends lT{constructor(e,t,i){super(e,kxt[i],t,i),this.profileId=uw.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Re(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=Oe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}uw.ProfileId="generic-trigger";const kxt={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 zUe extends lT{constructor(e,t,i,n,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=n,this.controllerCache=s,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=bs.IsPluginForExtensionAvailable(".glb");return e||ge.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(n=>{const s=i.visualResponses[n];if(s.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[n]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const a=i.type===wd.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[t].states[n]={valueMesh:this._getChildByName(this.rootMesh,a)},i.type===wd.TOUCHPAD_TYPE&&!this._touchDots[n]){const o=bu(n+"dot",{diameter:.0015,segments:8},this.scene);o.material=new ct(n+"mat",this.scene),o.material.diffuseColor=Pe.Red(),o.parent=this._buttonMeshMapping[t].states[n].valueMesh||null,o.isVisible=!1,this._touchDots[n]=o}}})})}_setRootMesh(e){this.rootMesh=new Re(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 n=this._buttonMeshMapping[t],s=this.layout.components[t];Object.keys(s.visualResponses).forEach(a=>{const o=s.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(n.states[a],l,o.componentProperty!=="button");else{const c=n.states[a].valueMesh;c&&(c.isVisible=i.touched||i.pressed),this._touchDots[a]&&(this._touchDots[a].isVisible=i.touched||i.pressed)}})})}}const Sae=[];class Xl{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 n=[];if(i&&n.push(i),n.push(...e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):n.push("oculus-touch-v2");break}const s=n.indexOf("windows-mixed-reality");if(s!==-1&&n.splice(s,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){const a=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return a.call(this,n,e,t).catch(()=>o.call(this,n,e,t))}else return this._LoadProfilesFromAvailableControllers(n,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=Ie.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){Sae.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),Sae.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(n=>{for(let s=0;s(this._ProfileLoadingPromises[n]||(this._ProfileLoadingPromises[n]=Ie.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${n}/profile.json`,!1).then(s=>JSON.parse(s))),this._ProfileLoadingPromises[n])).then(n=>new zUe(i,t,n,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:Sae))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let n=0;nnew uw(e,r.gamepad,r.handedness));Xl.DefaultFallbacks();let Uxt=0;class VUe{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new O,this._disposed=!1,this.onDisposeObservable=new Ce,this.onMeshLoadedObservable=new Ce,this.onMotionControllerInitObservable=new Ce,this._uniqueId=`controller-${Uxt++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Re(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new Oe,this.inputSource.gripSpace&&(this.grip=new Re(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new Oe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&Xl.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(n=>{this.motionController=n,this.onMotionControllerInitObservable.notifyObservers(n),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(s=>{var a;s&&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())})},()=>{Ie.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;O.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,n){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const a=s.transform.position;this.pointer.position.set(a.x,a.y,a.z).scaleInPlace(n.worldScalingFactor);const o=s.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(n.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(n.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(n.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class GUe{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new Ce,this.onControllerRemovedObservable=new Ce,this._onInputSourcesChange=n=>{this._addAndRemoveControllers(n.added,n.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(n=>n.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(n=>{n.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(n=>{this.controllers.forEach(s=>{s.updateFromXRFrame(n,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)})}),this._options.customControllersRepositoryURL&&(Xl.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Xl.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Xl.UseOnlineRepository)try{Xl.UpdateProfilesList().catch(()=>{Xl.UseOnlineRepository=!1})}catch{Xl.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 VUe(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 n=[],s=[];this.controllers.forEach(a=>{t.indexOf(a.inputSource)===-1?n.push(a):s.push(a)}),this.controllers=n,s.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(),Xl.ClearControllerCache()}}class nc{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&&ge.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 Ce,this.onFeatureDetachObservable=new Ce}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)ge.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 yg extends nc{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:n,selectionMesh:s}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&i.grip?i.grip:i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:n,selectionMesh:s,meshUnderPointer:null,pick:null,tmpRay:new wr(new O,new O),disabledByNearInteraction:!1,id:yg._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 O,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Pe(.9,.9,.9),this.laserPointerDefaultColor=new Pe(.7,.7,.7),this.selectionMeshDefaultColor=new Pe(.8,.8,.8),this.selectionMeshPickedColor=new Pe(.3,.3,1),this._identityMatrix=pe.Identity(),this._screenCoordinatesRef=O.Zero(),this._viewportRef=new Yc(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 wr(new O,new O),disabledByNearInteraction:!1,id:yg._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 n;if(i.xrController)n=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)n=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&n){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),O.ProjectToRef(n,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 s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const a=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!s||!s.hit?i.pick=a:!a||!a.hit||s.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(s,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),s=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 n={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,n):(this._scene.simulatePointerDown(t.pick,n),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,n)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,n),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 n=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.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 wl,{pointerId:l.id,pointerType:"xr"}),l.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}})};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const n=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)})},s=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:s,selectstart:n},this._xrSessionManager.session.addEventListener("selectstart",n),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(O.Dot(e,t.direction)){const n=t.eventListeners&&t.eventListeners[i];n&&this._xrSessionManager.session.removeEventListener(i,n)}),!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 wl,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{Ie.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Tn.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():zu("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const n=new ct("laserPointerMat",t);n.emissiveColor=this.laserPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Pg("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const a=new ct("targetMat",t);return a.specularColor=Pe.Black(),a.emissiveColor=this.selectionMeshDefaultColor,a.backFaceCulling=!1,s.material=a,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var s;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(s=e.pickedPoint)==null||s.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}}yg._IdCounter=200;yg.Name=ln.POINTER_SELECTION;yg.Version=1;Ea.AddWebXRFeature(yg.Name,(r,e)=>()=>new yg(r,e),yg.Version,!0);var re;(function(r){r[r.Float=1]="Float",r[r.Int=2]="Int",r[r.Vector2=4]="Vector2",r[r.Vector3=8]="Vector3",r[r.Vector4=16]="Vector4",r[r.Color3=32]="Color3",r[r.Color4=64]="Color4",r[r.Matrix=128]="Matrix",r[r.Object=256]="Object",r[r.AutoDetect=1024]="AutoDetect",r[r.BasedOnInput=2048]="BasedOnInput",r[r.All=4095]="All"})(re||(re={}));var Ee;(function(r){r[r.Vertex=1]="Vertex",r[r.Fragment=2]="Fragment",r[r.Neutral=4]="Neutral",r[r.VertexAndFragment=3]="VertexAndFragment"})(Ee||(Ee={}));class tRe{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===Ee.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 n="";for(const s in this.functions)n+=this.functions[s]+` `;if(this.compilationString=` ${n} ${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 s in this.extensions){const a=this.extensions[s];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 re.Float:return"float";case re.Int:return"int";case re.Vector2:return"vec2";case re.Color3:case re.Vector3:return"vec3";case re.Color4:case re.Vector4:return"vec4";case re.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===1;switch(e){case re.Float:return t?"f32":"float";case re.Int:return t?"i32":"int";case re.Vector2:return t?"vec2f":"vec2";case re.Color3:case re.Vector3:return t?"vec3f":"vec3";case re.Color4:case re.Vector4:return t?"vec4f":"vec4";case re.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 n=me.GetIncludesShadersStore(this.shaderLanguage);if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `;let s=n[e]+` `;if(this.sharedData.emitComments&&(s=t+` `+s),!i)return s;if(i.replaceStrings)for(let a=0;a${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] `:this.functions[s]=`#include<${e}>${i!=null&&i.substitutionVars?"("+(i==null?void 0:i.substitutionVars)+")":""} `,this.sharedData.emitComments&&(this.functions[s]=t+` `+this.functions[s]);return}if(this.functions[s]=a[e],this.sharedData.emitComments&&(this.functions[s]=t+` `+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,` `)),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,` `)),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,` `)),i.replaceStrings)for(let o=0;o")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),(t,i,n,s)=>`select(${s}, ${n}, ${i})`)}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),(t,i,n)=>`((${i})%(${n}))`)}_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 n=i[1],s=i[2],o=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${n}(${o}) -> ${s}`)}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,n,s)=>`${i} ? ${n} : ${s}`)}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),e=this._convertTernaryOperandsToGLSL(e),e}}class zxt{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 ade;(function(r){r[r.Compatible=0]="Compatible",r[r.TypeIncompatible=1]="TypeIncompatible",r[r.TargetIncompatible=2]="TargetIncompatible",r[r.HierarchyIssue=3]="HierarchyIssue"})(ade||(ade={}));var ode;(function(r){r[r.Input=0]="Input",r[r.Output=1]="Output"})(ode||(ode={}));class oE{static AreEquivalentTypes(e,t){switch(e){case re.Vector3:{if(t===re.Color3)return!0;break}case re.Vector4:{if(t===re.Color4)return!0;break}case re.Color3:{if(t===re.Vector3)return!0;break}case re.Color4:{if(t===re.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===re.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===re.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!==Ee.VertexAndFragment?this._target:this._ownerBlock.target===Ee.Fragment?Ee.Fragment:Ee.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===Ee.Vertex||(e.ownerBlock.target===Ee.Neutral||e.ownerBlock.target===Ee.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===Ee.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Ee.Vertex||e.target===Ee.Vertex||(e.ownerBlock.target===Ee.Neutral||e.ownerBlock.target===Ee.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===Ee.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===Ee.Fragment||(e.ownerBlock.target===Ee.Neutral||e.ownerBlock.target===Ee.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=re.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ce,this.onDisconnectionObservable=new Ce,this.onTypeChangedObservable=new Ce,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Ee.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===Ee.Fragment){if(i.target===Ee.Vertex)return 2;for(const a of i.outputs)if(a.ownerBlock.target!=Ee.Neutral&&a.isConnectedInVertexShader)return 2}if(this.type!==e.type&&e.innerType!==re.AutoDetect)return oE.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&oE.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?0:1;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return 1;let n=i,s=t;return this.direction===0&&(n=t,s=i),n.isAnAncestorOf(s)?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 Li{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=Ee.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 Ce,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===Ee.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=Rz.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===Ee.Neutral}initialize(e){}bind(e,t,i,n){}_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,n,s){return s=s??new oE(e,this,0),s.type=t,s.isOptional=i,n&&(s.target=n),this._inputs.push(s),this}registerOutput(e,t,i,n){return n=n??new oE(e,this,1),n.type=t,i&&(n.target=i),this._outputs.push(n),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===re.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===Ee.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),n=!0;for(;n;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),n=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,n){}provideFallbacks(e,t){}initializeDefines(e,t,i,n=!1){}prepareDefines(e,t,i,n=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,n){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===Ee.Vertex?!1:!!((this.target===Ee.VertexAndFragment||this.target===Ee.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,n=!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,n){e.build(t,n);const s=t._vertexState!=null,a=e._buildTarget===Ee.Vertex&&e.target!==Ee.VertexAndFragment;if(s&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==Ee.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!==Ee.Neutral&&(!(i.target&this.target)||!(i.target&e.target)))continue;const n=i.connectedPoint.ownerBlock;n&&n!==this&&this._processBuild(n,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&ge.Log(`${e.target===Ee.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case Ee.Vertex:e.sharedData.checks.emitVertex=!0;break;case Ee.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 n of i.endpoints){const s=n.ownerBlock;s&&s.target&e.target&&t.indexOf(s)!==-1&&this._processBuild(s,e,n,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 s=0;do s++,this._codeVariableName=i+s;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let n=` // ${this.getClassName()} `;this.comments&&(n+=`// ${this.comments} `),n+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); `,n+=this._dumpPropertiesCode();for(const s of this.inputs){if(!s.isConnected)continue;const o=s.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(n+=o._dumpCode(e,t))}for(const s of this.outputs)if(s.hasEndpoints)for(const a of s.endpoints){const o=a.ownerBlock;o&&t.indexOf(o)===-1&&(n+=o._dumpCode(e,t))}return n}_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 n=i.connectedPoint,s=n.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(n.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); `}return t}clone(e,t=""){const i=this.serialize(),n=Sa(i.customType);if(n){const s=new n;return s._deserialize(i,e,t),s}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,n){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((n,s)=>{n.displayName&&(this.inputs[s].displayName=n.displayName),n.isExposedOnFrame&&(this.inputs[s].isExposedOnFrame=n.isExposedOnFrame,this.inputs[s].exposedPortPosition=n.exposedPortPosition)}),i&&i.forEach((n,s)=>{n.displayName&&(this.outputs[s].displayName=n.displayName),n.isExposedOnFrame&&(this.outputs[s].isExposedOnFrame=n.isExposedOnFrame,this.outputs[s].exposedPortPosition=n.exposedPortPosition)})}dispose(){this.onCodeIsReadyObservable.clear();for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class EZ extends Li{constructor(e){super(e,Ee.Neutral),this.complementW=1,this.complementZ=0,this.target=Ee.Vertex,this.registerInput("vector",re.AutoDetect),this.registerInput("transform",re.Matrix),this.registerOutput("output",re.Vector4),this.registerOutput("xyz",re.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,n=e._getShaderType(re.Vector4),s=e._getShaderType(re.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 re.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${n}(${o} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); `;break;case re.Vector3:case re.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${n}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); `;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${n}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); `;break}}else{const a=i.associatedVariableName;switch(t.connectedPoint.type){case re.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${a} * ${n}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); `;break;case re.Vector3:case re.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${a} * ${n}(${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}}xe("BABYLON.TransformBlock",EZ);class q9 extends Li{constructor(e){super(e,Ee.Vertex,!0),this.registerInput("vector",re.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",re.Float),e._emitVaryingFromString("vFragmentDepth",re.Float);const n=i?"vertexOutputs.vFragmentDepth":"vFragmentDepth",s=i?"uniforms.":"",a=i?"vertexOutputs.position":"gl_Position";e.compilationString+=`${n} = 1.0 + ${a}.w; `,e.compilationString+=`${a}.z = log2(max(0.000001, ${n})) * ${s}logarithmicDepthConstant; `}return this}}xe("BABYLON.VertexOutputBlock",q9);var lde;(function(r){r[r.Boolean=0]="Boolean",r[r.Float=1]="Float",r[r.Int=2]="Int",r[r.Vector2=3]="Vector2",r[r.List=4]="List"})(lde||(lde={}));function Fi(r,e=0,t="PROPERTIES",i){return(n,s)=>{let a=n._propStore;a||(a=[],n._propStore=a),a.push({propertyName:s,displayName:r,type:e,groupName:t,options:i??{}})}}class Ov extends Li{constructor(e){super(e,Ee.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",re.Color4,!0),this.registerInput("rgb",re.AutoDetect,!0),this.registerInput("a",re.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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&&Xo(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,n=this.a,s=e.shaderLanguage===1;e.sharedData.hints.needAlphaBlending=t.isConnected||n.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",re.Float),e._emitVaryingFromString("vFragmentDepth",re.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(re.Vector4);if(t.connectedPoint)n.isConnected?e.compilationString+=`${o} = ${l}(${t.associatedVariableName}.rgb, ${n.associatedVariableName}); `:e.compilationString+=`${o} = ${t.associatedVariableName}; `;else if(i.connectedPoint){let c="1.0";n.connectedPoint&&(c=n.associatedVariableName),i.connectedPoint.type===re.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=s?"input.vFragmentDepth":"vFragmentDepth",u=s?"uniforms.":"",h=s?"fragmentOutputs.fragDepth":"gl_FragDepthEXT";e.compilationString+=`${h} = log2(${c}) * ${u}logarithmicDepthConstant * 0.5; `}return e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=`${s?"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}}V([Fi("Convert to gamma space",0,"PROPERTIES",{notifiers:{update:!0}})],Ov.prototype,"convertToGammaSpace",void 0);V([Fi("Convert to linear space",0,"PROPERTIES",{notifiers:{update:!0}})],Ov.prototype,"convertToLinearSpace",void 0);V([Fi("Use logarithmic depth",0,"PROPERTIES")],Ov.prototype,"useLogarithmicDepth",void 0);xe("BABYLON.FragmentOutputBlock",Ov);var Hr;(function(r){r[r.World=1]="World",r[r.View=2]="View",r[r.Projection=3]="Projection",r[r.ViewProjection=4]="ViewProjection",r[r.WorldView=5]="WorldView",r[r.WorldViewProjection=6]="WorldViewProjection",r[r.CameraPosition=7]="CameraPosition",r[r.FogColor=8]="FogColor",r[r.DeltaTime=9]="DeltaTime",r[r.CameraParameters=10]="CameraParameters",r[r.MaterialAlpha=11]="MaterialAlpha"})(Hr||(Hr={}));var J1;(function(r){r[r.None=0]="None",r[r.Time=1]="Time",r[r.RealTime=2]="RealTime",r[r.MouseInfo=3]="MouseInfo"})(J1||(J1={}));const Vxt={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Eae={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},iRe={particle_texturemask:!0};class Br extends Li{get type(){if(this._type===re.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=re.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=re.Vector2,this._type;case"Vector3":return this._type=re.Vector3,this._type;case"Vector4":return this._type=re.Vector4,this._type;case"Color3":return this._type=re.Color3,this._type;case"Color4":return this._type=re.Color4,this._type;case"Matrix":return this._type=re.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=re.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=re.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=re.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=re.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Hr.World:case Hr.WorldView:case Hr.WorldViewProjection:case Hr.View:case Hr.ViewProjection:case Hr.Projection:return this._type=re.Matrix,this._type;case Hr.CameraPosition:return this._type=re.Vector3,this._type;case Hr.FogColor:return this._type=re.Color3,this._type;case Hr.DeltaTime:case Hr.MaterialAlpha:return this._type=re.Float,this._type;case Hr.CameraParameters:return this._type=re.Vector4,this._type}}return this._type}constructor(e,t=Ee.Vertex,i=re.AutoDetect){super(e,t,!1),this._mode=3,this._animationType=J1.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 Ce,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===re.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 J1.Time:{this.type===re.Float&&(this.value+=e.getAnimationRatio()*.01);break}case J1.RealTime:{this.type===re.Float&&(this.value=(hn.Now-e.getEngine().startTime)/1e3);break}case J1.MouseInfo:{if(this.type===re.Vector4){const t=e._inputManager._originMouseEvent;if(t){const i=t.offsetX,n=t.offsetY,s=t.buttons&1?1:0,a=t.buttons&2?1:0;this.value=new It(i,n,s,a)}else this.value=new It(0,0,0,0)}break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)} `:`#ifdef ${e} `}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case re.Float:this.value=0;break;case re.Vector2:this.value=Ne.Zero();break;case re.Vector3:this.value=O.Zero();break;case re.Vector4:this.value=It.Zero();break;case re.Color3:this.value=Pe.White();break;case re.Color4:this.value=new at(1,1,1,1);break;case re.Matrix:this.value=pe.Identity();break}}_emitConstant(e){switch(this.type){case re.Float:return`${e._emitFloat(this.value)}`;case re.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case re.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case re.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case re.Color3:return En.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&En.Color3[0].toGammaSpaceToRef(En.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&En.Color3[0].toLinearSpaceToRef(En.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${En.Color3[0].r}, ${En.Color3[0].g}, ${En.Color3[0].b})`;case re.Color4:return En.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&En.Color4[0].toGammaSpaceToRef(En.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&En.Color4[0].toLinearSpaceToRef(En.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${En.Color4[0].r}, ${En.Color4[0].g}, ${En.Color4[0].b}, ${En.Color4[0].a})`}return""}get _noContextSwitch(){return Eae[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 n=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case Hr.WorldView:n.needWorldViewMatrix=!0;break;case Hr.WorldViewProjection:n.needWorldViewProjectionMatrix=!0;break}else this._animationType!==J1.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=Vxt[this.name]??this.name,this.target===Ee.Vertex&&e._vertexState){Eae[this.name]?iRe[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),Eae[this.name]?iRe[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,n){if(!this._systemValue)return;const s=this._associatedVariableName;switch(this._systemValue){case Hr.World:e.setMatrix(s,t);break;case Hr.WorldView:e.setMatrix(s,i);break;case Hr.WorldViewProjection:e.setMatrix(s,n);break}}_transmit(e,t,i){if(this.isAttribute)return;const n=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case Hr.World:case Hr.WorldView:case Hr.WorldViewProjection:return;case Hr.View:e.setMatrix(n,t.getViewMatrix());break;case Hr.Projection:e.setMatrix(n,t.getProjectionMatrix());break;case Hr.ViewProjection:e.setMatrix(n,t.getTransformMatrix());break;case Hr.CameraPosition:t.bindEyePosition(e,n,!0);break;case Hr.FogColor:e.setColor3(n,t.fogColor);break;case Hr.DeltaTime:e.setFloat(n,t.deltaTime/1e3);break;case Hr.CameraParameters:t.activeCamera&&e.setFloat4(n,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Hr.MaterialAlpha:e.setFloat(n,i.alpha);break}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(s!==null)switch(this.type){case re.Float:e.setFloat(n,s);break;case re.Int:e.setInt(n,s);break;case re.Color3:En.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&En.Color3[0].toGammaSpaceToRef(En.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&En.Color3[0].toLinearSpaceToRef(En.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(n,En.Color3[0]);break;case re.Color4:En.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&En.Color4[0].toGammaSpaceToRef(En.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&En.Color4[0].toLinearSpaceToRef(En.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(n,En.Color4[0]);break;case re.Vector2:e.setVector2(n,s);break;case re.Vector3:e.setVector3(n,s);break;case re.Vector4:e.setVector4(n,s);break;case re.Matrix:e.setMatrix(n,s);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.${Hr[this._systemValue]}); `;if(this.isUniform){const t=[];let i="";switch(this.type){case re.Float:i=`${this.value}`;break;case re.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case re.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case re.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case re.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case re.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 re.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===re.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${J1[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===re.Vector3&&(this._type=re.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const n=Sa(e.valueType);n&&(this._storedValue=n.FromArray(e.value))}}}xe("BABYLON.InputBlock",Br);class P_e extends Li{constructor(e){super(e,Ee.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",re.AutoDetect,!1,Ee.VertexAndFragment),this.registerOutput("rgba",re.Color4,Ee.Neutral),this.registerOutput("rgb",re.Color3,Ee.Neutral),this.registerOutput("r",re.Float,Ee.Neutral),this.registerOutput("g",re.Float,Ee.Neutral),this.registerOutput("b",re.Float,Ee.Neutral),this.registerOutput("a",re.Float,Ee.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector2|re.Vector3|re.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?Ee.VertexAndFragment:Ee.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,re.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,re.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===Ee.Fragment)return;const s=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,a=e.shaderLanguage===0?"":", 0";e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = ${s} ${i.associatedVariableName}${a}); `;return}const n=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;if(this.uv.ownerBlock.target===Ee.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = ${n} ${i.associatedVariableName}); `;return}e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = ${n} ${this._mainUVName}); `}_writeOutput(e,t,i,n=!1){if(n){if(e.target===Ee.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===Ee.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!==Ee.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=be.Parse(e.texture,t,i))}}xe("BABYLON.CurrentScreenBlock",P_e);class w_e extends Li{constructor(e){super(e,Ee.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",re.AutoDetect,!1,Ee.VertexAndFragment),this.registerOutput("rgba",re.Color4,Ee.Neutral),this.registerOutput("rgb",re.Color3,Ee.Neutral),this.registerOutput("r",re.Float,Ee.Neutral),this.registerOutput("g",re.Float,Ee.Neutral),this.registerOutput("b",re.Float,Ee.Neutral),this.registerOutput("a",re.Float,Ee.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector2|re.Vector3|re.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(n=>n.isAttribute&&n.name==="particle_uv"&&t(n));i||(i=new Br("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===Ee.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,re.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=be.Parse(e.texture,t,i))}}xe("BABYLON.ParticleTextureBlock",w_e);class D_e extends Li{constructor(e){super(e,Ee.Fragment),this._isUnique=!0,this.registerInput("color",re.Color4,!1,Ee.Fragment),this.registerOutput("rampColor",re.Color4,Ee.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!==Ee.Vertex)return e._emit2DSampler("rampSampler","RAMPGRADIENT"),e._emitVaryingFromString("remapRanges",re.Vector4,"RAMPGRADIENT"),e.compilationString+=` #ifdef RAMPGRADIENT ${e._declareLocalVar("baseColor",re.Vector4)} = ${this.color.associatedVariableName}; ${e._declareLocalVar("alpha",re.Float)} = ${this.color.associatedVariableName}.a; ${e._declareLocalVar("remappedColorIndex",re.Float)} = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); ${e._declareLocalVar("rampColor",re.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}}xe("BABYLON.ParticleRampGradientBlock",D_e);class O_e extends Li{constructor(e){super(e,Ee.Fragment),this._isUnique=!0,this.registerInput("color",re.Color4,!1,Ee.Fragment),this.registerInput("alphaTexture",re.Float,!1,Ee.Fragment),this.registerInput("alphaColor",re.Float,!1,Ee.Fragment),this.registerOutput("blendColor",re.Color4,Ee.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!==Ee.Vertex)return e.compilationString+=` #ifdef BLENDMULTIPLYMODE ${e._declareOutput(this.blendColor)}; ${e._declareLocalVar("sourceAlpha",re.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}}xe("BABYLON.ParticleBlendMultiplyBlock",O_e);class J9 extends Li{constructor(e){super(e,Ee.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",re.Vector4,!0),this.registerInput("xyz ",re.Vector3,!0),this.registerInput("xy ",re.Vector2,!0),this.registerInput("zw ",re.Vector2,!0),this.registerInput("x",re.Float,!0),this.registerInput("y",re.Float,!0),this.registerInput("z",re.Float,!0),this.registerInput("w",re.Float,!0),this.registerOutput("xyzw",re.Vector4),this.registerOutput("xyz",re.Vector3),this.registerOutput("xy",re.Vector2),this.registerOutput("zw",re.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,n=this.z,s=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(re.Vector4),g=e._getShaderType(re.Vector3),m=e._getShaderType(re.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}, ${s.isConnected?this._writeVariable(s):"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}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${g}(${a.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"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)+` = ${m}(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"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"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; `),h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${g}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)}; `),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${m}(${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)+` = ${m}(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"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}}xe("BABYLON.VectorMergerBlock",J9);class lV extends Li{constructor(e){super(e,Ee.Neutral),this.sourceRange=new Ne(-1,1),this.targetRange=new Ne(0,1),this.registerInput("input",re.AutoDetect),this.registerInput("sourceMin",re.Float,!0),this.registerInput("sourceMax",re.Float,!0),this.registerInput("targetMin",re.Float,!0),this.registerInput("targetMax",re.Float,!0),this.registerOutput("output",re.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),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=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)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${a} - ${s}) / (${n} - ${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=Ne.FromArray(e.sourceRange),this.targetRange=Ne.FromArray(e.targetRange)}}V([Fi("From",3)],lV.prototype,"sourceRange",void 0);V([Fi("To",3)],lV.prototype,"targetRange",void 0);xe("BABYLON.RemapBlock",lV);class Mee extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(re.Float),this.right.acceptedConnectionPointTypes.push(re.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===re.Int||this.left.type===re.Float&&this.right.type!==re.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=[re.Int,re.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===re.Int||t.type===re.Float)&&e.acceptedConnectionPointTypes.push(re.Vector2,re.Vector3,re.Vector4,re.Color3,re.Color4,re.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach(e=>e.remove()),this._connectionObservers.length=0}}class TZ 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}}xe("BABYLON.MultiplyBlock",TZ);var ah;(function(r){r[r.Material=0]="Material",r[r.PostProcess=1]="PostProcess",r[r.Particle=2]="Particle",r[r.ProceduralTexture=3]="ProceduralTexture"})(ah||(ah={}));class Gxt extends Kn{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 El{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:O.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:O.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:O.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:O.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 n=0;for(const s of t){if(s.gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=O.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 O(10,10,10),this.onAnimationEnd=null,this.blendMode=El.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 Ne(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new O(0,0,0),this._useLogarithmicDepth=!1,this.gravity=O.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 at(1,1,1,1),this.color2=new at(1,1,1,1),this.colorDead=new at(0,0,0,1),this.textureMask=new at(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Gxt,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 O(0,1,0),i=new O(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,n=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new O(0,1,0),s=new O(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 O(0,1,0),n=new O(0,1,0)){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,n){throw new Error("Method not implemented.")}}El.BLENDMODE_ONEONE=0;El.BLENDMODE_STANDARD=1;El.BLENDMODE_ADD=2;El.BLENDMODE_MULTIPLY=3;El.BLENDMODE_MULTIPLYADD=4;xe("BABYLON.BaseParticleSystem",El);class L_e extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("rgba",re.Color4,!0),this.registerInput("rgb ",re.Color3,!0),this.registerOutput("rgb",re.Color3),this.registerOutput("r",re.Float),this.registerOutput("g",re.Float),this.registerOutput("b",re.Float),this.registerOutput("a",re.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],n=this._outputs[1],s=this._outputs[2],a=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb; `),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.r; `),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.g; `),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = ${t.associatedVariableName}.b; `),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a; `),this}}xe("BABYLON.ColorSplitterBlock",L_e);class WUe{constructor(e){this.name=bt.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(bt.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ie.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const Wxt="proceduralVertexShader",Kxt=`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 }`;me.ShadersStore[Wxt]=Kxt;class Bu extends be{constructor(e,t,i,n,s=null,a=!0,o=!1,l=0){super(null,n,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new Ce,this.onBeforeGenerationObservable=new Ce,this.nodeMaterialSource=null,this.defines="",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,s!==null&&!(s instanceof be)?(this._options=s,this._fallbackTexture=s.fallbackTexture??null):(this._options={},this._fallbackTexture=s),n=this.getScene()||ei.LastCreatedScene;let c=n._getComponent(bt.NAME_PROCEDURALTEXTURE);c||(c=new WUe(n),n._addComponent(c)),n.proceduralTextures.push(this),this._fullEngine=n.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=a,this._drawWrapper=new pl(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[ee.PositionKind]=new ee(this._fullEngine,h,ee.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,n){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n,...this._options}),this.setFloat("face",0)):(this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n,...this._options}),this._rtWrapper.is3D&&(this.setFloat("layer",0),this.setInt("layerNum",0))),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[ee.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===vn.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=vn.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)==null||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return this.defines}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,[ee.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var n;(n=this._rtWrapper)==null||n.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 n=this._createRtWrapper(i,e,t,this._textureType);this._texture=n.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 s,a,o,l;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 c in this._textures)this._drawWrapper.effect.setTexture(c,this._textures[c]);for(const c in this._ints)this._drawWrapper.effect.setInt(c,this._ints[c]);for(const c in this._floats)this._drawWrapper.effect.setFloat(c,this._floats[c]);for(const c in this._floatsArrays)this._drawWrapper.effect.setArray(c,this._floatsArrays[c]);for(const c in this._colors3)this._drawWrapper.effect.setColor3(c,this._colors3[c]);for(const c in this._colors4){const u=this._colors4[c];this._drawWrapper.effect.setFloat4(c,u.r,u.g,u.b,u.a)}for(const c in this._vectors2)this._drawWrapper.effect.setVector2(c,this._vectors2[c]);for(const c in this._vectors3)this._drawWrapper.effect.setVector3(c,this._vectors3[c]);for(const c in this._vectors4)this._drawWrapper.effect.setVector4(c,this._vectors4[c]);for(const c in this._matrices)this._drawWrapper.effect.setMatrix(c,this._matrices[c])}if(!this._texture||!this._rtWrapper)return;(s=i._debugPushGroup)==null||s.call(i,`procedural texture generation for ${this.name}`,1);const n=i.currentViewport;if(this.isCube)for(let c=0;c<6;c++)i.bindFramebuffer(this._rtWrapper,c,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",c),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(tt.TriangleFillMode,0,6),i.unBindFramebuffer(this._rtWrapper,!0);else{let c=1;this._rtWrapper.is3D?c=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(c=this._rtWrapper.layers);for(let u=0;u=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[ee.PositionKind];i&&(i.dispose(),this._vertexBuffers[ee.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}V([Q()],Bu.prototype,"isEnabled",void 0);V([Q()],Bu.prototype,"autoClear",void 0);V([Q()],Bu.prototype,"_generateMipMaps",void 0);V([Q()],Bu.prototype,"_size",void 0);V([Q()],Bu.prototype,"refreshRate",null);xe("BABYLON.ProceduralTexture",Bu);var ol;(function(r){r[r.Cos=0]="Cos",r[r.Sin=1]="Sin",r[r.Abs=2]="Abs",r[r.Exp=3]="Exp",r[r.Exp2=4]="Exp2",r[r.Round=5]="Round",r[r.Floor=6]="Floor",r[r.Ceiling=7]="Ceiling",r[r.Sqrt=8]="Sqrt",r[r.Log=9]="Log",r[r.Tan=10]="Tan",r[r.ArcTan=11]="ArcTan",r[r.ArcCos=12]="ArcCos",r[r.ArcSin=13]="ArcSin",r[r.Fract=14]="Fract",r[r.Sign=15]="Sign",r[r.Radians=16]="Radians",r[r.Degrees=17]="Degrees",r[r.Set=18]="Set"})(ol||(ol={}));class N_e extends Li{constructor(e){super(e,Ee.Neutral),this.operation=ol.Cos,this.registerInput("input",re.AutoDetect),this.registerOutput("output",re.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 ol.Cos:{i="cos";break}case ol.Sin:{i="sin";break}case ol.Abs:{i="abs";break}case ol.Exp:{i="exp";break}case ol.Exp2:{i="exp2";break}case ol.Round:{i="round";break}case ol.Floor:{i="floor";break}case ol.Ceiling:{i="ceil";break}case ol.Sqrt:{i="sqrt";break}case ol.Log:{i="log";break}case ol.Tan:{i="tan";break}case ol.ArcTan:{i="atan";break}case ol.ArcCos:{i="acos";break}case ol.ArcSin:{i="asin";break}case ol.Fract:{i="fract";break}case ol.Sign:{i="sign";break}case ol.Radians:{i="radians";break}case ol.Degrees:{i="degrees";break}case ol.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.${ol[this.operation]}; `}}xe("BABYLON.TrigonometryBlock",N_e);const Tae={effect:null,subMesh:null};class A9 extends Kn{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_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NDC_DEPTH=!1,this.PREPASS_NDC_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 Yn extends Va{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||ei.LastCreatedScene),this._buildId=Yn._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new pe,this._cachedWorldViewProjectionMatrix=new pe,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 Ce,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=ah.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:Yn.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 Ie.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&Ee.Vertex&&this._addVertexOutputNode(e),e.target&Ee.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&Ee.Vertex&&this._removeVertexOutputNode(e),e.target&Ee.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=Ee.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=Ee.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,n=!0){(e.target===Ee.VertexAndFragment||t.target===Ee.Fragment&&e.target===Ee.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,n)}_initializeBlock(e,t,i,n=!0){if(e.initialize(t),n&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const s=e.getClassName();for(const a of this.attachedBlocks)if(a.getClassName()===s)throw`Cannot have multiple blocks of type ${s} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const s of e.inputs){s.associatedVariableName="";const a=s.connectedPoint;if(a){const o=a.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,n)}}if(e.isTeleportOut){const s=e;s.entryPoint&&this._processInitializeOnLink(s.entryPoint,t,i,n)}for(const s of e.outputs)s.associatedVariableName=""}_resetDualBlocks(e,t){e.target===Ee.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const n=i.connectedPoint;if(n){const s=n.ownerBlock;s!==e&&this._resetDualBlocks(s,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){ge.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 n=this.getScene().getEngine(),s=this._mode===ah.Particle;if(this._vertexOutputNodes.length===0&&!s)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new tRe,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=Ee.Vertex,this._fragmentCompilationState=new tRe,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=Ee.Fragment,this._sharedData=new zxt,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=s;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,n){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 n)this._resetDualBlocks(o,this._buildId-1);for(const o of n)o.build(this._fragmentCompilationState,n);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Yn._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(ge.Log("Vertex shader:"),ge.Log(this._vertexCompilationState.compilationString),ge.Log("Fragment shader:"),ge.Log(this._fragmentCompilationState.compilationString)),this._buildIsInProgress=!1,this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const s=this.getScene().meshes;for(const o of s)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,n=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(ee.NormalKind),t.TANGENT=e.isVerticesDataPresent(ee.TangentKind);const a=e.useVertexColors&&e.isVerticesDataPresent(ee.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;Dz(this.getScene(),t,!l),(i!==t.NORMAL||n!==t.TANGENT||s!==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.viewDepthNDC.isConnected&&t.push(10),e.viewNormal.isConnected&&t.push(6),e.worldNormal.isConnected&&t.push(8),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.clipSpaceDepth.isConnected&&!t.includes(10)&&t.push(10),i.normal.isConnected&&!t.includes(6)&&t.push(6),i.worldNormal.isConnected&&!t.includes(8)&&t.push(8);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 n of t)i.texturesRequired.includes(n)||i.texturesRequired.push(n);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,n,s,a=0,o=5){return this.mode!==ah.PostProcess?(ge.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,n,s,a,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,n=1,s,a,o=0,l=5){let c=this.name+this._buildId;const u=new A9,h=new Re(c+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(h,u),Sr.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 ii(this.name+"PostProcess",c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,n,s,a,u.toString(),o,c,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l,this.shaderLanguage),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete Sr.ShadersStore[c+"VertexShader"],delete Sr.ShadersStore[c+"PixelShader"],c=this.name+this._buildId,u.markAllAsDirty(),d=this._buildId),this._processDefines(h,u)&&(Sr.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),nw.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!==ah.ProceduralTexture)return ge.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const n=new Bu(i,e,null,t),s=new Re(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const a=new A9,o=this._processDefines(s,a);Sr.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ee.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),o==null?void 0:o.fallbacks,void 0,void 0,void 0,this.shaderLanguage);n.nodeMaterialSource=this,n._setEffect(l);let c=this._buildId;const u=()=>{c!==this._buildId&&(delete Sr.ShadersStore[i+"VertexShader"],delete Sr.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,a.markAllAsDirty(),c=this._buildId);const h=this._processDefines(s,a);h&&(Sr.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),nw.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ee.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),h==null?void 0:h.fallbacks,void 0),n._setEffect(l)})),this._checkInternals(l)};return n.onBeforeGenerationObservable.add(()=>{u()}),this.onBuildObservable.add(()=>{u()}),n}_createEffectForParticles(e,t,i,n,s,a,o,l=""){let c=this.name+this._buildId+"_"+t;a||(a=new A9),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new Re(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let u=this._buildId;const h=[];let d=l;if(!s){const f=this._processDefines(o,a);Sr.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),e.fillDefines(h,t,!1),d=h.join(` `),s=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,f==null?void 0:f.fallbacks,i,n,e,this.shaderLanguage),e.setCustomEffect(s,t)}s.onBindObservable.add(f=>{u!==this._buildId&&(delete Sr.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 g=this._processDefines(o,a);if(g){Sr.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),f=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+` `+d,g==null?void 0:g.fallbacks,i,n,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,n,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 n of this._sharedData.animatedInputs)n.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!==ah.Particle){ge.Log("Incompatible material mode");return}this._createEffectForParticles(e,El.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,El.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==ah.Material){ge.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,n){let s=null;const a=this.getScene();if($J(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,n)}),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 ha;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,h)}),s={lightDisposed:o,uniformBuffers:l,mergedUniforms:c,mergedSamplers:u,fallbacks:h}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const n=this.getScene();if(this._sharedData.animatedInputs){const c=n.getFrameId();if(this._animationFrame!==c){for(const u of this._sharedData.animatedInputs)u.animate(n);this._animationFrame=c}}const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new A9);const a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=n.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&&(Tae.effect=h,Tae.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Tae)),this.allowShaderHotSwapping&&c&&!h.isReady()){if(h=c,a.markAsUnprocessed(),l.lightDisposed)return a._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._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 n of this._sharedData.inputBlocks)n._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const a=this._mustRebind(n,s,i,t.visibility),o=this._sharedData;if(a){for(const l of o.bindableBlocks)l.bind(s,this,t,i);for(const l of o.forcedBindableBlocks)l.bind(s,this,t,i);for(const l of o.inputBlocks)l._transmit(s,n,this)}else if(!this.isFrozen)for(const l of o.forcedBindableBlocks)l.bind(s,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)Yn._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 n of this.getTextureBlocks().filter(s=>s.texture).map(s=>s.texture))n.dispose();for(const n of this.attachedBlocks)n.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:Yn.EditorURL;Ie.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 Br("Position");e.setAsAttribute("position");const t=new Br("World");t.setAsSystemValue(Hr.World);const i=new EZ("WorldPos");e.connectTo(i),t.connectTo(i);const n=new Br("ViewProjection");n.setAsSystemValue(Hr.ViewProjection);const s=new EZ("WorldPos * ViewProjectionTransform");i.connectTo(s),n.connectTo(s);const a=new q9("VertexOutput");s.connectTo(a);const o=new Br("color");o.value=new at(.8,.8,.8,1);const l=new Ov("FragmentOutput");o.connectTo(l),this.addOutputNode(a),this.addOutputNode(l),this._mode=ah.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Br("Position");e.setAsAttribute("position2d");const t=new Br("Constant1");t.isConstant=!0,t.value=1;const i=new J9("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new q9("VertexOutput");i.connectTo(n);const s=new Br("Scale");s.visibleInInspector=!0,s.value=new Ne(1,1);const a=new lV("uv0");e.connectTo(a);const o=new TZ("UV scale");a.connectTo(o),s.connectTo(o);const l=new P_e("CurrentScreen");o.connectTo(l),l.texture=new be("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const c=new Ov("FragmentOutput");l.connectTo(c,{output:"rgba"}),this.addOutputNode(n),this.addOutputNode(c),this._mode=ah.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Br("Position");e.setAsAttribute("position2d");const t=new Br("Constant1");t.isConstant=!0,t.value=1;const i=new J9("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new q9("VertexOutput");i.connectTo(n);const s=new Br("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=J1.Time,s.isConstant=!1;const a=new Br("Color3");a.value=new Pe(1,1,1),a.isConstant=!1;const o=new Ov("FragmentOutput"),l=new J9("VectorMerger");l.visibleInInspector=!1;const c=new N_e("Cos");c.operation=ol.Cos,e.connectTo(l),s.output.connectTo(c.input),c.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(n),this.addOutputNode(o),this._mode=ah.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Br("uv");e.setAsAttribute("particle_uv");const t=new w_e("ParticleTexture");e.connectTo(t);const i=new Br("Color");i.setAsAttribute("particle_color");const n=new TZ("Texture * Color");t.connectTo(n),i.connectTo(n);const s=new D_e("ParticleRampGradient");n.connectTo(s);const a=new L_e("ColorSplitter");i.connectTo(a);const o=new O_e("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),a.connectTo(o,{output:"a"});const l=new Ov("FragmentOutput");o.connectTo(l),this.addOutputNode(l),this._mode=ah.Particle}async loadAsync(e,t=""){return Yn.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 n=i.connectedPoint;if(n){const s=n.ownerBlock;s!==e&&this._gatherBlocks(s,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 n=[];for(const a of this._fragmentOutputNodes)this._gatherBlocks(a,n);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); `;s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${ah[this.mode]}; `;for(const a of t)a.isInput&&e.indexOf(a)===-1&&(s+=a._dumpCode(i,e));for(const a of n)a.isInput&&e.indexOf(a)===-1&&(s+=a._dumpCode(i,e));e=[],s+=` // Connections `;for(const a of this._vertexOutputNodes)s+=a._dumpCodeForOutputConnections(e);for(const a of this._fragmentOutputNodes)s+=a._dumpCodeForOutputConnections(e);s+=` // Output nodes `;for(const a of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;for(const a of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${a._codeVariableName}); `;return s+=`nodeMaterial.build(); `,s}serialize(e){const t=e?{}:ot.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 n of this._vertexOutputNodes)this._gatherBlocks(n,i),t.outputNodes.push(n.uniqueId);for(const n of this._fragmentOutputNodes)this._gatherBlocks(n,i),t.outputNodes.indexOf(n.uniqueId)===-1&&t.outputNodes.push(n.uniqueId)}t.blocks=[];for(const n of i)t.blocks.push(n.serialize());if(!e)for(const n of this.attachedBlocks)i.indexOf(n)===-1&&t.blocks.push(n.serialize());return t.uniqueId=this.uniqueId,t}_restoreConnections(e,t,i){for(const n of e.outputs)for(const s of t.blocks){const a=i[s.id];if(a){for(const o of s.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===n.name){const l=a.getInputByName(o.inputName);if(!l||l.isConnected)continue;n.connectTo(l,!0),this._restoreConnections(a,t,i);continue}}}}parseSerializedObject(e,t="",i=!1,n){i||this.clear();const s={};for(const a of e.blocks){const o=Sa(a.customType);if(o){const l=new o;l._deserialize(a,this.getScene(),t,n),s[a.id]=l,this.attachedBlocks.push(l)}}for(const a of this.attachedBlocks)if(a.isTeleportOut){const o=a,l=o._tempEntryPointUniqueId;l&&s[l].attachToEndpoint(o)}for(let a=0;anew Yn(e,this.getScene(),this.options),this);return n.id=e,n.name=e,n.parseSerializedObject(i),n._buildId=this._buildId,n.build(!1,!t),n}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((n,s)=>{i.onLoadedObservable.addOnce(()=>{n()}),i.onErrorObservable.addOnce(a=>{s(a)})}))}),Promise.all(e)}static Parse(e,t,i="",n=0){const s=ot.Parse(()=>new Yn(e.name,t,{shaderLanguage:n}),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,n="",s=!1,a,o){const l=a??new Yn(e,i),c=await i._loadFileAsync(t),u=JSON.parse(c);return l.parseSerializedObject(u,n,void 0,o),s||l.build(),l}static ParseFromSnippetAsync(e,t=ei.LastCreatedScene,i="",n,s=!1,a=!1,o){return e==="_BLANK"?Promise.resolve(Yn.CreateDefault("blank",t)):new Promise((l,c)=>{const u=new oa;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);n||(n=ot.Parse(()=>new Yn(e,t),d,t,i),n.uniqueId=t.getUniqueId()),n.parseSerializedObject(d,void 0,void 0,o),n.snippetId=e,n.sideOrientation=null;try{s||n.build()}catch(f){c(f)}a?n.whenTexturesReadyAsync().then(()=>{l(n)}).catch(f=>{c(f)}):l(n)}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 Yn(e,t);return i.setToDefault(),i.build(),i}}Yn._BuildIdGenerator=0;Yn.EditorURL=`${Ie._DefaultCdnUrl}/v${Qe.Version}/nodeEditor/babylon.nodeEditor.js`;Yn.SnippetUrl="https://snippet.babylonjs.com";Yn.IgnoreTexturesAtLoadTime=!1;Yn.DefaultShaderLanguage=0;V([Q()],Yn.prototype,"ignoreAlpha",void 0);V([Q()],Yn.prototype,"maxSimultaneousLights",void 0);V([Q("mode")],Yn.prototype,"_mode",void 0);V([Q("comment")],Yn.prototype,"comment",void 0);V([Q()],Yn.prototype,"forceAlphaBlending",void 0);xe("BABYLON.NodeMaterial",Yn);yc.prototype._projectOnTrianglesToRef=function(r,e,t,i,n,s){const a=oe.Vector3[0],o=oe.Vector3[1];let l=1/0;for(let c=this.indexStart;c{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:n,touchCollisionMeshFunction:s,hydrateCollisionMeshFunction:a}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:n,touchCollisionMeshFunction:s,hydrateCollisionMeshFunction:a,currentAnimationState:tf.DEHYDRATED,grabRay:new wr(new O,new O),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:xg._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 Pe(.8,.8,.8),this.selectionMeshPickedColor=new Pe(.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 tf.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===tf.HOVER)break;case tf.HOVER:if(e.touchCollisionMeshFunction(!0),t===tf.TOUCH)break}else switch(e.currentAnimationState){case tf.TOUCH:if(e.touchCollisionMeshFunction(!1),t===tf.HOVER)break;case tf.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===tf.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var s;const n=this._controllers[e];n.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(oe.Vector3[0]),n.grabRay.direction.copyFrom(oe.Vector3[0]),this._options.nearInteractionControllerMode===2&&!((s=n.xrController)!=null&&s.inputSource.hand)&&(n.xrController.getWorldPointerRayToRef(this._tmpRay),n.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),n.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,n.touchCollisionMesh.position.copyFrom(n.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var l;const i=this._controllers[t],n=(l=i.xrController)==null?void 0:l.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!n&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad)){i.pick=null;return}if(i.hoverInteraction=!1,i.nearInteraction=!1,i.xrController){if(n){const c=n.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;oe.Vector3[0].set(u.transform.position.x,u.transform.position.y,u.transform.position.z*h),oe.Quaternion[0].set(u.transform.orientation.x,u.transform.orientation.y,u.transform.orientation.z*h,u.transform.orientation.w*h),this._processTouchPoint(t,oe.Vector3[0],oe.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 s=(c,u)=>{let h=null;return!u||!u.hit?h=c:!c||!c.hit||u.distance{let u=new wl,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=s(h,u);if(d&&d.hit&&(c=a(d),c.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let f=null;const p=(n?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(i,p,this._utilityLayerScene,y=>this._nearPickPredicate(y)));const g=this._pickWithSphere(i,p,this._scene,y=>this._nearPickPredicate(y)),m=s(g,f),_=a(m);_.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=tf.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=tf.TOUCH:i.hoverInteraction&&(o=tf.HOVER),this._handleTransitionAnimation(i,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Tn.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Tn.DefaultUtilityLayer.utilityLayerScene:this._scene,t=bu("nearInteraction",{diameter:.0035*3*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=Oe.Identity();const i=new ct("targetMat",e);return i.specularColor=Pe.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 n=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):s&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const s=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;n(l)}}):(t.selectionComponent=a.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;n(l)}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=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:s},this._xrSessionManager.session.addEventListener("selectstart",s),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 n=t.eventListeners&&t.eventListeners[i];n&&this._xrSessionManager.session.removeEventListener(i,n)}),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 wl,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||Tn.DefaultUtilityLayer.utilityLayerScene:this._scene,i=bu("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let E;this._options.motionControllerTouchMaterialSnippetUrl?E=Yn.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):E=Yn.ParseFromSnippetAsync("8RUNKL#3",t),E.then(P=>{i.material=P}).catch(P=>{ge.Warn(`Error creating touch material in WebXRNearInteraction: ${P}`)})}const n=new g1e;n.setEasingMode(Ja.EASINGMODE_EASEINOUT);const s=new O(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),a=this._controllerPickRadius*(4/3),o=new O(a,a,a).scaleInPlace(e),l=this._controllerPickRadius*(7/6),c=new O(l,l,l).scaleInPlace(e),u=this._controllerPickRadius*(4/5),h=new O(u,u,u).scaleInPlace(e),d=this._controllerPickRadius*(3/2),f=new O(d,d,d).scaleInPlace(e),p=[{frame:0,value:s},{frame:10,value:f},{frame:18,value:o}],g=[{frame:0,value:o},{frame:10,value:h},{frame:18,value:s}],m=[{frame:0,value:O.ZeroReadOnly},{frame:12,value:c},{frame:15,value:s}],_=[{frame:0,value:s},{frame:10,value:O.ZeroReadOnly},{frame:15,value:O.ZeroReadOnly}],y=new dt("touch","scaling",60,dt.ANIMATIONTYPE_VECTOR3,dt.ANIMATIONLOOPMODE_CONSTANT),v=new dt("release","scaling",60,dt.ANIMATIONTYPE_VECTOR3,dt.ANIMATIONLOOPMODE_CONSTANT),x=new dt("hydrate","scaling",60,dt.ANIMATIONTYPE_VECTOR3,dt.ANIMATIONLOOPMODE_CONSTANT),b=new dt("dehydrate","scaling",60,dt.ANIMATIONTYPE_VECTOR3,dt.ANIMATIONLOOPMODE_CONSTANT);return y.setEasingFunction(n),v.setEasingFunction(n),x.setEasingFunction(n),b.setEasingFunction(n),y.setKeys(p),v.setKeys(g),x.setKeys(m),b.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:E=>{const P=E?y:v;t.beginDirectAnimation(i,[P],0,18,!1,1)},hydrateCollisionMeshFunction:E=>{const P=E?x:b;E&&(i.isVisible=!0),t.beginDirectAnimation(i,[P],0,15,!1,1,()=>{E||(i.isVisible=!1)})}}}_pickWithSphere(e,t,i,n){const s=new wl;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const a=e.touchCollisionMesh.position,o=gg.CreateFromCenterAndRadius(a,t);for(let l=0;ld&&(h=0,l.copyFrom(t.center)),h!==-1&&h()=>new xg(r,e),xg.Version,!0);class KUe{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Hxt{}class Ree{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new Ce,this._onSessionGranted=n=>{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 Ie.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 n=t.sessionMode||"immersive-vr",s=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=`${n} - ${s}`,this._buttons.push(new KUe(c,n,s)),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(s=>e.sessionManager.isSessionSupportedAsync(s.sessionMode));e.onStateChangedObservable.add(s=>{s==3&&this._updateButtons(null)}),(await Promise.all(i)).forEach((s,a)=>{s?(this.overlay.appendChild(this._buttons[a].element),this._buttons[a].element.onclick=this._enterXRWithButtonIndex.bind(this,a)):Ie.Warn(`Session mode "${this._buttons[a].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const n=new Ree(e,i);return await n.setHelperAsync(t,i.renderTarget||void 0),n}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,n=i.title;i.title="Error entering XR session : "+n,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 ude;(function(r){r.WRIST="wrist",r.THUMB="thumb",r.INDEX="index",r.MIDDLE="middle",r.RING="ring",r.LITTLE="little"})(ude||(ude={}));var hde;(function(r){r.WRIST="wrist",r.THUMB_METACARPAL="thumb-metacarpal",r.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",r.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",r.THUMB_TIP="thumb-tip",r.INDEX_FINGER_METACARPAL="index-finger-metacarpal",r.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",r.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",r.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",r.INDEX_FINGER_TIP="index-finger-tip",r.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",r.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",r.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",r.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",r.MIDDLE_FINGER_TIP="middle-finger-tip",r.RING_FINGER_METACARPAL="ring-finger-metacarpal",r.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",r.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",r.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",r.RING_FINGER_TIP="ring-finger-tip",r.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",r.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",r.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",r.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",r.PINKY_FINGER_TIP="pinky-finger-tip"})(hde||(hde={}));const Wm=["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"],jxt={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 HUe{get handMesh(){return this._handMesh}getHandPartMeshes(e){return jxt[e].map(t=>this._jointMeshes[Wm.indexOf(t)])}getJointMesh(e){return this._jointMeshes[Wm.indexOf(e)]}constructor(e,t,i,n,s=!1,a=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=n,this._leftHandedMeshes=s,this._jointsInvisible=a,this._jointScaleFactor=o,this.onHandMeshSetObservable=new Ce,this._jointTransforms=new Array(Wm.length),this._jointTransformMatrices=new Float32Array(Wm.length*16),this._tempJointMatrix=new pe,this._jointRadii=new Float32Array(Wm.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(n=>{n.alwaysSelectAsActiveMesh=!0}),this._handMesh.skeleton){const n=this._handMesh.skeleton;Wm.forEach((s,a)=>{const o=n.getBoneIndexByName(t?t[s]:s);o!==-1&&n.bones[o].linkTransformNode(this._jointTransforms[a])})}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const n=i,s=Wm.map(o=>n[o]||i.get(o));let a=!1;if(e.fillPoses&&e.fillJointRadii)a=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){a=!0;for(let o=0;o{const c=this._jointTransforms[l];pe.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 ls extends nc{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var a,o,l,c,u;const n=[],s=((a=e.jointMeshes)==null?void 0:a.sourceMesh)||tV("jointParent",ls._ICOSPHERE_PARAMS);s.isVisible=!!((o=e.jointMeshes)!=null&&o.keepOriginalVisible);for(let h=0;h{var d,f,p,g,m,_;const s={};(f=(d=ls._RightHandGLB)==null?void 0:d.meshes[1])!=null&&f.isDisposed()&&(ls._RightHandGLB=null),(g=(p=ls._LeftHandGLB)==null?void 0:p.meshes[1])!=null&&g.isDisposed()&&(ls._LeftHandGLB=null);const a=!!(ls._RightHandGLB&&ls._LeftHandGLB),o=await Promise.all([ls._RightHandGLB||bs.ImportMeshAsync("",ls.DEFAULT_HAND_MODEL_BASE_URL,ls.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ls._LeftHandGLB||bs.ImportMeshAsync("",ls.DEFAULT_HAND_MODEL_BASE_URL,ls.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ls._RightHandGLB=o[0],ls._LeftHandGLB=o[1];const l=await Yn.ParseFromFileAsync("handShader",ls.DEFAULT_HAND_MODEL_SHADER_URL,e);l.needDepthPrePass=!0,l.transparencyMode=tt.MATERIAL_ALPHABLEND,l.alphaMode=2,l.build(!1);const c={base:Pe.FromInts(116,63,203),fresnel:Pe.FromInts(149,102,229),fingerColor:Pe.FromInts(177,130,255),tipFresnel:Pe.FromInts(220,200,255),...(m=i==null?void 0:i.handMeshes)==null?void 0:m.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"?ls._LeftHandGLB:ls._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,s[y]=x,!a&&!e.useRightHandedSystem&&v.meshes[1].rotate(go.Y,Math.PI)}),l.dispose(),n({left:s.left,right:s.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 Ce,this.onHandRemovedObservable=new Ce,this._attachHand=s=>{var l,c,u;if(!s.inputSource.hand||s.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const a=s.inputSource.handedness,o=new HUe(s,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[s.uniqueId]=o,this._trackingHands[a]=o,this.onHandAddedObservable.notifyObservers(o)},this._detachHand=s=>{this._detachHandById(s.uniqueId)},this.xrNativeFeatureName="hand-tracking";const n=t.jointMeshes;if(n&&(typeof n.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=n.disableDefaultHandMesh),typeof n.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=n.handMeshes),typeof n.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=n.leftHandedSystemMeshes),typeof n.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const s={},a={};[[n.rigMapping.left,s],[n.rigMapping.right,a]].forEach(o=>{const l=o[0],c=o[1];l.forEach((u,h)=>{c[Wm[h]]=u})}),t.handMeshes.customRigMappings={left:s,right:a}}}attach(){var e,t,i,n;return super.attach()?(this._handResources={jointMeshes:ls._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)&&!((n=this.options.handMeshes)!=null&&n.disableDefaultMeshes)&&(ls._GenerateDefaultHandMeshesAsync(ei.LastCreatedScene,this._xrSessionManager,this.options).then(s=>{var a,o;this._handResources.handMeshes=s,this._handResources.rigMappings={left:ls._GenerateDefaultHandMeshRigMapping("left"),right:ls._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(s=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(s.newScaleFactor/s.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(s.newScaleFactor/s.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 n;const i=this.getHandByControllerId(e);if(i){const s=i.xrController.inputSource.handedness=="left"?"left":"right";((n=this._trackingHands[s])==null?void 0:n.xrController.uniqueId)===e&&(this._trackingHands[s]=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(),ls._RightHandGLB=null,ls._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}ls.Name=ln.HAND_TRACKING;ls.Version=1;ls.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";ls.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";ls.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";ls.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";ls._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};ls._RightHandGLB=null;ls._LeftHandGLB=null;Ea.AddWebXRFeature(ls.Name,(r,e)=>()=>new ls(r,e),ls.Version,!1);var dde;(function(r){r[r.INIT=0]="INIT",r[r.STARTED=1]="STARTED",r[r.ENDED=2]="ENDED"})(dde||(dde={}));function S9(r){let e=0;const t=Date.now();r.observableParameters=r.observableParameters??{};const i=r.contextObservable.add(n=>{const s=Date.now();e=s-t;const a={startTime:t,currentTime:s,deltaTime:e,completeRate:e/r.timeout,payload:n};r.onTick&&r.onTick(a),r.breakCondition&&r.breakCondition()&&(r.contextObservable.remove(i),r.onAborted&&r.onAborted(a)),e>=r.timeout&&(r.contextObservable.remove(i),r.onEnded&&r.onEnded(a))},r.observableParameters.mask,r.observableParameters.insertFirst,r.observableParameters.scope);return i}class jUe{constructor(e){this.onEachCountObservable=new Ce,this.onTimerAbortedObservable=new Ce,this.onTimerEndedObservable=new Ce,this.onStateChangedObservable=new Ce,this._observer=null,this._breakOnNextTick=!1,this._tick=t=>{const i=Date.now();this._timer=i-this._startTime;const n={startTime:this._startTime,currentTime:i,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:t},s=this._breakOnNextTick||this._breakCondition(n);s||this._timer>=this._timeToEnd?this._stop(n,s):this.onEachCountObservable.notifyObservers(n)},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 FS extends nc{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 at(1,1,1,1),this._tmpRay=new wr(new O,new O),this._tmpVector=new O,this._tmpQuaternion=new Oe,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 Ce,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new Ce,this.onAfterCameraTeleportRotation=new Ce,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 n=this._controllers[i.uniqueId];if(n.xrController.inputSource.targetRayMode==="tracked-pointer"&&n.xrController.inputSource.gamepad){const s=()=>{if(i.motionController){const a=i.motionController.getComponentOfType(wd.THUMBSTICK_TYPE)||i.motionController.getComponentOfType(wd.TOUCHPAD_TYPE);if(!a||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;n.teleportationState.mainComponentUsed=!0,n.teleportationComponent=o,n.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!this.teleportationEnabled)return;const l=()=>{n.teleportationState.forward=!0,n.teleportationState.initialHit=!1,this._currentTeleportationControllerId=n.xrController.uniqueId,n.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,n.teleportationState.currentRotation=0;const c=this._options.timeToTeleport||3e3;S9({timeout:c,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===n.xrController.uniqueId&&n.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};o.changes.pressed&&(o.changes.pressed.current?this._options.timeToTeleportStart?S9({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{o.pressed&&l()}}):l():(n.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else n.teleportationComponent=a,n.onAxisChangedObserver=a.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&n.teleportationState.backwards&&(n.teleportationState.backwards=!1),o.y>.7&&!n.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!n.teleportationState.backwards){n.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,Oe.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&&!n.teleportationState.rotating&&this.teleportationEnabled&&(n.teleportationState.forward=!0,this._currentTeleportationControllerId=n.xrController.uniqueId,n.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(n.teleportationState.forward)this._currentTeleportationControllerId===n.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{n.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):n.teleportationState.currentRotation=0);else if(!n.teleportationState.rotating&&Math.abs(o.x)>.7){n.teleportationState.rotating=!0;const l=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(l),Oe.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else n.teleportationState.rotating=!1;o.x===0&&o.y===0&&(n.teleportationState.blocked&&(n.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),n.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?s():i.onMotionControllerInitObservable.addOnce(()=>{s()})}else{n.teleportationState.mainComponentUsed=!0;let s=!1;const a=()=>{this._currentTeleportationControllerId=n.xrController.uniqueId,n.teleportationState.forward=!0,n.teleportationState.initialHit=!1,n.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,n.teleportationState.currentRotation=0;const o=this._options.timeToTeleport||3e3;S9({timeout:o,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===n.xrController.uniqueId&&n.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add(o=>{o.type===Wt.POINTERDOWN?(s=!1,this._options.timeToTeleportStart?S9({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===n.xrController.uniqueId&&a()},breakCondition:()=>s?(s=!1,!0):!1}):a()):o.type===Wt.POINTERUP&&(s=!0,n.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 at(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 n;this.parabolicCheckRadius=this.parabolicCheckRadius/i.previousScaleFactor*i.newScaleFactor,(n=this._options.teleportationTargetMesh)==null||n.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(s.teleportationState.mainComponentUsed&&!s.teleportationState.initialHit){s.teleportationState.forward=!1;return}s.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(h);return}else h&&h.pickedPoint&&(s.teleportationState.initialHit=!0,s.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||Tn.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 Ep("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 ct("teleportationPlaneMaterial",e);h.diffuseTexture=a,t.material=h}const i=Pg("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const s=new dt("animationInnerCircle","position.y",30,dt.ANIMATIONTYPE_FLOAT,dt.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),s.setKeys(a);const o=new _1e;o.setEasingMode(Ja.EASINGMODE_EASEINOUT),s.setEasingFunction(o),i.animations=[],i.animations.push(s),e.beginAnimation(i,0,60,!0)}const n=zu("rotationCone",{diameterTop:0,tessellation:4},e);if(n.isPickable=!1,n.scaling.set(.5,.12,.2),n.rotate(go.X,Math.PI/2),n.position.z=.6,n.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,n.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const s=new ct("torusConsMat",e);s.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,s.disableLighting?s.emissiveColor=new Pe(.3,.3,1):s.diffuseColor=new Pe(.3,.3,1),s.alpha=.9,i.material=s,n.material=s,this._teleportationRingMaterial=s}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,n.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,n=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach(a=>{const o=O.DistanceSquared(a,e);o<=s&&o{n.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||Tn.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],n=A0.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,a=this._colorArray.fill(s||this._cachedColor4White),o=n.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(n.getPoints(),e):this._quadraticBezierCurve=zs("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,Oe.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)}}}}FS.Name=ln.TELEPORTATION;FS.Version=1;Ea.AddWebXRFeature(FS.Name,(r,e)=>()=>new FS(r,e),FS.Version,!0);class $xt{}class Iee{constructor(){}static CreateAsync(e,t={}){const i=new Iee;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const n={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Ree(e,n)}return Tee.CreateAsync(e).then(n=>{if(i.baseExperience=n,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new GUe(n.sessionManager,n.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const s={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(yg.Name,t.useStablePlugins?"stable":"latest",s),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(FS.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(xg.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(ls.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(n=>(ge.Error("Error initializing XR"),ge.Error(n),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var Xxt=!0;Ut.prototype.createDefaultLight=function(r=!1){if(r&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),n=i.max.subtract(i.min),s=i.min.add(n.scale(.5));let a,o=n.length()*1.5;if(isFinite(o)||(o=1,s.copyFromFloats(0,0,0)),r){const l=new mn("default camera",-(Math.PI/2),Math.PI/2,o,s,this);l.lowerRadiusLimit=o*.01,l.wheelPrecision=100/o,a=l}else{const l=new ql("default camera",new O(s.x,s.y,-o),this);l.setTarget(s),a=l}a.minZ=o*.01,a.maxZ=o*1e3,a.speed=o*.2,this.activeCamera=a,t&&a.attachControl()}};Ut.prototype.createDefaultCameraOrLight=function(r=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(r,e,t)};Ut.prototype.createDefaultSkybox=function(r,e=!1,t=1e3,i=0,n=!0){if(!r)return ge.Warn("Can not create default skybox without environment texture."),null;n&&r&&(this.environmentTexture=r);const s=jh("hdrSkyBox",{size:t},this);if(e){const a=new ui("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=r.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=be.SKYBOX_MODE),a.microSurface=1-i,a.disableLighting=!0,a.twoSidedLighting=!0,s.material=a}else{const a=new ct("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=r.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=be.SKYBOX_MODE),a.disableLighting=!0,s.material=a}return s.isPickable=!1,s.infiniteDistance=!0,s.ignoreCameraMaxZ=!0,s};Ut.prototype.createDefaultEnvironment=function(r){return Vx?new Vx(r,this):null};Ut.prototype.createDefaultVRExperience=function(r={}){return new tE(this,r)};Ut.prototype.createDefaultXRExperienceAsync=function(r={}){return Iee.CreateAsync(this,r).then(e=>e)};function rRe(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.srcObject=null,r.src="",r.removeAttribute("src")}class Zh extends be{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new Ce),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):ge.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){ge.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,n=!1,s=!1,a=be.TRILINEAR_SAMPLINGMODE,o={},l,c=5){super(null,i,!n,s),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||Ie.IsExponentOfTwo(this.video.videoWidth)&&Ie.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=be.WRAP_ADDRESSMODE,this.wrapV=be.WRAP_ADDRESSMODE):(this.wrapU=be.CLAMP_ADDRESSMODE,this.wrapV=be.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 Ie.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(Ie.SetCorsBehavior(e,t),t.src=e):(Ie.SetCorsBehavior(e[0],t),e.forEach(i=>{const n=document.createElement("source");n.src=i,t.appendChild(n)})),this.onDisposeObservable.addOnce(()=>{rRe(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 Zh(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,n=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(s.mozSrcObject!==void 0?s.mozSrcObject=t:typeof s.srcObject=="object"?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(a=>{const o=()=>{const l=new Zh("video",s,e,!0,n,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{s.remove()}),l.onDisposeObservable.addOnce(()=>{rRe(s)}),a(l),s.removeEventListener("playing",o)};s.addEventListener("playing",o),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,n=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),a=await this.CreateFromStreamAsync(e,s,t,n);return a.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(o=>{o.stop()})}),a}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,n=!1,s=!0){this.CreateFromWebCamAsync(e,i,n,s).then(function(a){t&&t(a)}).catch(function(a){ge.Error(a.name)})}}V([Q("settings")],Zh.prototype,"_settings",void 0);V([Q("src")],Zh.prototype,"_currentSrc",void 0);V([Q()],Zh.prototype,"isVideo",void 0);be._CreateVideoTexture=(r,e,t,i=!1,n=!1,s=be.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new Zh(r,e,t,i,n,s,a,o,l);xe("BABYLON.VideoTexture",Zh);class Pee extends Yh{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Zh((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,be.TRILINEAR_SAMPLINGMODE,n);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()},Wt.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Pee.MODE_MONOSCOPIC=Yh.MODE_MONOSCOPIC;Pee.MODE_TOPBOTTOM=Yh.MODE_TOPBOTTOM;Pee.MODE_SIDEBYSIDE=Yh.MODE_SIDEBYSIDE;class $Ue{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 zo,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 XUe{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(()=>{Ie.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(()=>{Ie.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(()=>{Ie.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(()=>{Ie.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(()=>{Ie.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(()=>{Ie.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(()=>{Ie.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(()=>{Ie.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(()=>{Ie.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(()=>{Ie.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(),Ie.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(()=>{this._renderTime.endMonitoring(!1),Ie.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(),Ie.StartPerformanceCounter(`Rendering camera ${t.name}`)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(t=>{this._cameraRenderTime.endMonitoring(!1),Ie.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 zo,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new zo,this._captureFrameTime=!1,this._frameTime=new zo,this._captureRenderTime=!1,this._renderTime=new zo,this._captureInterFrameTime=!1,this._interFrameTime=new zo,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new zo,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new zo,this._capturePhysicsTime=!1,this._physicsTime=new zo,this._captureAnimationsTime=!1,this._animationsTime=new zo,this._captureCameraRenderTime=!1,this._cameraRenderTime=new zo,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&&(Ie.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&&(Ie.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 ed{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 n=0;n{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let s;const a=this._scene.getEngine();if(n.length){for(a.setColorWrite(!1),s=0;s{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 n=this._scene.getEngine(),s=e.getMesh(),a=(y=s._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:y[n.currentRenderPassId];if(a)return a.isReadyForSubMesh(s,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=[ee.PositionKind];let u=!1,h=!1;if(o){const v=o.needAlphaTesting(),x=o.getAlphaTestTexture(),b=x&&x.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);x&&(v||b)&&(l.push("#define DIFFUSE"),s.isVerticesDataPresent(ee.UV2Kind)&&x.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),h=!0):s.isVerticesDataPresent(ee.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 C=o.opacityTexture;C&&(l.push("#define OPACITY"),s.isVerticesDataPresent(ee.UV2Kind)&&C.coordinatesIndex===1?(l.push("#define OPACITYUV2"),h=!0):s.isVerticesDataPresent(ee.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),s.isVerticesDataPresent(ee.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),h=!0):s.isVerticesDataPresent(ee.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),s.useVertexColors&&s.isVerticesDataPresent(ee.ColorKind)&&s.hasVertexAlpha&&o.transparencyMode!==tt.MATERIAL_OPAQUE&&(c.push(ee.ColorKind),l.push("#define VERTEXALPHA")),u&&(c.push(ee.UVKind),l.push("#define UV1")),h&&(c.push(ee.UV2Kind),l.push("#define UV2"));const d=new ha;if(s.useBones&&s.computeBonesUsingShaders){c.push(ee.MatricesIndicesKind),c.push(ee.MatricesWeightsKind),s.numBoneInfluencers>4&&(c.push(ee.MatricesIndicesExtraKind),c.push(ee.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);const v=s.skeleton;v&&v.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(v?v.bones.length+1:0)),s.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,s)}else l.push("#define NUM_BONE_INFLUENCERS 0");const f=s.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"),tb(c,s,p))),t&&(l.push("#define INSTANCES"),k_(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),x3(o,this._scene,l),this._addCustomEffectDefines(l);const g=e._getDrawWrapper(void 0,!0),m=g.defines,_=l.join(` `);if(m!==_){const v=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Yo(v),g.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 g.effect.isReady()}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([je(()=>Promise.resolve().then(()=>abt),void 0),je(()=>Promise.resolve().then(()=>rbt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>ebt),void 0),je(()=>Promise.resolve().then(()=>Zxt),void 0)])}render(){for(let a=0;ay.setMatrix("world",x))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[ee.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 Ie.Instantiate(e.customType).Parse(e,t,i)}}ed.ForceGLSL=!1;ed._SceneComponentInitialization=r=>{throw Ji("EffectLayerSceneComponent")};V([Q()],ed.prototype,"name",void 0);V([Zw()],ed.prototype,"neutralColor",void 0);V([Q()],ed.prototype,"isEnabled",void 0);V([mBe()],ed.prototype,"camera",null);V([Q()],ed.prototype,"renderingGroupId",null);V([Q()],ed.prototype,"disableBoundingBoxesFromEffectLayer",void 0);vo.AddParser(bt.NAME_EFFECTLAYER,(r,e,t,i)=>{if(r.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let n=0;n{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,n=this.scene.effectLayers;for(const s of n){if(!s.hasMesh(e))continue;const a=s._mainTexture;this._engine.currentRenderPassId=a.renderPassId;for(const o of e.subMeshes)if(!s.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 n of i)if(n.shouldRender()&&(!n.camera||n.camera.cameraRigMode===di.RIG_MODE_NONE&&e===n.camera||n.camera.cameraRigMode!==di.RIG_MODE_NONE&&n.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||n.needStencil();const s=n._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.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=r._getComponent(bt.NAME_EFFECTLAYER);e||(e=new YUe(r),r._addComponent(e))};vo.prototype.getGlowLayerByName=function(r){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===r&&this.effectLayers[t].getEffectName()===Wo.EffectName)return this.effectLayers[t];return null};class Wo extends ed{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 at(0,0,0,1),this._options={mainTextureRatio:Wo.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([je(()=>Promise.resolve().then(()=>qze),void 0),je(()=>Promise.resolve().then(()=>iVe),void 0),je(()=>Promise.resolve().then(()=>B_e),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>Vze),void 0),je(()=>Promise.resolve().then(()=>Hze),void 0),je(()=>Promise.resolve().then(()=>F_e),void 0)]),await super._importShadersAsync()}getEffectName(){return Wo.EffectName}_createMergeEffect(){let e=`#define EMISSIVE `;return this._options.ldrMerge&&(e+=`#define LDR `),this._engine.createEffect("glowMapMerge",[ee.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?Ld(e,this._maxSize):e,t=this._engine.needPOTTextures?Ld(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new vn("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=be.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=be.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(be.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const n=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new vn("GlowLayerBlurRTT2",{width:n,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=be.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=be.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(be.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new Dl("GlowLayerHBP1",new Ne(1,0),a,{width:e,height:t},null,be.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 Dl("GlowLayerVBP1",new Ne(0,1),a,{width:e,height:t},null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Dl("GlowLayerHBP2",new Ne(1,0),a,{width:n,height:s},null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=n,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new Dl("GlowLayerVBP2",new Ne(0,1),a,{width:n,height:s},null,be.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(),n=e.getRenderingMesh();if(!i||!n)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}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(tt.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let n=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(n=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const s=i.emissiveIntensity??1;n*=s,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*n,i.emissiveColor.g*n,i.emissiveColor.b*n,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=ot.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Wo(e.name,t,e.options),e,t,i);let s;for(s=0;s{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(je(()=>Promise.resolve().then(()=>B_e),void 0))):t.push(je(()=>Promise.resolve().then(()=>F_e),void 0)),super._gatherImports(e,t)}}class _u extends ed{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 Ce,this.onAfterBlurObservable=new Ce,this._instanceGlowingMeshStencilReference=_u.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=_u.NeutralColor,this._engine.isStencilEnable||ge.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([je(()=>Promise.resolve().then(()=>qze),void 0),je(()=>Promise.resolve().then(()=>iVe),void 0),je(()=>Promise.resolve().then(()=>B_e),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>Vze),void 0),je(()=>Promise.resolve().then(()=>Hze),void 0),je(()=>Promise.resolve().then(()=>F_e),void 0)]),await super._importShadersAsync()}getEffectName(){return _u.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[ee.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?Ld(e,this._maxSize):e,t=this._engine.needPOTTextures?Ld(t,this._maxSize):t;let i=0;if(this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new vn("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=be.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=be.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(be.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2)this._downSamplePostprocess=new J0("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(n=>{n.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new nRe("HighlightLayerHBP",new Ne(1,0),this._options.blurHorizontalSize,1,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(n=>{n.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new nRe("HighlightLayerVBP",new Ne(0,1),this._options.blurVerticalSize,1,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(n=>{n.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess];else{this._horizontalBlurPostprocess=new Dl("HighlightLayerHBP",new Ne(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i);const n=this._horizontalBlurPostprocess;n.width=e,n.height=t,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new Dl("HighlightLayerVBP",new Ne(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]}this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const n=this._blurTexture.renderTarget;n&&(this._scene.postProcessManager.directRender(this._postProcesses,n,!0),this._engine.unBindFramebuffer(n,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(n=>{n.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n||!this._meshes)return!1;let s=null;const a=this._meshes[n.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_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(tt.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(tt.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 n=this._meshes[e.uniqueId];n?this._emissiveTextureAndColor.color.set(n.color.r,n.color.g,n.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),n&&n.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(n=>{i.stencilState=n.getEngine().getStencilBuffer(),n.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(n=>{n.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 n=this._meshes[e.uniqueId];n?n.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(s=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[s.uniqueId]?this._defaultStencilReference(s):s.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(s=>{this.isEnabled&&this._defaultStencilReference(s)}),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(_u.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=ot.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 n=ot.Parse(()=>new _u(e.name,t,e.options),e,t,i);let s;for(s=0;sthis._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,n,s){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(s)>-1&&(e.layerMask&n)!==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 n=this.scene.layers.indexOf(i);n!==-1&&this.scene.layers.splice(n,1),t&&i.dispose()})}}let wee=class ZUe{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,n,s,a=!1){this.name=e,this._applyPostProcess=!0,this.scale=new Ne(1,1),this.offset=new Ne(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new Ce,this.onBeforeRenderObservable=new Ce,this.onAfterRenderObservable=new Ce,this._shaderLanguage=0,this._shadersLoaded=!1,this.texture=t?new be(t,i,!0):null,this.isBackground=n===void 0?!0:n,this.color=s===void 0?new at(1,1,1,1):s,this._scene=i||ei.LastCreatedScene;const o=this._scene.getEngine();o.isWebGPU&&!a&&!ZUe.ForceGLSL&&(this._shaderLanguage=1);let l=this._scene._getComponent(bt.NAME_LAYER);l||(l=new QUe(this._scene),this._scene._addComponent(l)),this._scene.layers.push(this),this._drawWrapper=new pl(o);const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1);const u=new ee(o,c,ee.PositionKind,!1,!1,2);this._vertexBuffers[ee.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[ee.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",[ee.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([je(()=>Promise.resolve().then(()=>ubt),void 0),je(()=>Promise.resolve().then(()=>cbt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>lbt),void 0),je(()=>Promise.resolve().then(()=>obt),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(tt.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(tt.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[ee.PositionKind];e&&(e.dispose(),this._vertexBuffers[ee.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()}};wee.ForceGLSL=!1;const qUe="helperFunctions",JUe=`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;} `;me.IncludesShadersStore[qUe]=JUe;const eze={name:qUe,shader:JUe},tze=Object.freeze(Object.defineProperty({__proto__:null,helperFunctions:eze},Symbol.toStringTag,{value:"Module"})),ize="clipPlaneFragmentDeclaration",rze=`#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 `;me.IncludesShadersStore[ize]=rze;const nze={name:ize,shader:rze},Yxt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentDeclaration:nze},Symbol.toStringTag,{value:"Module"})),sze="clipPlaneFragment",aze=`#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 `;me.IncludesShadersStore[sze]=aze;const oze={name:sze,shader:aze},Qxt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragment:oze},Symbol.toStringTag,{value:"Module"})),lze="glowMapGenerationPixelShader",cze=`#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 }`;me.ShadersStore[_ze]=vze;const yze={name:_ze,shader:vze},ebt=Object.freeze(Object.defineProperty({__proto__:null,glowMapGenerationVertexShader:yze},Symbol.toStringTag,{value:"Module"})),xze="clipPlaneFragmentDeclaration",bze=`#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 `;me.IncludesShadersStoreWGSL[xze]=bze;const Cze={name:xze,shader:bze},tbt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentDeclarationWGSL:Cze},Symbol.toStringTag,{value:"Module"})),Aze="clipPlaneFragment",Sze=`#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 `;me.IncludesShadersStoreWGSL[Aze]=Sze;const Eze={name:Aze,shader:Sze},ibt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneFragmentWGSL:Eze},Symbol.toStringTag,{value:"Module"})),Tze="glowMapGenerationPixelShader",Mze=`#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 `;me.IncludesShadersStoreWGSL[Ize]=Pze;const wze={name:Ize,shader:Pze},nbt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertexDeclarationWGSL:wze},Symbol.toStringTag,{value:"Module"})),Dze="clipPlaneVertex",Oze=`#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 `;me.IncludesShadersStoreWGSL[Dze]=Oze;const Lze={name:Dze,shader:Oze},sbt=Object.freeze(Object.defineProperty({__proto__:null,clipPlaneVertexWGSL:Lze},Symbol.toStringTag,{value:"Module"})),Nze="glowMapGenerationVertexShader",Fze=`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 }`;me.ShadersStoreWGSL[Nze]=Fze;const Bze={name:Nze,shader:Fze},abt=Object.freeze(Object.defineProperty({__proto__:null,glowMapGenerationVertexShaderWGSL:Bze},Symbol.toStringTag,{value:"Module"})),kze="glowMapMergePixelShader",Uze=`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 }`;me.ShadersStore[kze]=Uze;const zze={name:kze,shader:Uze},Vze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergePixelShader:zze},Symbol.toStringTag,{value:"Module"})),Gze="glowMapMergeVertexShader",Wze=`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 }`;me.ShadersStore[Gze]=Wze;const Kze={name:Gze,shader:Wze},Hze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergeVertexShader:Kze},Symbol.toStringTag,{value:"Module"})),jze="glowBlurPostProcessPixelShader",$ze=`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;}`;me.ShadersStore[jze]=$ze;const Xze={name:jze,shader:$ze},F_e=Object.freeze(Object.defineProperty({__proto__:null,glowBlurPostProcessPixelShader:Xze},Symbol.toStringTag,{value:"Module"})),Yze="glowMapMergePixelShader",Qze=`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 }`;me.ShadersStoreWGSL[Yze]=Qze;const Zze={name:Yze,shader:Qze},qze=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergePixelShaderWGSL:Zze},Symbol.toStringTag,{value:"Module"})),Jze="glowMapMergeVertexShader",eVe=`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 }`;me.ShadersStoreWGSL[Jze]=eVe;const tVe={name:Jze,shader:eVe},iVe=Object.freeze(Object.defineProperty({__proto__:null,glowMapMergeVertexShaderWGSL:tVe},Symbol.toStringTag,{value:"Module"})),rVe="glowBlurPostProcessPixelShader",nVe=`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;}`;me.ShadersStoreWGSL[rVe]=nVe;const sVe={name:rVe,shader:nVe},B_e=Object.freeze(Object.defineProperty({__proto__:null,glowBlurPostProcessPixelShaderWGSL:sVe},Symbol.toStringTag,{value:"Module"})),aVe="layerPixelShader",oVe=`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 }`;me.ShadersStore[aVe]=oVe;const lVe={name:aVe,shader:oVe},obt=Object.freeze(Object.defineProperty({__proto__:null,layerPixelShader:lVe},Symbol.toStringTag,{value:"Module"})),cVe="layerVertexShader",uVe=`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 }`;me.ShadersStore[cVe]=uVe;const hVe={name:cVe,shader:uVe},lbt=Object.freeze(Object.defineProperty({__proto__:null,layerVertexShader:hVe},Symbol.toStringTag,{value:"Module"})),dVe="layerPixelShader",fVe=`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 }`;me.ShadersStoreWGSL[dVe]=fVe;const pVe={name:dVe,shader:fVe},cbt=Object.freeze(Object.defineProperty({__proto__:null,layerPixelShaderWGSL:pVe},Symbol.toStringTag,{value:"Module"})),mVe="layerVertexShader",gVe=`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 }`;me.ShadersStoreWGSL[mVe]=gVe;const _Ve={name:mVe,shader:gVe},ubt=Object.freeze(Object.defineProperty({__proto__:null,layerVertexShaderWGSL:_Ve},Symbol.toStringTag,{value:"Module"}));class Dee{static AddFlare(e,t,i,n,s){return new Dee(e,t,i,n,s)}constructor(e,t,i,n,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Pe(1,1,1),this.texture=n?new be(n,s.getScene(),!0):null,this._system=s;const a=s.scene.getEngine();s._onShadersLoaded.addOnce(()=>{this._drawWrapper=new pl(a),this._drawWrapper.effect=a.createEffect("lensFlare",[ee.PositionKind],["color","viewportMatrix"],["textureSampler"],"",void 0,void 0,void 0,void 0,s.shaderLanguage)}),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}class jv{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 Ce(void 0,!0),this._shadersLoaded=!1,this._scene=i||ei.LastCreatedScene,jv._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 n=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[ee.PositionKind]=new ee(n,s,ee.PositionKind,!1,!1,2),this._createIndexBuffer(),this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!jv.ForceGLSL?(this._shaderLanguage=1,await Promise.all([je(()=>Promise.resolve().then(()=>fbt),void 0),je(()=>Promise.resolve().then(()=>pbt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>hbt),void 0),je(()=>Promise.resolve().then(()=>dbt),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=O.Project(t,pe.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=O.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 n,s;this._positionXi.x+i.width-this.borderLimit?n=this._positionX-i.x-i.width+this.borderLimit:n=0,this._positionYi.y+i.height-this.borderLimit?s=this._positionY-i.y-i.height+this.borderLimit:s=0;let a=n>s?n:s;a-=this.viewportBorder,a>this.borderLimit&&(a=this.borderLimit);let o=1-Xt.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 Ji("LensFlareSystemSceneComponent")};vo.AddParser(bt.NAME_LENSFLARESYSTEM,(r,e,t,i)=>{if(r.lensFlareSystems!==void 0&&r.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let n=0,s=r.lensFlareSystems.length;n{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;Ie.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ie.EndPerformanceCounter("Lens flares",t.length>0)}}}jv._SceneComponentInitialization=r=>{let e=r._getComponent(bt.NAME_LENSFLARESYSTEM);e||(e=new vVe(r),r._addComponent(e))};const yVe="lensFlarePixelShader",xVe=`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 }`;me.ShadersStore[yVe]=xVe;const bVe={name:yVe,shader:xVe},hbt=Object.freeze(Object.defineProperty({__proto__:null,lensFlarePixelShader:bVe},Symbol.toStringTag,{value:"Module"})),CVe="lensFlareVertexShader",AVe=`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 }`;me.ShadersStore[CVe]=AVe;const SVe={name:CVe,shader:AVe},dbt=Object.freeze(Object.defineProperty({__proto__:null,lensFlareVertexShader:SVe},Symbol.toStringTag,{value:"Module"})),EVe="lensFlarePixelShader",TVe=`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 }`;me.ShadersStoreWGSL[EVe]=TVe;const MVe={name:EVe,shader:TVe},fbt=Object.freeze(Object.defineProperty({__proto__:null,lensFlarePixelShaderWGSL:MVe},Symbol.toStringTag,{value:"Module"})),RVe="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 }`;me.ShadersStoreWGSL[RVe]=IVe;const PVe={name:RVe,shader:IVe},pbt=Object.freeze(Object.defineProperty({__proto__:null,lensFlareVertexShaderWGSL:PVe},Symbol.toStringTag,{value:"Module"}));class Qi{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===Qi.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===Qi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===Qi.FILTER_PCF||e===Qi.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===Qi.FILTER_PCF||e===Qi.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===Qi.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Qi.FILTER_POISSONSAMPLING);!e&&this.filter!==Qi.FILTER_POISSONSAMPLING||(this.filter=e?t:Qi.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Qi.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Qi.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==Qi.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:Qi.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Qi.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Qi.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==Qi.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:Qi.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Qi.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Qi.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==Qi.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:Qi.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Qi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Qi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==Qi.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:Qi.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Qi.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Qi.FILTER_PCF);!e&&this.filter!==Qi.FILTER_PCF||(this.filter=e?t:Qi.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===Qi.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Qi.FILTER_PCSS);!e&&this.filter!==Qi.FILTER_PCSS||(this.filter=e?t:Qi.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 Qi.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 n of e.getChildren())this.removeShadowCaster(n);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,n,s,a=!1){this.onBeforeShadowMapRenderObservable=new Ce,this.onAfterShadowMapRenderObservable=new Ce,this.onBeforeShadowMapRenderMeshObservable=new Ce,this.onAfterShadowMapRenderMeshObservable=new Ce,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Qi.FILTER_NONE,this._filteringQuality=Qi.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=O.Zero(),this._viewMatrix=pe.Zero(),this._projectionMatrix=pe.Zero(),this._transformMatrix=pe.Zero(),this._cachedPosition=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=pe.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=n??null,this._useRedTextureType=!!s,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}")`))),Qi._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 vn(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 vn(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=be.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=be.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(be.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(n,s,a,o)=>this._renderForShadowMap(n,s,a,o),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var n;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(n=e._debugPushGroup)==null||n.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(n=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=n,this._filter===Qi.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 s,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Qi.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)==null||s.call(e,1);return}const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),(a=e._debugPopGroup)==null||a.call(e,1))});const t=new at(0,0,0,0),i=new at(1,1,1,1);this._shadowMap.onClearObservable.add(n=>{this._filter===Qi.FILTER_PCF?n.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?n.clear(t,!0,!0,!1):n.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(n=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=n.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let n=Rc.MIN_RENDERINGGROUPS;nPromise.resolve().then(()=>wbt),void 0),je(()=>Promise.resolve().then(()=>Bbt),void 0),je(()=>Promise.resolve().then(()=>kbt),void 0),je(()=>Promise.resolve().then(()=>Ubt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>Hbt),void 0),je(()=>Promise.resolve().then(()=>cCt),void 0),je(()=>Promise.resolve().then(()=>uCt),void 0),je(()=>Promise.resolve().then(()=>hCt),void 0)]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){const e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new vn(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=be.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=be.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(be.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Dl(this._light.name+"KernelBlurX",new Ne(1,0),this.blurKernel,1,null,be.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 Dl(this._light.name+"KernelBlurY",new Ne(0,1),this.blurKernel,1,null,be.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 ii(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,be.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,n){let s;if(n.length)for(s=0;s{n!==i&&!x?(i.getMeshUniformBuffer().bindToEffect(_,"Mesh"),i.transferToEffect(b)):(n.getMeshUniformBuffer().bindToEffect(_,"Mesh"),n.transferToEffect(x?b: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===Qi.FILTER_NONE||this.filter===Qi.FILTER_PCSS?this._shadowMap.updateSamplingMode(be.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(be.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},n=this.getShadowMap();if(!n){e&&e(this);return}const s=n.renderList;if(!s){e&&e(this);return}const a=[];for(const c of s)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,n){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 s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(ee.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Dr.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&n?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){if(!this._shadersLoaded)return!1;const n=e.getMaterial(),s=n==null?void 0:n.shadowDepthWrapper;if(this._opacityTexture=null,!n)return!1;const a=[];if(this._prepareShadowDefines(e,t,a,i),s){if(!s.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=[ee.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(ee.NormalKind)&&(u.push(ee.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));const d=n.needAlphaTesting();if((d||n.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=n.opacityTexture:this._opacityTexture=n.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const y=n.alphaCutOff??Qi.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),d&&a.push(`#define ALPHATESTVALUE ${y}${y%1===0?".":""}`),h.isVerticesDataPresent(ee.UVKind)&&(u.push(ee.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(ee.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(u.push(ee.UV2Kind),a.push("#define UV2"))}const f=new ha;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){u.push(ee.MatricesIndicesKind),u.push(ee.MatricesWeightsKind),h.numBoneInfluencers>4&&(u.push(ee.MatricesIndicesExtraKind),u.push(ee.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 g=0;if(p&&(g=p.numMaxInfluencers||p.numInfluencers,g>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+g),p.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),tb(u,h,g))),x3(n,this._scene,a),t&&(a.push("#define INSTANCES"),k_(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 m=h.bakedVertexAnimationManager;m&&m.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&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"],b=["Scene","Mesh"];if(Yo(v),this.customShaderOptions){if(y=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const A of this.customShaderOptions.attributes)u.indexOf(A)===-1&&u.push(A);if(this.customShaderOptions.uniforms)for(const A of this.customShaderOptions.uniforms)v.indexOf(A)===-1&&v.push(A);if(this.customShaderOptions.samplers)for(const A of this.customShaderOptions.samplers)x.indexOf(A)===-1&&x.push(A)}const C=this._scene.getEngine();l=C.createEffect(y,{attributes:u,uniformsNames:v,uniformBuffersNames:b,samplers:x,defines:_,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._shaderLanguage},C),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,n=this._light;!i.shadowsEnabled||!n.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Qi.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Qi.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Qi.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Qi.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),n.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const a=this.getShadowMap();if(!a)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const o=this.getShadowMapForRendering();this._filter===Qi.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===Qi.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(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),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),O.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(O.Dot(this._lightDirection,O.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),pe.LookAtLHToRef(t,t.add(this._lightDirection),O.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const n=i.renderList;n&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,n)}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,n]=t.value;n===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 n=0;n{throw Ji("ShadowGeneratorSceneComponent")};const wVe="packingFunctions",DVe=`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);}`;me.IncludesShadersStore[wVe]=DVe;const OVe={name:wVe,shader:DVe},mbt=Object.freeze(Object.defineProperty({__proto__:null,packingFunctions:OVe},Symbol.toStringTag,{value:"Module"})),LVe="depthPixelShader",NVe=`#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 }`;me.ShadersStore[LVe]=NVe;const FVe={name:LVe,shader:NVe},gbt=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShader:FVe},Symbol.toStringTag,{value:"Module"})),_bt="pointCloudVertexDeclaration",vbt=`#ifdef POINTSIZE uniform float pointSize; #endif `;me.IncludesShadersStore[_bt]=vbt;const ybt="pointCloudVertex",xbt=`#if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif `;me.IncludesShadersStore[ybt]=xbt;const BVe="depthVertexShader",kVe=`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 } `;me.ShadersStore[BVe]=kVe;const UVe={name:BVe,shader:kVe},bbt=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShader:UVe},Symbol.toStringTag,{value:"Module"}));class I_{get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,n=!1,s=be.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=n,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new at(1,1,1,1):this.clearColor=new at(a?1e8:1,0,0,1),this._initShaderSourceAsync(),I_._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,s!==be.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(s=be.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(s=be.NEAREST_SAMPLINGMODE));const c=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new vn(o??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,c),this._depthMap.wrapU=be.CLAMP_ADDRESSMODE,this._depthMap.wrapV=be.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 A;const d=h.getRenderingMesh(),f=h.getEffectiveMesh(),p=this._scene,g=p.getEngine(),m=h.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!m||f.infiniteDistance||m.disableDepthWrite||h.verticesCount===0||h._renderId===p.getRenderId())return;const _=f._getWorldMatrixDeterminant()<0;let y=m._getEffectiveOrientation(d);_&&(y=y===0?1:0);const v=y===0;g.setState(m.backFaceCulling,0,!1,v,this.reverseCulling?!m.cullBackFaces:m.cullBackFaces);const x=d._getInstancesRenderList(h._id,!!h.getReplacementMesh());if(x.mustReturn)return;const b=g.getCaps().instancedArrays&&(x.visibleInstances[h._id]!==null&&x.visibleInstances[h._id]!==void 0||d.hasThinInstances),C=this._camera||p.activeCamera;if(this.isReady(h,b)&&C){h._renderId=p.getRenderId();const E=(A=f._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:A[g.currentRenderPassId];let P=h._getDrawWrapper();!P&&E&&(P=E._getDrawWrapper());const w=C.mode===di.ORTHOGRAPHIC_CAMERA;if(!P)return;const M=P.effect;g.enableEffect(P),b||d._bind(h,M,m.fillMode),E?E.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(w?(R=!g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:1,I=g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:1):(R=g.useReverseDepthBuffer&&g.isNDCHalfZRange?C.minZ:g.isNDCHalfZRange?0:C.minZ,I=g.useReverseDepthBuffer&&g.isNDCHalfZRange?0:C.maxZ),M.setFloat2("depthValues",R,R+I),!E){if(m.needAlphaTesting()){const k=m.getAlphaTestTexture();k&&(M.setTexture("diffuseSampler",k),M.setMatrix("diffuseMatrix",k.getTextureMatrix()))}rc(d,M),wo(M,m,p),Np(d,M),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind(M);const D=h.getMesh().bakedVertexAnimationManager;D&&D.isEnabled&&D.bind(M,b),m.pointsCloud&&M.setFloat("pointSize",m.pointSize)}d._processRendering(f,h,M,m.fillMode,x,b,(D,k)=>M.setMatrix("world",k))}};this._depthMap.customRenderFunction=(h,d,f,p)=>{let g;if(p.length)for(g=0;gPromise.resolve().then(()=>kwt),void 0),je(()=>Promise.resolve().then(()=>Bwt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>bbt),void 0),je(()=>Promise.resolve().then(()=>gbt),void 0)]),this._shadersLoaded=!0}isReady(e,t){var _;if(!this._shadersLoaded)return!1;const i=this._scene.getEngine(),n=e.getMesh(),s=n.getScene(),a=(_=n._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:_[i.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);const o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;const l=[],c=[ee.PositionKind];o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),n.isVerticesDataPresent(ee.UVKind)&&(c.push(ee.UVKind),l.push("#define UV1")),n.isVerticesDataPresent(ee.UV2Kind)&&(c.push(ee.UV2Kind),l.push("#define UV2")));const u=new ha;if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){c.push(ee.MatricesIndicesKind),c.push(ee.MatricesWeightsKind),n.numBoneInfluencers>4&&(c.push(ee.MatricesIndicesExtraKind),c.push(ee.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),n.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,n);const y=n.skeleton;y.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(y.bones.length+1))}else l.push("#define NUM_BONE_INFLUENCERS 0");const h=n.morphTargetManager;let d=0;h&&(d=h.numMaxInfluencers||h.numInfluencers,d>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+d),h.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),tb(c,n,d))),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),k_(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES"));const f=n.bakedVertexAnimationManager;f&&f.isEnabled&&(l.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&c.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),x3(o,s,l);const p=e._getDrawWrapper(void 0,!0),g=p.defines,m=l.join(` `);if(g!==m){const y=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],v=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];Yo(y),p.setEffect(i.createEffect("depth",{attributes:c,uniformsNames:y,uniformBuffersNames:[],samplers:v,defines:m,fallbacks:u,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d},shaderLanguage:this._shaderLanguage},i))}return p.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]}}}I_.ForceGLSL=!1;I_._SceneComponentInitialization=r=>{throw Ji("DepthRendererSceneComponent")};const Cbt="minmaxReduxPixelShader",Abt=`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 `;me.ShadersStore[Cbt]=Abt;class zVe{constructor(e){this.onAfterReductionPerformed=new Ce,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Xk(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,n=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=n;const s=this._camera.getScene(),a=new ii("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?` #define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);a.autoClear=!1,a.forceFullscreenViewport=n;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 ii("Reduction phase "+c,"minmaxRedux",["texSize"],null,{width:o,height:l},null,1,s.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=n,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 g=new Float32Array(4*d*f),m={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(p.inputTexture.texture,d,f,-1,0,g,!1),m.min=g[0],m.max=g[1],this.onAfterReductionPerformed.notifyObservers(m)}};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 dc.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 n=i.min,s=i.max;n>=s&&(n=0,s=1),(n!=this._minDistance||s!=this._maxDistance)&&this.setMinMaxDistance(n,s)}),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,n=i-t,s=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+s*n,l=t+a*n,c=l-o,u=l/o;for(let h=0;h{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Qi.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!==Qi.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,n=this._light;if(!i.shadowsEnabled||!n.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.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 s=this._getCamera();if(!s)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===Qi.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===Qi.FILTER_PCSS){for(let l=0;lnew dc(n,s,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}}dc._FrustumCornersNDCSpace=[new O(-1,1,-1),new O(1,1,-1),new O(1,-1,-1),new O(-1,-1,-1),new O(-1,1,1),new O(1,1,1),new O(1,-1,1),new O(-1,-1,1)];dc.CLASSNAME="CascadedShadowGenerator";dc.DEFAULT_CASCADES_COUNT=4;dc.MIN_CASCADES_COUNT=2;dc.MAX_CASCADES_COUNT=4;dc._SceneComponentInitialization=r=>{throw Ji("ShadowGeneratorSceneComponent")};vo.AddParser(bt.NAME_SHADOWGENERATOR,(r,e)=>{if(r.shadowGenerators!==void 0&&r.shadowGenerators!==null)for(let t=0,i=r.shadowGenerators.length;t{let e=r._getComponent(bt.NAME_SHADOWGENERATOR);e||(e=new GVe(r),r._addComponent(e))};const WVe="packingFunctions",KVe=`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);}`;me.IncludesShadersStoreWGSL[WVe]=KVe;const HVe={name:WVe,shader:KVe},Ebt=Object.freeze(Object.defineProperty({__proto__:null,packingFunctionsWGSL:HVe},Symbol.toStringTag,{value:"Module"})),Tbt="bayerDitherFunctions",Mbt=`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);} `;me.IncludesShadersStoreWGSL[Tbt]=Mbt;const Rbt="shadowMapFragmentExtraDeclaration",Ibt=`#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 `;me.IncludesShadersStoreWGSL[Rbt]=Ibt;const jVe="shadowMapFragment",$Ve=`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 `;me.IncludesShadersStoreWGSL[jVe]=$Ve;const XVe={name:jVe,shader:$Ve},Pbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentWGSL:XVe},Symbol.toStringTag,{value:"Module"})),YVe="shadowMapPixelShader",QVe=`#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 }`;me.ShadersStoreWGSL[YVe]=QVe;const ZVe={name:YVe,shader:QVe},wbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapPixelShaderWGSL:ZVe},Symbol.toStringTag,{value:"Module"})),Dbt="shadowMapVertexExtraDeclaration",Obt=`#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 `;me.IncludesShadersStoreWGSL[Dbt]=Obt;const Lbt="shadowMapVertexNormalBias",Nbt=`#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 `;me.IncludesShadersStoreWGSL[Lbt]=Nbt;const qVe="shadowMapVertexMetric",JVe=`#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 `;me.IncludesShadersStoreWGSL[qVe]=JVe;const eGe={name:qVe,shader:JVe},Fbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexMetricWGSL:eGe},Symbol.toStringTag,{value:"Module"})),tGe="shadowMapVertexShader",iGe=`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 }`;me.ShadersStoreWGSL[tGe]=iGe;const rGe={name:tGe,shader:iGe},Bbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexShaderWGSL:rGe},Symbol.toStringTag,{value:"Module"})),nGe="depthBoxBlurPixelShader",sGe=`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)));}`;me.ShadersStoreWGSL[nGe]=sGe;const aGe={name:nGe,shader:sGe},kbt=Object.freeze(Object.defineProperty({__proto__:null,depthBoxBlurPixelShaderWGSL:aGe},Symbol.toStringTag,{value:"Module"})),oGe="shadowMapFragmentSoftTransparentShadow",lGe=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;} #endif `;me.IncludesShadersStoreWGSL[oGe]=lGe;const cGe={name:oGe,shader:lGe},Ubt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentSoftTransparentShadowWGSL:cGe},Symbol.toStringTag,{value:"Module"})),zbt="bayerDitherFunctions",Vbt=`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);} `;me.IncludesShadersStore[zbt]=Vbt;const Gbt="shadowMapFragmentExtraDeclaration",Wbt=`#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 `;me.IncludesShadersStore[Gbt]=Wbt;const uGe="shadowMapFragment",hGe=`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;`;me.IncludesShadersStore[uGe]=hGe;const dGe={name:uGe,shader:hGe},Kbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragment:dGe},Symbol.toStringTag,{value:"Module"})),fGe="shadowMapPixelShader",pGe=`#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 }`;me.ShadersStore[fGe]=pGe;const mGe={name:fGe,shader:pGe},Hbt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapPixelShader:mGe},Symbol.toStringTag,{value:"Module"})),jbt="sceneVertexDeclaration",$bt=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; `;me.IncludesShadersStore[jbt]=$bt;const Xbt="meshVertexDeclaration",Ybt=`uniform mat4 world;uniform float visibility; `;me.IncludesShadersStore[Xbt]=Ybt;const Qbt="shadowMapVertexDeclaration",Zbt=`#include #include `;me.IncludesShadersStore[Qbt]=Zbt;const qbt="sceneUboDeclaration",Jbt=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;}; `;me.IncludesShadersStore[qbt]=Jbt;const eCt="meshUboDeclaration",tCt=`#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO `;me.IncludesShadersStore[eCt]=tCt;const iCt="shadowMapUboDeclaration",rCt=`layout(std140,column_major) uniform; #include #include `;me.IncludesShadersStore[iCt]=rCt;const nCt="shadowMapVertexExtraDeclaration",sCt=`#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 `;me.IncludesShadersStore[nCt]=sCt;const aCt="shadowMapVertexNormalBias",oCt=`#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 `;me.IncludesShadersStore[aCt]=oCt;const gGe="shadowMapVertexMetric",_Ge=`#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 `;me.IncludesShadersStore[gGe]=_Ge;const vGe={name:gGe,shader:_Ge},lCt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexMetric:vGe},Symbol.toStringTag,{value:"Module"})),yGe="shadowMapVertexShader",xGe=`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 }`;me.ShadersStore[yGe]=xGe;const bGe={name:yGe,shader:xGe},cCt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapVertexShader:bGe},Symbol.toStringTag,{value:"Module"})),CGe="depthBoxBlurPixelShader",AGe=`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)));}`;me.ShadersStore[CGe]=AGe;const SGe={name:CGe,shader:AGe},uCt=Object.freeze(Object.defineProperty({__proto__:null,depthBoxBlurPixelShader:SGe},Symbol.toStringTag,{value:"Module"})),EGe="shadowMapFragmentSoftTransparentShadow",TGe=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard; #endif `;me.IncludesShadersStore[EGe]=TGe;const MGe={name:EGe,shader:TGe},hCt=Object.freeze(Object.defineProperty({__proto__:null,shadowMapFragmentSoftTransparentShadow:MGe},Symbol.toStringTag,{value:"Module"}));Dn.AddNodeConstructor("Light_Type_0",(r,e)=>()=>new bg(r,O.Zero(),e));class bg extends nb{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 n=i.next();n.done!==!0;n=i.next())n.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Dr.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new O(1,0,0);case 1:return new O(-1,0,0);case 2:return new O(0,-1,0);case 3:return new O(0,1,0);case 4:return new O(0,0,1);case 5:return new O(0,0,-1)}return O.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const s=this.shadowMinZ!==void 0?this.shadowMinZ:n.minZ,a=this.shadowMaxZ!==void 0?this.shadowMaxZ:n.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;pe.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:s,o?s: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}}V([Q()],bg.prototype,"shadowAngle",null);xe("BABYLON.PointLight",bg);class Lv{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const n=this._renderingCanvas.getBoundingClientRect(),s=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position=s==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=n.left+"px",this._loadingDiv.style.top=n.top+"px",this._loadingDiv.style.width=n.width+"px",this._loadingDiv.style.height=n.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;Lv.DefaultLogoUrl?i.src=Lv.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 n=document.createElement("div");n.style.width="300px",n.style.gridColumn="1",n.style.gridRow="1",n.style.top="50%",n.style.left="50%",n.style.transform="translate(-50%, -50%)",n.style.position="absolute";const s=new Image;if(Lv.DefaultSpinnerUrl?s.src=Lv.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.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)`,s.style.width=`${o.w}vh`,s.style.height=`${o.h}vh`,s.style.left=`calc(50% - ${o.w/2}vh)`,s.style.top=`calc(50% - ${o.h/2}vh)`}n.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(n),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)}}Lv.DefaultLogoUrl="";Lv.DefaultSpinnerUrl="";Qe.DefaultLoadingScreenFactory=r=>new Lv(r);class C3{static ConvertPanoramaToCubemap(e,t,i,n,s=!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(n,this.FACE_FRONT,e,t,i,s),o=this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i,s),l=this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i,s),c=this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i,s),u=this.CreateCubemapTexture(n,this.FACE_UP,e,t,i,s),h=this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i,s);return{front:a,back:o,left:l,right:c,up:u,down:h,size:n,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,n,s,a=!1){const o=new ArrayBuffer(e*e*4*3),l=new Float32Array(o),c=a?Math.max(1,Math.round(n/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 g=0;for(let m=0;mMath.PI;)s-=2*Math.PI;let o=s/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*n);u<0?u=0:u>=n&&(u=n-1);const h=n-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}}}C3.FACE_LEFT=[new O(-1,-1,-1),new O(1,-1,-1),new O(-1,1,-1),new O(1,1,-1)];C3.FACE_RIGHT=[new O(1,-1,1),new O(-1,-1,1),new O(1,1,1),new O(-1,1,1)];C3.FACE_FRONT=[new O(1,-1,-1),new O(1,-1,1),new O(1,1,-1),new O(1,1,1)];C3.FACE_BACK=[new O(-1,-1,1),new O(-1,-1,-1),new O(-1,1,1),new O(-1,1,-1)];C3.FACE_DOWN=[new O(1,1,-1),new O(1,1,1),new O(-1,1,-1),new O(-1,1,1)];C3.FACE_UP=[new O(-1,-1,-1),new O(-1,-1,1),new O(1,-1,-1),new O(1,-1,1)];function dCt(r,e){return e>1023?r*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?r*Math.pow(2,-1074)*Math.pow(2,e+1074):r*Math.pow(2,e)}function RGe(r,e,t,i,n,s){n>0?(n=dCt(1,n-136),r[s+0]=e*n,r[s+1]=t*n,r[s+2]=i*n):(r[s+0]=0,r[s+1]=0,r[s+2]=0)}function Mae(r,e){let t="",i="";for(let n=e;n32767)throw"HDR Bad header format, unsupported size";return a+=i.length+1,{height:e,width:t,dataPosition:a}}function IGe(r,e,t=!1){const i=new Uint8Array(r),n=k_e(i),s=U_e(i,n);return C3.ConvertPanoramaToCubemap(s,n.width,n.height,e,t)}function U_e(r,e){return fCt(r,e)}function fCt(r,e){let t=e.height;const i=e.width;let n,s,a,o,l,c=e.dataPosition,u=0,h=0,d=0;const f=new ArrayBuffer(i*4),p=new Uint8Array(f),g=new ArrayBuffer(e.width*e.height*4*3),m=new Float32Array(g);for(;t>0;){if(n=r[c++],s=r[c++],a=r[c++],o=r[c++],n!=2||s!=2||a&128||e.width<8||e.width>32767)return pCt(r,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=n-128,l==0||l>h-u)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[u++]=s}else{if(l=n,l==0||l>h-u)throw"HDR Bad Format, bad scanline data (non-run)";if(p[u++]=s,--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 `;me.IncludesShadersStore[CCt]=ACt;const SCt="hdrFilteringPixelShader",ECt=`#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);}`;me.ShadersStore[SCt]=ECt;class z_e{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=Xt.ILog2(t)+1,n=this._effectWrapper.effect,s=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 O(0,0,-1),new O(0,-1,0),new O(1,0,0)],[new O(0,0,1),new O(0,-1,0),new O(-1,0,0)],[new O(1,0,0),new O(0,0,1),new O(0,1,0)],[new O(1,0,0),new O(0,0,-1),new O(0,-1,0)],[new O(1,0,0),new O(0,-1,0),new O(0,0,1)],[new O(-1,0,0),new O(0,-1,0),new O(0,0,-1)]];n.setFloat("hdrScale",this.hdrScale),n.setFloat2("vFilteringInfo",e.getSize().width,i),n.setTexture("inputTexture",e);for(let u=0;u<6;u++){n.setVector3("up",o[u][0]),n.setVector3("right",o[u][1]),n.setVector3("front",o[u][2]);for(let h=0;h{this._effectRenderer=new aD(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(ge.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 Cg extends Cn{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(pe.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,n=!1,s=!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=O.Zero(),this.onLoadObservable=new Ce,e&&(this._coordinatesMode=be.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=pe.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=c,this.gammaSpace=a,this._noMipmap=n,this._size=i,this._supersample=u,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ie.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 n=s=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const a=IGe(s,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[Cg._FacesMapping[u]];if(this.gammaSpace||c||l){for(let d=0;d255){const _=255/m;f*=_,p*=_,g*=_}l[d*3+0]=f,l[d*3+1]=p,l[d*3+2]=g}}c?o.push(c):l?o.push(l):o.push(h)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const s=this._onLoad,a=new z_e(e);this._onLoad=()=>{a.prefilter(this,s)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,n,null,this._onLoad,this._onError)}clone(){const e=new Cg(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 n=null;return e.name&&!e.isRenderTarget&&(n=new Cg(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),n.name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=O.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=O.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n}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}}Cg._FacesMapping=["right","left","up","down","front","back"];xe("BABYLON.HDRCubeTexture",Cg);class xx{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 Ce,this._onDataLayoutChanged=new Ce,this._animationPropertiesOverride=null,this._scene=i||ei.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=ot.Clone(()=>new xx(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())),ot.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new xx(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 n=0;n0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Go(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=ei.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 L0.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 L0(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 n of this._targets){if(i++,n.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=L0.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(n),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=n.influence,this._supportsNormals=this._supportsNormals&&n.hasNormals,this._supportsTangents=this._supportsTangents&&n.hasTangents,this._supportsUVs=this._supportsUVs&&n.hasUVs;const s=n.getPositions();if(s){const a=s.length/3;if(this._vertexCount===0)this._vertexCount=a;else if(this._vertexCount!==a){ge.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 n=0;n0)){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,n=new Float32Array(i*this._textureWidth*this._textureHeight*4);let s=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 L0(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(xx.Parse(n,t));return i}}L0.EnableTextureStorage=!0;L0.MaxActiveMorphTargetsInVertexAttributeMode=8;class V_e{constructor(){this._hasHit=!1,this._hitNormal=O.Zero(),this._hitPoint=O.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 cV extends V_e{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=O.Zero(),this._rayToWorld=O.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=O.Distance(this._rayFromWorld,this._hitPoint)}reset(e=O.Zero(),t=O.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}let G_e=class PGe{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ji("CannonJSPlugin")}constructor(e,t=PGe.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 O(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 n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)}removeJoint(e,t,i){const n=this._joints.filter(function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e});n.length&&this._physicsPlugin.removeJoint(n[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 n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,n)}applyForce(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,n)}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){ge.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:n},a=e.getParam("nativeOptions");for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&(s[o]=a[o]);e.physicsBody=new this.BJSCANNON.Body(s),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 n=s=>{if(!s.rotationQuaternion)return;const a=s.getPhysicsImpostor();if(a&&a.parent!==e&&s.parent){const l=s.getAbsolutePosition().subtract(s.parent.getAbsolutePosition()),c=s.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")}s.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(n)};t.filter(s=>!!s.physicsImpostor).forEach(n)}}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 n;const s=e.joint.jointData,a={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case cs.HingeJoint:case cs.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,a);break;case cs.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case cs.SpringJoint:{const o=s;n=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break}case cs.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,a);break;case cs.PointToPointJoint:case cs.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,a.pivotA,i,a.pivotB,a.maxForce);break}n.collideConnected=!!s.collision,e.joint.physicsJoint=n,e.joint.type!==cs.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==cs.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let n,s;for(n=0;ni*1e3));d++);this.time+=n;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))}}G_e.DefaultPluginFactory=()=>new MZ;class fde{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=O.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new cV}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(n){n.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(n=>{n.afterStep(),this._tmpImpostorsArray[n.uniqueId]=n});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const n=this._tmpImpostorsArray[+i.body1.name],s=this._tmpImpostorsArray[+i.body2.name];if(!n||!s){i=i.next;continue}n.onCollide({body:s.physicsBody,point:null,distance:0,impulse:0,normal:null}),s.onCollide({body:n.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))}applyForce(e,t,i){ge.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 s=o=>Math.max(o,Ki),a=new Oe;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 Gi.ParticleImpostor:ge.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Gi.SphereImpostor:{const d=u.x,f=u.y,p=u.z,g=Math.max(s(d),s(f),s(p))/2;t.type.push("sphere"),t.size.push(g),t.size.push(g),t.size.push(g);break}case Gi.CylinderImpostor:{const d=s(u.x)/2,f=s(u.y);t.type.push("cylinder"),t.size.push(d),t.size.push(f),t.size.push(f);break}case Gi.PlaneImpostor:case Gi.BoxImpostor:default:{const d=s(u.x),f=s(u.y),p=s(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 n=e.joint.jointData,s=n.nativeParams||{};let a;const o={body1:t,body2:i,axe1:s.axe1||(n.mainAxis?n.mainAxis.asArray():null),axe2:s.axe2||(n.connectedAxis?n.connectedAxis.asArray():null),pos1:s.pos1||(n.mainPivot?n.mainPivot.asArray():null),pos2:s.pos2||(n.connectedPivot?n.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||n.collision,spring:s.spring,world:this.world};switch(e.joint.type){case cs.BallAndSocketJoint:a="jointBall";break;case cs.SpringJoint:{ge.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=n;o.min=l.length||o.min,o.max=Math.max(o.min,o.max)}case cs.DistanceJoint:a="jointDistance",o.max=n.maxDistance;break;case cs.PrismaticJoint:a="jointPrisme";break;case cs.SliderJoint:a="jointSlide";break;case cs.WheelJoint:a="jointWheel";break;case cs.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){ge.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 n=e.physicsBody;e.physicsBody.shapes.next||(n.position.set(t.x,t.y,t.z),n.orientation.set(i.x,i.y,i.z,i.w),n.syncShapes(),n.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 O(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new O(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,n){i!==void 0?ge.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,n){const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.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 ge.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){ge.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class ug{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 Oe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new O,this._tmpContactNormal=new O,this._tmpVec3=new O,this._tmpMatrix=new pe,typeof t=="function"){ge.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){ge.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=n=>{n=this.bjsAMMO.wrapPointer(n,this.bjsAMMO.btManifoldPoint);const s=n.getPositionWorldOnA(),a=n.m_normalWorldOnB;this._tmpContactPoint.x=s.x(),this._tmpContactPoint.y=s.y(),this._tmpContactPoint.z=s.z(),this._tmpContactNormal.x=a.x(),this._tmpContactNormal.y=a.y(),this._tmpContactNormal.z=a.z(),this._tmpContactImpulse=n.getAppliedImpulse(),this._tmpContactDistance=n.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new cV,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 n of i._onPhysicsCollideCallbacks)for(const s of n.otherImpostors)(i.physicsBody.isActive()||s.physicsBody.isActive())&&this._isImpostorPairInContact(i,s)&&(i.onCollide({body:s.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),s.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===Gi.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let n,s,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 n=e.joint.jointData;n.mainPivot||(n.mainPivot=new O(0,0,0)),n.connectedPivot||(n.connectedPivot=new O(0,0,0));let s;switch(e.joint.type){case cs.DistanceJoint:{const a=n.maxDistance;a&&(n.mainPivot=new O(0,-a/2,0),n.connectedPivot=new O(0,a/2,0));const o=this._tmpAmmoVectorA;o.setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z);const l=this._tmpAmmoVectorB;l.setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,o,l);break}case cs.HingeJoint:{n.mainAxis||(n.mainAxis=new O(0,0,0)),n.connectedAxis||(n.connectedAxis=new O(0,0,0));const a=this._tmpAmmoVectorA;a.setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z);const l=this._tmpAmmoVectorC;l.setValue(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z);const c=this._tmpAmmoVectorD;c.setValue(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z),s=new this.bjsAMMO.btHingeConstraint(t,i,a,o,l,c);break}case cs.BallAndSocketJoint:{const a=this._tmpAmmoVectorA;a.setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,a,o);break}default:{ge.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const a=this._tmpAmmoVectorA;a.setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,a,o);break}}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(ee.PositionKind);a||(a=[]);let o;if(t&&t!==i){let c;t.rotationQuaternion?c=t.rotationQuaternion:t.rotation?c=Oe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):c=Oe.Identity(),pe.Compose(O.One(),c,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else pe.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const l=s.length/3;for(let c=0;c{n+=this._addMeshVerts(e,t,c)})}return n}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData(ee.PositionKind);i||(i=[]);let n=t.getVerticesData(ee.NormalKind);n||(n=[]),t.computeWorldMatrix(!1);const s=[],a=[];for(let l=0;ld*d),l=(d,f)=>d+f;if(o.reduce(l)===0)t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const d=e.getParam("path");if(e.getParam("shape")===null)return ge.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 n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(ee.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);const o=s.length/3;for(let l=0;l{n+=this._addHullVerts(e,t,l)})}return n}_createShape(e,t=!1){const i=e.object;let n;const s=e.getObjectExtents();if(!t){const a=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];n=new this.bjsAMMO.btCompoundShape;let o=0;if(a.forEach(l=>{const c=l.getPhysicsImpostor();if(c){if(c.type==Gi.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 O;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),n.addChildShape(this._tmpAmmoTransform,u),c.dispose(),o++}}),o>0){if(e.type!=Gi.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),n.addChildShape(this._tmpAmmoTransform,l))}return n}else this.bjsAMMO.destroy(n),n=null}switch(e.type){case Gi.SphereImpostor:if(Xt.WithinEpsilon(s.x,s.y,1e-4)&&Xt.WithinEpsilon(s.x,s.z,1e-4))n=new this.bjsAMMO.btSphereShape(s.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const a=[this._tmpAmmoVectorA],o=[1];n=new this.bjsAMMO.btMultiSphereShape(a,o,1),this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n.setLocalScaling(this._tmpAmmoVectorA)}break;case Gi.CapsuleImpostor:{const a=s.x/2;n=new this.bjsAMMO.btCapsuleShape(a,s.y-a*2)}break;case Gi.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Gi.PlaneImpostor:case Gi.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Gi.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)n=this.onCreateCustomMeshImpostor(e);else{const a=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(a),this._addMeshVerts(a,i,i)==0?n=new this.bjsAMMO.btCompoundShape:n=new this.bjsAMMO.btBvhTriangleMeshShape(a)}break}case Gi.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)n=this.onCreateCustomConvexHullImpostor(e);else{const a=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(a,i,i)==0?(e._pluginData.toDispose.push(a),n=new this.bjsAMMO.btCompoundShape):n=a}break}case Gi.NoImpostor:n=new this.bjsAMMO.btSphereShape(s.x/2);break;case Gi.CustomImpostor:n=this._createCustom(e);break;case Gi.SoftbodyImpostor:n=this._createSoftbody(e);break;case Gi.ClothImpostor:n=this._createCloth(e);break;case Gi.RopeImpostor:n=this._createRope(e);break;default:ge.Warn("The impostor type is not currently supported by the ammo plugin.");break}return n}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 n=e.physicsBody.getWorldTransform();if(Math.abs(n.getOrigin().x()-t.x)>Ki||Math.abs(n.getOrigin().y()-t.y)>Ki||Math.abs(n.getOrigin().z()-t.z)>Ki||Math.abs(n.getRotation().x()-i.x)>Ki||Math.abs(n.getRotation().y()-i.y)>Ki||Math.abs(n.getRotation().z()-i.z)>Ki||Math.abs(n.getRotation().w()-i.w)>Ki)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),e.mass==0){const s=e.physicsBody.getMotionState();s&&s.setWorldTransform(n)}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 O(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 O(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:(ge.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===Gi.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):ge.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(ge.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):ge.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(ge.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):ge.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(ge.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):ge.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,n,s=1,a=!1){const o=e.segments,l=Math.round((o-1)*i),c=Math.round((o-1)*n),u=o-1-c,h=l+o*u;e.physicsBody.appendAnchor(h,t.physicsBody,a,s)}appendHook(e,t,i,n=1,s=!1){const a=Math.round(e.segments*i);e.physicsBody.appendAnchor(a,t.physicsBody,s,n)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){ge.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){ge.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 n=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,n),i.reset(e,t),n.hasHit()&&(i.setHitData({x:n.get_m_hitNormalWorld().x(),y:n.get_m_hitNormalWorld().y(),z:n.get_m_hitNormalWorld().z()},{x:n.get_m_hitPointWorld().x(),y:n.get_m_hitPointWorld().y(),z:n.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(n),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}ug._DISABLE_COLLISION_FLAG=4;ug._KINEMATIC_FLAG=2;ug._DISABLE_DEACTIVATION_FLAG=4;vo.prototype.removeReflectionProbe=function(r){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(r);return e!==-1&&this.reflectionProbes.splice(e,1),e};vo.prototype.addReflectionProbe=function(r){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(r)};class cT{constructor(e,t,i,n=!0,s=!1,a=!1){if(this.name=e,this._viewMatrix=pe.Identity(),this._target=O.Zero(),this._add=O.Zero(),this._invertYAxis=!1,this.position=O.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(s){const u=this._scene.getEngine().getCaps();u.textureHalfFloatRender?o=2:u.textureFloatRender&&(o=1)}this._renderTargetTexture=new vn(e,t,i,n,!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?pe.LookAtRHToRef:pe.LookAtLHToRef,d=i.useRightHandedSystem?pe.PerspectiveFovRH:pe.PerspectiveFovLH;h(this.position,this._target,O.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=ot.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let n=null;if(t.reflectionProbes)for(let s=0;sn||new cT(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),n.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&n.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(n.metadata=e.metadata),n}}V([Qw()],cT.prototype,"_attachedMesh",void 0);V([ta()],cT.prototype,"position",void 0);class TCt{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,n,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,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 Lee extends TCt{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 Ce,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new at(1,1,1,1),this.position=O.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,n,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,n,this._endAnimation)}dispose(){for(let e=0;e0)for(let s=0;s=n.distance)&&(n=o,t))break}return n||new wl};Ut.prototype._internalMultiPickSprites=function(r,e,t){if(!wl)return null;let i=[];if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let n=0;nt.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(bt.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(bt.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(bt.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,n,s){const a=this.scene.pickSprite(t,i,this._spritePredicate,n,s);return a&&(a.ray=e?e.ray:null),a}_pointerMove(e,t,i,n,s){const a=this.scene;return n?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&&s&&(a._pointerOverSprite&&a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor)):a.setPointerOverSprite(null)),i}_pointerDown(e,t,i,n){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(s._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Ca.CreateNewFromSprite(i.pickedSprite,s,n));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Ca.CreateNewFromSprite(i.pickedSprite,s,n));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Ca.CreateNewFromSprite(i.pickedSprite,s,n));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Ca.CreateNewFromSprite(i.pickedSprite,s,n))}return i}_pointerUp(e,t,i,n,s){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,Ca.CreateNewFromSprite(o.pickedSprite,a,n)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,Ca.CreateNewFromSprite(o.pickedSprite,a,n)),s&&o.pickedSprite.actionManager.processTrigger(6,Ca.CreateNewFromSprite(o.pickedSprite,a,n)))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==o.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(16,Ca.CreateNewFromSprite(a._pickedDownSprite,a,n)))}return i}}class Nee{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&&ge.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,n=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=n,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new fl(e,this._vertexData,!0,this._vertexBufferSize);const s=this._buffer.createVertexBuffer(ee.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 fl(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(ee.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ee.PositionKind]=s,this._vertexBuffers.options=a,this._vertexBuffers.offsets=l,this._vertexBuffers.inverts=c,this._vertexBuffers.cellInfo=u,this._vertexBuffers[ee.ColorKind]=h,this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._engine.isWebGPU&&!Nee.ForceGLSL?(this._shaderLanguage=1,await Promise.all([je(()=>Promise.resolve().then(()=>vDt),void 0),je(()=>Promise.resolve().then(()=>_Dt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>pDt),void 0),je(()=>Promise.resolve().then(()=>fDt),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 pl(this._engine),this._drawWrapperDepth=new pl(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",[ee.PositionKind,"options","offsets","inverts","cellInfo",ee.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,n,s=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,g=!0;for(let v=0;v>0;t._xOffset=(t.cellIndex-u*c)*this.cellWidth/s.width,t._yOffset=u*this.cellHeight/s.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]=n),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/s.width,this._vertexData[l+13]=t._ySize/s.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},s||(s=ei.LastCreatedScene),s._getComponent(bt.NAME_SPRITE)||s._addComponent(new wGe(s)),this._fromPacked=l,this._scene=s;const u=this._scene.getEngine();if(this._spriteRenderer=new Nee(u,i,a,s),n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else if(n!==void 0)this.cellWidth=n,this.cellHeight=n;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new be(t,s,!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 s={};for(let a=0;a0);const s=e.substring(0,n-1)+".json",a=()=>{ge.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.")}};Ie.LoadFile(s,o,void 0,void 0,!1,a)}}_checkTextureAlpha(e,t,i,n,s){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=oe.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const l=(o.x-n.x)/(s.x-n.x),c=1-(o.y-n.y)/(s.y-n.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,n){const s=Math.min(this.capacity,this.sprites.length),a=O.Zero(),o=O.Zero();let l=Number.MAX_VALUE,c=null;const u=oe.Vector3[0],h=oe.Vector3[1],d=t.getViewMatrix();let f=e,p=e;for(let g=0;g_){if(!this._checkTextureAlpha(m,f,_,a,o))continue;if(p=f,l=_,c=m,n)break}}}}if(c){const g=new wl;d.invertToRef(oe.Matrix[0]),g.hit=!0,g.pickedSprite=c,g.distance=l;const m=oe.Vector3[2];return m.copyFrom(p.direction),m.normalize(),m.scaleInPlace(l),p.origin.addToRef(m,u),g.pickedPoint=O.TransformCoordinates(u,oe.Matrix[0]),g}return null}multiIntersects(e,t,i){const n=Math.min(this.capacity,this.sprites.length),s=O.Zero(),a=O.Zero();let o;const l=[],c=oe.Vector3[0].copyFromFloats(0,0,0),u=oe.Vector3[1].copyFromFloats(0,0,0),h=t.getViewMatrix();for(let d=0;d{const o=new oa;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),c=hg.Parse(l,i||ei.LastCreatedScene,n);e&&(c.name=e),s(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 hg("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((n,s)=>{const a=new oa;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=hg.Parse(l,t||ei.LastCreatedScene,i);c.snippetId=e,n(c)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}hg.SnippetUrl="https://snippet.babylonjs.com";hg.CreateFromSnippetAsync=hg.ParseFromSnippetAsync;var MCt=!0;class ek{}ek.LoaderInjectedPhysicsEngine=void 0;let vP={},rx={};const aRe=(r,e,t,i)=>{if(!e.materials)return null;for(let n=0,s=e.materials.length;n{for(const i in e)if(r.name===e[i])return t.push(r.id),!0;return r.parentId!==void 0&&t.indexOf(r.parentId)!==-1?(t.push(r.id),!0):!1},MP=(r,e)=>r+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),DGe=(r,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,n=t.isEnabled(!1);if(e._waitingData.lods.distances){const s=e._waitingData.lods.distances;if(s.length>=i.length){const a=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let o=0;o0&&t.addLODLevel(a,null),n===!0&&t.setEnabled(!0)}else Ie.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},vX=(r,e,t)=>{if(typeof r!="number"){const n=t.getLastEntryById(r);return n&&e!==void 0&&e!==null?n.instances[parseInt(e)]:n}const i=vP[r];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},RZ=(r,e)=>typeof r!="number"?e.getLastMaterialById(r,!0):rx[r],oRe=(r,e,t,i,n=!1)=>{const s=new Lz(r);let a="importScene has failed JSON parse";try{var o=JSON.parse(e);a="";const l=bs.loggingLevel===bs.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 Cg((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,r,f,!0,!d,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(p.rotationY=o.environmentTextureRotationY),r.environmentTexture=p}else if(typeof o.environmentTexture=="object"){const f=Za.Parse(o.environmentTexture,r,t);r.environmentTexture=f}else if(o.environmentTexture.endsWith(".env")){const f=new Za((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,r,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),r.environmentTexture=f}else{const f=Za.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,r,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),r.environmentTexture=f}if(o.createDefaultSkybox===!0){const f=r.activeCamera!==void 0&&r.activeCamera!==null?(r.activeCamera.maxZ-r.activeCamera.minZ)/2:1e3,p=o.skyboxBlurLevel||0;r.createDefaultSkybox(r.environmentTexture,d,f,p)}s.environmentTexture=r.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(r.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(c=0,u=o.lights.length;c{s.textures.indexOf(g)==-1&&(s.textures.push(g),g._parentContainer=s)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(c=0,u=o.multiMaterials.length;c{s.textures.indexOf(g)==-1&&(s.textures.push(g),g._parentContainer=s)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const d of o.morphTargetManagers){const f=L0.Parse(d,r);s.morphTargetManagers.push(f),f._parentContainer=s}if(o.skeletons!==void 0&&o.skeletons!==null)for(c=0,u=o.skeletons.length;c{p&&(s.geometries.push(p),p._parentContainer=s)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(c=0,u=o.transformNodes.length;c{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(RZ(f,r))}),d._waitingSubMaterialsUniqueIds=[]}),r.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=RZ(d._waitingMaterialId,r),d._waitingMaterialId=null)}),c=0,u=r.skeletons.length;c{if(f._waitingTransformNodeId){const p=r.getLastEntryById(f._waitingTransformNodeId);p&&f.linkTransformNode(p),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(c=0,u=r.meshes.length;c0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),vo.Parse(o,r,s,t),c=0,u=r.meshes.length;cr.indexOf("babylon")!==-1,importMesh:(r,e,t,i,n,s,a,o)=>{var u;let l="importMesh has failed JSON parse";try{var c=JSON.parse(t);l="";const h=bs.loggingLevel===bs.DETAILED_LOGGING;r?Array.isArray(r)||(r=[r]):r=null;const d=[],f=new Map,p=[];if(c.transformNodes!==void 0&&c.transformNodes!==null)for(let g=0,m=c.transformNodes.length;g{E===!0||!c.geometries[P]||!Array.isArray(c.geometries[P])||c.geometries[P].forEach(w=>{if(w.id===C.geometryId){switch(P){case"vertexData":ul.Parse(w,e,i);break}E=!0}})}),E===!1&&ge.Warn("Geometry not found for mesh "+C.id)}if(C.materialUniqueId||C.materialId){const E=C.materialUniqueId?_:m;let P=E.indexOf(C.materialUniqueId||C.materialId)!==-1;if(P===!1&&c.multiMaterials!==void 0&&c.multiMaterials!==null){const w=(M,R)=>{E.push(M);const I=aRe(R,c,e,i);I&&I.material&&(rx[I.parsedMaterial.uniqueId||I.parsedMaterial.id]=I.material,l+=` Material `+I.material.toString(h))};for(let M=0,R=c.multiMaterials.length;Mw(k,z=>z.uniqueId===k)):I.materials.forEach(k=>w(k,z=>z.id===k)),E.push(I.uniqueId||I.id);const D=Tf.ParseMultiMaterial(I,e);rx[I.uniqueId||I.id]=D,D&&(P=!0,l+=` Multi-Material `+D.toString(h));break}}}if(P===!1){E.push(C.materialUniqueId||C.materialId);const w=aRe(M=>C.materialUniqueId&&M.uniqueId===C.materialUniqueId||M.id===C.materialId,c,e,i);!w||!w.material?ge.Warn("Material not found for mesh "+C.id):(rx[w.parsedMaterial.uniqueId||w.parsedMaterial.id]=w.material,l+=` Material `+w.material.toString(h))}}if(C.skeletonId!==null&&C.skeletonId!==void 0&&c.skeletonId!==-1&&c.skeletons!==void 0&&c.skeletons!==null&&!(g.indexOf(C.skeletonId)>-1))for(let P=0,w=c.skeletons.length;P-1&&c.morphTargetManagers!==void 0&&c.morphTargetManagers!==null&&!(y.indexOf(C.morphTargetManagerId)>-1))for(let P=0,w=c.morphTargetManagers.length;P{x._waitingSubMaterialsUniqueIds.forEach(b=>{x.subMaterials.push(RZ(b,e))}),x._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(x=>{x._waitingMaterialId!==null&&(x.material=RZ(x._waitingMaterialId,e),x._waitingMaterialId=null)});for(let x=0,b=e.transformNodes.length;x-1&&p.splice(E,1)}v._waitingParentId=null}v._waitingData.lods&&DGe(e,v)}for(const x of p)x.dispose();for(let x=0,b=e.skeletons.length;x{if(A._waitingTransformNodeId){const E=e.getLastEntryById(A._waitingTransformNodeId);E&&A.linkTransformNode(E),A._waitingTransformNodeId=null}}),C._hasWaitingData=null)}for(let x=0,b=e.meshes.length;x{g._loadedUniqueId=""}),!0}catch(h){const d=MP("importMesh",c?c.producer:"Unknown")+l;if(o)o(d,h);else throw ge.Log(d),h}finally{l!==null&&bs.loggingLevel!==bs.NO_LOGGING&&ge.Log(MP("importMesh",c?c.producer:"Unknown")+(bs.loggingLevel!==bs.MINIMAL_LOGGING?l:"")),rx={}}return!1},load:(r,e,t,i)=>{let n="importScene has failed JSON parse";try{var s=JSON.parse(e);switch(n="",s.useDelayedTextureLoading!==void 0&&s.useDelayedTextureLoading!==null&&(r.useDelayedTextureLoading=s.useDelayedTextureLoading&&!bs.ForceFullSceneLoadingForIncremental),s.autoClear!==void 0&&s.autoClear!==null&&(r.autoClear=s.autoClear),s.clearColor!==void 0&&s.clearColor!==null&&(r.clearColor=at.FromArray(s.clearColor)),s.ambientColor!==void 0&&s.ambientColor!==null&&(r.ambientColor=Pe.FromArray(s.ambientColor)),s.gravity!==void 0&&s.gravity!==null&&(r.gravity=O.FromArray(s.gravity)),s.useRightHandedSystem!==void 0&&(r.useRightHandedSystem=!!s.useRightHandedSystem),s.fogMode!==void 0&&s.fogMode!==null&&(r.fogMode=s.fogMode),s.fogColor!==void 0&&s.fogColor!==null&&(r.fogColor=Pe.FromArray(s.fogColor)),s.fogStart!==void 0&&s.fogStart!==null&&(r.fogStart=s.fogStart),s.fogEnd!==void 0&&s.fogEnd!==null&&(r.fogEnd=s.fogEnd),s.fogDensity!==void 0&&s.fogDensity!==null&&(r.fogDensity=s.fogDensity),n+=" Fog mode for scene: ",r.fogMode){case 0:n+=`none `;break;case 1:n+=`exp `;break;case 2:n+=`exp2 `;break;case 3:n+=`linear `;break}if(s.physicsEnabled){let o;s.physicsEngine==="cannon"||s.physicsEngine===MZ.name?o=new MZ(void 0,void 0,ek.LoaderInjectedPhysicsEngine):s.physicsEngine==="oimo"||s.physicsEngine===fde.name?o=new fde(void 0,ek.LoaderInjectedPhysicsEngine):(s.physicsEngine==="ammo"||s.physicsEngine===ug.name)&&(o=new ug(void 0,ek.LoaderInjectedPhysicsEngine,void 0)),n=" Physics engine "+(s.physicsEngine?s.physicsEngine:"oimo")+` enabled `;const l=s.gravity?O.FromArray(s.gravity):s.physicsGravity?O.FromArray(s.physicsGravity):null;r.enablePhysics(l,o)}return s.metadata!==void 0&&s.metadata!==null&&(r.metadata=s.metadata),s.collisionsEnabled!==void 0&&s.collisionsEnabled!==null&&(r.collisionsEnabled=s.collisionsEnabled),oRe(r,e,t,i,!0)?(s.autoAnimate&&r.beginAnimation(r,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1),s.activeCameraID!==void 0&&s.activeCameraID!==null&&r.setActiveCameraById(s.activeCameraID),!0):!1}catch(a){const o=MP("importScene",s?s.producer:"Unknown")+n;if(i)i(o,a);else throw ge.Log(o),a}finally{n!==null&&bs.loggingLevel!==bs.NO_LOGGING&&ge.Log(MP("importScene",s?s.producer:"Unknown")+(bs.loggingLevel!==bs.MINIMAL_LOGGING?n:""))}return!1},loadAssetContainer:(r,e,t,i)=>oRe(r,e,t,i)});const ICt="backgroundUboDeclaration",PCt=`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 `;me.IncludesShadersStoreWGSL[ICt]=PCt;const wCt="fogVertexDeclaration",DCt=`#ifdef FOG varying vFogDistance: vec3f; #endif `;me.IncludesShadersStoreWGSL[wCt]=DCt;const OGe="lightVxUboDeclaration",LGe=`#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 `;me.IncludesShadersStoreWGSL[OGe]=LGe;const NGe={name:OGe,shader:LGe},OCt=Object.freeze(Object.defineProperty({__proto__:null,lightVxUboDeclarationWGSL:NGe},Symbol.toStringTag,{value:"Module"})),LCt="logDepthDeclaration",NCt=`#ifdef LOGARITHMICDEPTH uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32; #endif `;me.IncludesShadersStoreWGSL[LCt]=NCt;const FCt="fogVertex",BCt=`#ifdef FOG vertexOutputs.vFogDistance=(scene.view*worldPos).xyz; #endif `;me.IncludesShadersStoreWGSL[FCt]=BCt;const FGe="shadowsVertex",BGe=`#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 `;me.IncludesShadersStoreWGSL[FGe]=BGe;const kGe={name:FGe,shader:BGe},kCt=Object.freeze(Object.defineProperty({__proto__:null,shadowsVertexWGSL:kGe},Symbol.toStringTag,{value:"Module"})),UCt="logDepthVertex",zCt=`#ifdef LOGARITHMICDEPTH vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant; #endif `;me.IncludesShadersStoreWGSL[UCt]=zCt;const UGe="backgroundVertexShader",zGe=`#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 } `;me.ShadersStoreWGSL[UGe]=zGe;const VGe={name:UGe,shader:zGe},VCt=Object.freeze(Object.defineProperty({__proto__:null,backgroundVertexShaderWGSL:VGe},Symbol.toStringTag,{value:"Module"})),GGe="reflectionFunction",WGe=`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 `;me.IncludesShadersStoreWGSL[GGe]=WGe;const KGe={name:GGe,shader:WGe},GCt=Object.freeze(Object.defineProperty({__proto__:null,reflectionFunctionWGSL:KGe},Symbol.toStringTag,{value:"Module"})),HGe="imageProcessingDeclaration",jGe=`#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 `;me.IncludesShadersStoreWGSL[HGe]=jGe;const $Ge={name:HGe,shader:jGe},WCt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclarationWGSL:$Ge},Symbol.toStringTag,{value:"Module"})),XGe="lightUboDeclaration",YGe=`#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 `;me.IncludesShadersStoreWGSL[XGe]=YGe;const QGe={name:XGe,shader:YGe},KCt=Object.freeze(Object.defineProperty({__proto__:null,lightUboDeclarationWGSL:QGe},Symbol.toStringTag,{value:"Module"})),ZGe="lightsFragmentFunctions",qGe=`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;}`;me.IncludesShadersStoreWGSL[ZGe]=qGe;const JGe={name:ZGe,shader:qGe},HCt=Object.freeze(Object.defineProperty({__proto__:null,lightsFragmentFunctionsWGSL:JGe},Symbol.toStringTag,{value:"Module"})),eWe="shadowsFragmentFunctions",tWe=`#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 `;me.IncludesShadersStoreWGSL[eWe]=tWe;const iWe={name:eWe,shader:tWe},jCt=Object.freeze(Object.defineProperty({__proto__:null,shadowsFragmentFunctionsWGSL:iWe},Symbol.toStringTag,{value:"Module"})),rWe="imageProcessingFunctions",nWe=`#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);}`;me.IncludesShadersStoreWGSL[rWe]=nWe;const sWe={name:rWe,shader:nWe},$Ct=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingFunctionsWGSL:sWe},Symbol.toStringTag,{value:"Module"})),aWe="fogFragmentDeclaration",oWe=`#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 `;me.IncludesShadersStoreWGSL[aWe]=oWe;const lWe={name:aWe,shader:oWe},XCt=Object.freeze(Object.defineProperty({__proto__:null,fogFragmentDeclarationWGSL:lWe},Symbol.toStringTag,{value:"Module"})),cWe="lightFragment",uWe=`#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 `;me.IncludesShadersStoreWGSL[cWe]=uWe;const hWe={name:cWe,shader:uWe},YCt=Object.freeze(Object.defineProperty({__proto__:null,lightFragmentWGSL:hWe},Symbol.toStringTag,{value:"Module"})),QCt="logDepthFragment",ZCt=`#ifdef LOGARITHMICDEPTH fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5; #endif `;me.IncludesShadersStoreWGSL[QCt]=ZCt;const qCt="fogFragment",JCt=`#ifdef FOG var fog: f32=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a); #endif `;me.IncludesShadersStoreWGSL[qCt]=JCt;const dWe="backgroundPixelShader",fWe=`#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 } `;me.ShadersStoreWGSL[dWe]=fWe;const pWe={name:dWe,shader:fWe},eAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundPixelShaderWGSL:pWe},Symbol.toStringTag,{value:"Module"})),tAt="backgroundVertexDeclaration",iAt=`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 `;me.IncludesShadersStore[tAt]=iAt;const rAt="backgroundUboDeclaration",nAt=`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 `;me.IncludesShadersStore[rAt]=nAt;const sAt="fogVertexDeclaration",aAt=`#ifdef FOG varying vec3 vFogDistance; #endif `;me.IncludesShadersStore[sAt]=aAt;const mWe="lightVxFragmentDeclaration",gWe=`#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 `;me.IncludesShadersStore[mWe]=gWe;const _We={name:mWe,shader:gWe},oAt=Object.freeze(Object.defineProperty({__proto__:null,lightVxFragmentDeclaration:_We},Symbol.toStringTag,{value:"Module"})),vWe="lightVxUboDeclaration",yWe=`#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 `;me.IncludesShadersStore[vWe]=yWe;const xWe={name:vWe,shader:yWe},lAt=Object.freeze(Object.defineProperty({__proto__:null,lightVxUboDeclaration:xWe},Symbol.toStringTag,{value:"Module"})),cAt="logDepthDeclaration",uAt=`#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif `;me.IncludesShadersStore[cAt]=uAt;const hAt="fogVertex",dAt=`#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif `;me.IncludesShadersStore[hAt]=dAt;const bWe="shadowsVertex",CWe=`#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 } `;me.ShadersStore[SWe]=EWe;const TWe={name:SWe,shader:EWe},gAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundVertexShader:TWe},Symbol.toStringTag,{value:"Module"})),_At="backgroundFragmentDeclaration",vAt=`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 `;me.IncludesShadersStore[_At]=vAt;const MWe="reflectionFunction",RWe=`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 `;me.IncludesShadersStore[MWe]=RWe;const IWe={name:MWe,shader:RWe},yAt=Object.freeze(Object.defineProperty({__proto__:null,reflectionFunction:IWe},Symbol.toStringTag,{value:"Module"})),PWe="imageProcessingDeclaration",wWe=`#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 `;me.IncludesShadersStore[PWe]=wWe;const DWe={name:PWe,shader:wWe},xAt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingDeclaration:DWe},Symbol.toStringTag,{value:"Module"})),OWe="lightFragmentDeclaration",LWe=`#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 `;me.IncludesShadersStore[OWe]=LWe;const NWe={name:OWe,shader:LWe},bAt=Object.freeze(Object.defineProperty({__proto__:null,lightFragmentDeclaration:NWe},Symbol.toStringTag,{value:"Module"})),FWe="lightUboDeclaration",BWe=`#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 `;me.IncludesShadersStore[FWe]=BWe;const kWe={name:FWe,shader:BWe},CAt=Object.freeze(Object.defineProperty({__proto__:null,lightUboDeclaration:kWe},Symbol.toStringTag,{value:"Module"})),UWe="lightsFragmentFunctions",zWe=`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;}`;me.IncludesShadersStore[UWe]=zWe;const VWe={name:UWe,shader:zWe},AAt=Object.freeze(Object.defineProperty({__proto__:null,lightsFragmentFunctions:VWe},Symbol.toStringTag,{value:"Module"})),GWe="shadowsFragmentFunctions",WWe=`#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 `;me.IncludesShadersStore[ZWe]=qWe;const JWe={name:ZWe,shader:qWe},MAt=Object.freeze(Object.defineProperty({__proto__:null,lightFragment:JWe},Symbol.toStringTag,{value:"Module"})),RAt="logDepthFragment",IAt=`#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif `;me.IncludesShadersStore[RAt]=IAt;const PAt="fogFragment",wAt=`#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif `;me.IncludesShadersStore[PAt]=wAt;const eKe="backgroundPixelShader",tKe=`#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 } `;me.ShadersStore[eKe]=tKe;const iKe={name:eKe,shader:tKe},DAt=Object.freeze(Object.defineProperty({__proto__:null,backgroundPixelShader:iKe},Symbol.toStringTag,{value:"Module"}));class eU{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Qe.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||Pe.White(),this.rightColor=e.rightColor||Pe.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new eU;return bc.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 eU({isEnabled:e.isEnabled,leftColor:Pe.FromArray(e.leftColor),rightColor:Pe.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}ot._FresnelParametersParser=eU.Parse;class ia{}ia.BindSceneUniformBuffer=tD;ia.PrepareDefinesForMergedUV=Is;ia.BindTextureMatrix=Ps;ia.GetFogState=WJ;ia.PrepareDefinesForMisc=Tu;ia.PrepareDefinesForCamera=$J;ia.PrepareDefinesForFrameBoundValues=Mu;ia.PrepareDefinesForBones=KJ;ia.PrepareDefinesForMorphTargets=HJ;ia.PrepareDefinesForBakedVertexAnimation=y1e;ia.PrepareDefinesForAttributes=xo;ia.PrepareDefinesForMultiview=rD;ia.PrepareDefinesForOIT=jJ;ia.PrepareDefinesForPrePass=Dz;ia.PrepareDefinesForLight=wz;ia.PrepareDefinesForLights=Xu;ia.PrepareUniformsAndSamplersForLight=Oz;ia.PrepareUniformsAndSamplersList=Qo;ia.HandleFallbacksForShadows=Bl;ia.PrepareAttributesForMorphTargetsInfluencers=tb;ia.PrepareAttributesForMorphTargets=Iz;ia.PrepareAttributesForBakedVertexAnimation=iD;ia.PrepareAttributesForBones=Ch;ia.PrepareAttributesForInstances=Do;ia.PushAttributesForInstances=k_;ia.BindLightProperties=r9e;ia.BindLight=Pz;ia.BindLights=$u;ia.BindFogParameters=ic;ia.BindBonesParameters=rc;ia.BindMorphTargetParameters=Np;ia.BindLogDepth=Xo;const rKe="colorPixelShader",nKe=`#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 }`;me.ShadersStore[rKe]=nKe;const sKe={name:rKe,shader:nKe},OAt=Object.freeze(Object.defineProperty({__proto__:null,colorPixelShader:sKe},Symbol.toStringTag,{value:"Module"})),LAt="vertexColorMixing",NAt=`#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 `;me.IncludesShadersStore[LAt]=NAt;const aKe="colorVertexShader",oKe=`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 }`;me.ShadersStore[aKe]=oKe;const lKe={name:aKe,shader:oKe},FAt=Object.freeze(Object.defineProperty({__proto__:null,colorVertexShader:lKe},Symbol.toStringTag,{value:"Module"}));class BAt extends ua{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new at(0,0,0,1))}}class Ah extends an{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 Pe(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}V([Q(),Ke("_markAllSubMeshesAsLightsDirty")],Ah.prototype,"maxSimultaneousLights",void 0);V([Q(),Ke("_markAllSubMeshesAsLightsDirty")],Ah.prototype,"disableLighting",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Ah.prototype,"environmentTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"invertNormalMapX",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"invertNormalMapY",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Ah.prototype,"normalTexture",void 0);V([qr("emissive"),Ke("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"emissiveColor",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"emissiveTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Ah.prototype,"occlusionStrength",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Ah.prototype,"occlusionTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Ah.prototype,"alphaCutOff",void 0);V([Q()],Ah.prototype,"doubleSided",null);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty",null)],Ah.prototype,"lightmapTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"useLightmapAsShadowmap",void 0);class P_ extends Ah{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=ot.Clone(()=>new P_(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=ot.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 n=ot.Parse(()=>new P_(e.name,t),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}V([qr(),Ke("_markAllSubMeshesAsTexturesDirty","_albedoColor")],P_.prototype,"baseColor",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],P_.prototype,"baseTexture",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],P_.prototype,"metallic",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],P_.prototype,"roughness",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],P_.prototype,"metallicRoughnessTexture",void 0);xe("BABYLON.PBRMetallicRoughnessMaterial",P_);class w_ extends Ah{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=ot.Clone(()=>new w_(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=ot.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 n=ot.Parse(()=>new w_(e.name,t),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}V([qr("diffuse"),Ke("_markAllSubMeshesAsTexturesDirty","_albedoColor")],w_.prototype,"diffuseColor",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],w_.prototype,"diffuseTexture",void 0);V([qr("specular"),Ke("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],w_.prototype,"specularColor",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty","_microSurface")],w_.prototype,"glossiness",void 0);V([ki(),Ke("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],w_.prototype,"specularGlossinessTexture",void 0);xe("BABYLON.PBRSpecularGlossinessMaterial",w_);const kAt="pbrUboDeclaration",UAt=`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 `;me.IncludesShadersStoreWGSL[kAt]=UAt;const zAt="uvAttributeDeclaration",VAt=`#ifdef UV{X} attribute uv{X}: vec2f; #endif `;me.IncludesShadersStoreWGSL[zAt]=VAt;const GAt="mainUVVaryingDeclaration",WAt=`#ifdef MAINUV{X} varying vMainUV{X}: vec2f; #endif `;me.IncludesShadersStoreWGSL[GAt]=WAt;const KAt="prePassVertexDeclaration",HAt=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `;me.IncludesShadersStoreWGSL[KAt]=HAt;const jAt="samplerVertexDeclaration",$At=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying v_VARYINGNAME_UV: vec2f; #endif `;me.IncludesShadersStoreWGSL[jAt]=$At;const XAt="harmonicsFunctions",YAt=`#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 `;me.IncludesShadersStoreWGSL[XAt]=YAt;const QAt="bumpVertexDeclaration",ZAt=`#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 `;me.IncludesShadersStoreWGSL[QAt]=ZAt;const qAt="prePassVertex",JAt=`#ifdef PREPASS_DEPTH vertexOutputs.vViewPos=(scene.view*worldPos).rgb; #endif #ifdef PREPASS_LOCAL_POSITION vertexOutputs.vPosition=positionUpdated.xyz; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) || defined(PREPASS_VELOCITY_LINEAR) 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 `;me.IncludesShadersStoreWGSL[qAt]=JAt;const eSt="uvVariableDeclaration",tSt=`#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 `;me.IncludesShadersStoreWGSL[eSt]=tSt;const iSt="samplerVertexImplementation",rSt=`#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 `;me.IncludesShadersStoreWGSL[iSt]=rSt;const nSt="bumpVertex",sSt=`#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 `;me.IncludesShadersStoreWGSL[nSt]=sSt;const aSt="vertexColorMixing",oSt=`#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 `;me.IncludesShadersStoreWGSL[aSt]=oSt;const cKe="pbrVertexShader",uKe=`#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) || defined(PREPASS_VELOCITY_LINEAR)) 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 }`;me.ShadersStoreWGSL[cKe]=uKe;const hKe={name:cKe,shader:uKe},dKe=Object.freeze(Object.defineProperty({__proto__:null,pbrVertexShaderWGSL:hKe},Symbol.toStringTag,{value:"Module"})),lSt="prePassDeclaration",cSt=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `;me.IncludesShadersStoreWGSL[lSt]=cSt;const uSt="oitDeclaration",hSt=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #define MAX_DEPTH 99999.0 var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d; #endif `;me.IncludesShadersStoreWGSL[uSt]=hSt;const dSt="pbrFragmentExtraDeclaration",fSt=`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 `;me.IncludesShadersStoreWGSL[dSt]=fSt;const pSt="samplerFragmentDeclaration",mSt=`#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 `;me.IncludesShadersStoreWGSL[pSt]=mSt;const gSt="samplerFragmentAlternateDeclaration",_St=`#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 `;me.IncludesShadersStoreWGSL[gSt]=_St;const vSt="pbrFragmentSamplersDeclaration",ySt=`#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 `;me.IncludesShadersStoreWGSL[vSt]=ySt;const xSt="subSurfaceScatteringFunctions",bSt=`fn testLightingForSSS(diffusionProfile: f32)->bool {return diffusionProfile<1.;}`;me.IncludesShadersStoreWGSL[xSt]=bSt;const CSt="importanceSampling",ASt=`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);}`;me.IncludesShadersStoreWGSL[CSt]=ASt;const SSt="pbrHelperFunctions",ESt=`#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 `;me.IncludesShadersStoreWGSL[SSt]=ESt;const TSt="pbrDirectLightingSetupFunctions",MSt=`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;}`;me.IncludesShadersStoreWGSL[TSt]=MSt;const RSt="pbrDirectLightingFalloffFunctions",ISt=`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 }`;me.IncludesShadersStoreWGSL[RSt]=ISt;const PSt="pbrBRDFFunctions",wSt=`#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 `;me.IncludesShadersStoreWGSL[PSt]=wSt;const DSt="hdrFilteringFunctions",OSt=`#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 `;me.IncludesShadersStoreWGSL[DSt]=OSt;const LSt="pbrDirectLightingFunctions",NSt=`#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 `;me.IncludesShadersStoreWGSL[LSt]=NSt;const FSt="pbrIBLFunctions",BSt=`#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 `;me.IncludesShadersStoreWGSL[FSt]=BSt;const fKe="bumpFragmentMainFunctions",pKe=`#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 `;me.IncludesShadersStoreWGSL[fKe]=pKe;const mKe={name:fKe,shader:pKe},kSt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentMainFunctionsWGSL:mKe},Symbol.toStringTag,{value:"Module"})),gKe="bumpFragmentFunctions",_Ke=`#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 `;me.IncludesShadersStoreWGSL[gKe]=_Ke;const vKe={name:gKe,shader:_Ke},USt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentFunctionsWGSL:vKe},Symbol.toStringTag,{value:"Module"})),zSt="pbrBlockAlbedoOpacity",VSt=`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;} `;me.IncludesShadersStoreWGSL[GSt]=WSt;const KSt="pbrBlockAmbientOcclusion",HSt=`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;} `;me.IncludesShadersStoreWGSL[KSt]=HSt;const jSt="pbrBlockAlphaFresnel",$St=`#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 `;me.IncludesShadersStoreWGSL[XSt]=YSt;const QSt="pbrBlockReflection",ZSt=`#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 `;me.IncludesShadersStoreWGSL[QSt]=ZSt;const qSt="pbrBlockSheen",JSt=`#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 `;me.IncludesShadersStoreWGSL[qSt]=JSt;const eEt="pbrBlockClearcoat",tEt=`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 `;me.IncludesShadersStoreWGSL[eEt]=tEt;const iEt="pbrBlockIridescence",rEt=`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 `;me.IncludesShadersStoreWGSL[iEt]=rEt;const nEt="pbrBlockSubSurface",sEt=`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 `;me.IncludesShadersStoreWGSL[nEt]=sEt;const aEt="pbrBlockNormalGeometric",oEt=`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 `;me.IncludesShadersStoreWGSL[aEt]=oEt;const yKe="bumpFragment",xKe=`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 `;me.IncludesShadersStoreWGSL[yKe]=xKe;const bKe={name:yKe,shader:xKe},lEt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentWGSL:bKe},Symbol.toStringTag,{value:"Module"})),cEt="pbrBlockNormalFinal",uEt=`#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 `;me.IncludesShadersStoreWGSL[cEt]=uEt;const hEt="depthPrePass",dEt=`#ifdef DEPTHPREPASS fragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs; #endif `;me.IncludesShadersStoreWGSL[hEt]=dEt;const fEt="pbrBlockLightmapInit",pEt=`#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 `;me.IncludesShadersStoreWGSL[fEt]=pEt;const mEt="pbrBlockGeometryInfo",gEt=`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 `;me.IncludesShadersStoreWGSL[mEt]=gEt;const _Et="pbrBlockReflectance0",vEt=`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 `;me.IncludesShadersStoreWGSL[_Et]=vEt;const yEt="pbrBlockReflectance",xEt=`#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 `;me.IncludesShadersStoreWGSL[yEt]=xEt;const bEt="pbrBlockDirectLighting",CEt=`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 `;me.IncludesShadersStoreWGSL[bEt]=CEt;const AEt="pbrBlockFinalLitComponents",SEt=`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 `;me.IncludesShadersStoreWGSL[AEt]=SEt;const EEt="pbrBlockFinalUnlitComponents",TEt=`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; `;me.IncludesShadersStoreWGSL[EEt]=TEt;const MEt="pbrBlockFinalColorComposition",REt=`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)); `;me.IncludesShadersStoreWGSL[MEt]=REt;const IEt="pbrBlockImageProcessing",PEt=`#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 `;me.IncludesShadersStoreWGSL[IEt]=PEt;const wEt="oitFragment",DEt=`#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 `;me.IncludesShadersStoreWGSL[OEt]=LEt;const CKe="pbrPixelShader",AKe=`#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); #elif defined(PREPASS_VELOCITY_LINEAR) var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy / fragmentInputs.vPreviousPosition.w) - (fragmentInputs.vCurrentPosition.xy / fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_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 } `;me.ShadersStoreWGSL[CKe]=AKe;const SKe={name:CKe,shader:AKe},EKe=Object.freeze(Object.defineProperty({__proto__:null,pbrPixelShaderWGSL:SKe},Symbol.toStringTag,{value:"Module"})),NEt="decalVertexDeclaration",FEt=`#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif `;me.IncludesShadersStore[NEt]=FEt;const BEt="pbrVertexDeclaration",kEt=`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 `;me.IncludesShadersStore[BEt]=kEt;const UEt="pbrUboDeclaration",zEt=`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 `;me.IncludesShadersStore[UEt]=zEt;const VEt="uvAttributeDeclaration",GEt=`#ifdef UV{X} attribute vec2 uv{X}; #endif `;me.IncludesShadersStore[VEt]=GEt;const WEt="mainUVVaryingDeclaration",KEt=`#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif `;me.IncludesShadersStore[WEt]=KEt;const HEt="prePassVertexDeclaration",jEt=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vec3 vPosition; #endif #ifdef PREPASS_DEPTH varying vec3 vViewPos; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif `;me.IncludesShadersStore[HEt]=jEt;const $Et="samplerVertexDeclaration",XEt=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif `;me.IncludesShadersStore[$Et]=XEt;const YEt="harmonicsFunctions",QEt=`#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 `;me.IncludesShadersStore[YEt]=QEt;const ZEt="bumpVertexDeclaration",qEt=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif `;me.IncludesShadersStore[ZEt]=qEt;const JEt="prePassVertex",e6t=`#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #ifdef PREPASS_LOCAL_POSITION vPosition=positionUpdated.xyz; #endif #if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) || defined(PREPASS_VELOCITY_LINEAR) 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 `;me.IncludesShadersStore[JEt]=e6t;const t6t="uvVariableDeclaration",i6t=`#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif `;me.IncludesShadersStore[t6t]=i6t;const r6t="samplerVertexImplementation",n6t=`#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 `;me.IncludesShadersStore[r6t]=n6t;const s6t="bumpVertex",a6t=`#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 `;me.IncludesShadersStore[s6t]=a6t;const TKe="pbrVertexShader",MKe=`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) || defined(PREPASS_VELOCITY_LINEAR)) 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 }`;me.ShadersStore[TKe]=MKe;const RKe={name:TKe,shader:MKe},IKe=Object.freeze(Object.defineProperty({__proto__:null,pbrVertexShader:RKe},Symbol.toStringTag,{value:"Module"})),o6t="prePassDeclaration",l6t=`#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_LOCAL_POSITION varying highp vec3 vPosition; #endif #ifdef PREPASS_DEPTH varying highp vec3 vViewPos; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif `;me.IncludesShadersStore[o6t]=l6t;const c6t="oitDeclaration",u6t=`#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 `;me.IncludesShadersStore[c6t]=u6t;const h6t="decalFragmentDeclaration",d6t=`#ifdef DECAL uniform vec4 vDecalInfos; #endif `;me.IncludesShadersStore[h6t]=d6t;const f6t="pbrFragmentDeclaration",p6t=`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 `;me.IncludesShadersStore[f6t]=p6t;const m6t="pbrFragmentExtraDeclaration",g6t=`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 `;me.IncludesShadersStore[m6t]=g6t;const _6t="samplerFragmentDeclaration",v6t=`#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 `;me.IncludesShadersStore[_6t]=v6t;const y6t="samplerFragmentAlternateDeclaration",x6t=`#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 `;me.IncludesShadersStore[y6t]=x6t;const b6t="pbrFragmentSamplersDeclaration",C6t=`#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 `;me.IncludesShadersStore[b6t]=C6t;const A6t="subSurfaceScatteringFunctions",S6t=`bool testLightingForSSS(float diffusionProfile) {return diffusionProfile<1.;}`;me.IncludesShadersStore[A6t]=S6t;const E6t="pbrHelperFunctions",T6t=`#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;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=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 `;me.IncludesShadersStore[E6t]=T6t;const M6t="pbrDirectLightingSetupFunctions",R6t=`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;}`;me.IncludesShadersStore[M6t]=R6t;const I6t="pbrDirectLightingFalloffFunctions",P6t=`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 }`;me.IncludesShadersStore[I6t]=P6t;const w6t="pbrDirectLightingFunctions",D6t=`#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 `;me.IncludesShadersStore[w6t]=D6t;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 `;me.IncludesShadersStore[O6t]=L6t;const PKe="bumpFragmentMainFunctions",wKe=`#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 `;me.IncludesShadersStore[PKe]=wKe;const DKe={name:PKe,shader:wKe},N6t=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentMainFunctions:DKe},Symbol.toStringTag,{value:"Module"})),OKe="bumpFragmentFunctions",LKe=`#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 `;me.IncludesShadersStore[OKe]=LKe;const NKe={name:OKe,shader:LKe},F6t=Object.freeze(Object.defineProperty({__proto__:null,bumpFragmentFunctions:NKe},Symbol.toStringTag,{value:"Module"})),B6t="decalFragment",k6t=`#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 `;me.IncludesShadersStore[B6t]=k6t;const U6t="pbrBlockAlbedoOpacity",z6t=`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;} `;me.IncludesShadersStore[V6t]=G6t;const W6t="pbrBlockAmbientOcclusion",K6t=`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;} `;me.IncludesShadersStore[W6t]=K6t;const H6t="pbrBlockAlphaFresnel",j6t=`#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 `;me.IncludesShadersStore[$6t]=X6t;const Y6t="pbrBlockReflection",Q6t=`#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 `;me.IncludesShadersStore[Y6t]=Q6t;const Z6t="pbrBlockSheen",q6t=`#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 `;me.IncludesShadersStore[Z6t]=q6t;const J6t="pbrBlockClearcoat",eTt=`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 `;me.IncludesShadersStore[J6t]=eTt;const tTt="pbrBlockIridescence",iTt=`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 `;me.IncludesShadersStore[tTt]=iTt;const rTt="pbrBlockSubSurface",nTt=`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 `;me.IncludesShadersStore[rTt]=nTt;const sTt="pbrBlockNormalGeometric",aTt=`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 `;me.IncludesShadersStore[sTt]=aTt;const FKe="bumpFragment",BKe=`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 `;me.IncludesShadersStore[FKe]=BKe;const kKe={name:FKe,shader:BKe},oTt=Object.freeze(Object.defineProperty({__proto__:null,bumpFragment:kKe},Symbol.toStringTag,{value:"Module"})),lTt="pbrBlockNormalFinal",cTt=`#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 `;me.IncludesShadersStore[lTt]=cTt;const uTt="depthPrePass",hTt=`#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif `;me.IncludesShadersStore[uTt]=hTt;const dTt="pbrBlockLightmapInit",fTt=`#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 `;me.IncludesShadersStore[dTt]=fTt;const pTt="pbrBlockGeometryInfo",mTt=`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 `;me.IncludesShadersStore[pTt]=mTt;const gTt="pbrBlockReflectance0",_Tt=`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 `;me.IncludesShadersStore[gTt]=_Tt;const vTt="pbrBlockReflectance",yTt=`#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 `;me.IncludesShadersStore[vTt]=yTt;const xTt="pbrBlockDirectLighting",bTt=`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 `;me.IncludesShadersStore[xTt]=bTt;const CTt="pbrBlockFinalLitComponents",ATt=`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 `;me.IncludesShadersStore[CTt]=ATt;const STt="pbrBlockFinalUnlitComponents",ETt=`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; `;me.IncludesShadersStore[STt]=ETt;const TTt="pbrBlockFinalColorComposition",MTt=`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); `;me.IncludesShadersStore[TTt]=MTt;const RTt="pbrBlockImageProcessing",ITt=`#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 `;me.IncludesShadersStore[RTt]=ITt;const PTt="oitFragment",wTt=`#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 `;me.IncludesShadersStore[DTt]=OTt;const UKe="pbrPixelShader",zKe=`#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>ALPHATESTVALUE ? 1.0 : 0.0; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_LOCAL_POSITION gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition*0.5+0.5,writeGeometryInfo); #endif #if defined(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); #elif defined(PREPASS_VELOCITY_LINEAR) vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) - (vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_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_NDC_DEPTH gl_FragData[PREPASS_NDC_DEPTH_INDEX]=vec4( gl_FragCoord.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_WORLD_NORMAL gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo); #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 } `;me.ShadersStore[UKe]=zKe;const VKe={name:UKe,shader:zKe},GKe=Object.freeze(Object.defineProperty({__proto__:null,pbrPixelShader:VKe},Symbol.toStringTag,{value:"Module"}));var pde;(function(r){r[r.GLSL=0]="GLSL",r[r.WGSL=1]="WGSL"})(pde||(pde={}));class bx extends Cn{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=pe.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const n=this.getScene();n?n.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=s=>{if(typeof s!="string")return;let a=null,o=null,l;const c=s.split(` `);let u=0,h=0,d=0,f=0,p=0;for(let g=0;g0&&(g+1)%4===0)a[g]=255;else{const m=o[g];a[g]=m/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()},n=this.getScene();return n?n._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 bx(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 bx(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}}bx._NoneEmptyLineRegex=/\S+/;xe("BABYLON.ColorGradingTexture",bx);class hw extends Cn{constructor(e,t,i,n=!1,s=!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=be.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=l,this._noMipmap=n,this.gammaSpace=s,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?Ie.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 n=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);n.generateMipMaps=!this._noMipmap,i.addPendingData(n),n.url=this.url,n.isReady=!1,i.getEngine()._internalTexturesCache.push(n),this._texture=n;const s=document.createElement("canvas");qw(this.url,a=>{this._width=a.width,this._height=a.height,s.width=this._width,s.height=this._height;const o=s.getContext("2d");o.drawImage(a,0,0);const l=o.getImageData(0,0,a.width,a.height);this._buffer=l.data.buffer,s.remove(),e()},(a,o)=>{i.removePendingData(n),t&&t(`${this.getClassName()} could not be loaded`,o)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const s=this._getFloat32ArrayFromArrayBuffer(this._buffer),a=C3.ConvertPanoramaToCubemap(s,this._width,this._height,this._size,this._supersample),o=[];for(let l=0;l<6;l++){const c=a[hw._FacesMapping[l]];o.push(c)}return o};if(!e)return;const i=t(),n=this._texture;e.getEngine().updateRawCubeTexture(n,i,n.format,n.type,n.invertY),n.isReady=!0,e.removePendingData(n),n.onLoadedObservable.notifyObservers(n),n.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let n=0;for(let s=0;se.length){ge.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let n=!1,s=!1,a=!1;switch(i.image_type){case BTt:n=!0;case LTt:s=!0;break;case kTt:n=!0;case NTt:break;case UTt:n=!0;case FTt:a=!0;break}let o;const l=i.pixel_size>>3,c=i.width*i.height*l;let u;if(s&&(u=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),n){o=new Uint8Array(c);let x,b,C,A=0;const E=new Uint8Array(l);for(;t>VTt){default:case KTt:h=0,f=1,m=i.width,d=0,p=1,g=i.height;break;case GTt:h=0,f=1,m=i.width,d=i.height-1,p=-1,g=-1;break;case HTt:h=i.width-1,f=-1,m=-1,d=0,p=1,g=i.height;break;case WTt:h=i.width-1,f=-1,m=-1,d=i.height-1,p=-1,g=-1;break}const _="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",y=WKe[_](i,u,o,d,p,g,h,f,m);r.getEngine()._uploadDataToTextureDirectly(r,y)}function jTt(r,e,t,i,n,s,a,o,l){const c=t,u=e,h=r.width,d=r.height;let f,p=0,g,m;const _=new Uint8Array(h*d*4);for(m=i;m!==s;m+=n)for(g=a;g!==l;g+=o,p++)f=c[p],_[(g+h*m)*4+3]=255,_[(g+h*m)*4+2]=u[f*3+0],_[(g+h*m)*4+1]=u[f*3+1],_[(g+h*m)*4+0]=u[f*3+2];return _}function $Tt(r,e,t,i,n,s,a,o,l){const c=t,u=r.width,h=r.height;let d,f=0,p,g;const m=new Uint8Array(u*h*4);for(g=i;g!==s;g+=n)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;m[(p+u*g)*4+0]=_,m[(p+u*g)*4+1]=y,m[(p+u*g)*4+2]=v,m[(p+u*g)*4+3]=d&32768?0:255}return m}function XTt(r,e,t,i,n,s,a,o,l){const c=t,u=r.width,h=r.height;let d=0,f,p;const g=new Uint8Array(u*h*4);for(p=i;p!==s;p+=n)for(f=a;f!==l;f+=o,d+=3)g[(f+u*p)*4+3]=255,g[(f+u*p)*4+2]=c[d+0],g[(f+u*p)*4+1]=c[d+1],g[(f+u*p)*4+0]=c[d+2];return g}function YTt(r,e,t,i,n,s,a,o,l){const c=t,u=r.width,h=r.height;let d=0,f,p;const g=new Uint8Array(u*h*4);for(p=i;p!==s;p+=n)for(f=a;f!==l;f+=o,d+=4)g[(f+u*p)*4+2]=c[d+0],g[(f+u*p)*4+1]=c[d+1],g[(f+u*p)*4+0]=c[d+2],g[(f+u*p)*4+3]=c[d+3];return g}function QTt(r,e,t,i,n,s,a,o,l){const c=t,u=r.width,h=r.height;let d,f=0,p,g;const m=new Uint8Array(u*h*4);for(g=i;g!==s;g+=n)for(p=a;p!==l;p+=o,f++)d=c[f],m[(p+u*g)*4+0]=d,m[(p+u*g)*4+1]=d,m[(p+u*g)*4+2]=d,m[(p+u*g)*4+3]=255;return m}function ZTt(r,e,t,i,n,s,a,o,l){const c=t,u=r.width,h=r.height;let d=0,f,p;const g=new Uint8Array(u*h*4);for(p=i;p!==s;p+=n)for(f=a;f!==l;f+=o,d+=2)g[(f+u*p)*4+0]=c[d+0],g[(f+u*p)*4+1]=c[d+0],g[(f+u*p)*4+2]=c[d+0],g[(f+u*p)*4+3]=c[d+1];return g}const WKe={GetTGAHeader:uV,UploadContent:W_e,_getImageData8bits:jTt,_getImageData16bits:$Tt,_getImageData24bits:XTt,_getImageData32bits:YTt,_getImageDataGrey8bits:QTt,_getImageDataGrey16bits:ZTt};class KKe{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=uV(n);i(s.width,s.height,t.generateMipMaps,!1,()=>{W_e(t,n)})}}const qTt=Object.freeze(Object.defineProperty({__proto__:null,_TGATextureLoader:KKe},Symbol.toStringTag,{value:"Module"}));class HKe{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=k_e(n),a=U_e(n,s),o=s.width*s.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 JTt=Object.freeze(Object.defineProperty({__proto__:null,_HDRTextureLoader:HKe},Symbol.toStringTag,{value:"Module"}));function eMt(){const r={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?r.cTFBC3:r.cTFBC1);let f=!0;c.startTranscoding()||(f=!1);const p=[];for(let g=0;g>2&3],h[v++]=u[y>>4&3],h[v++]=u[y>>6&3]}}return h}}function tMt(r,e,t){return new Promise((i,n)=>{const s=a=>{a.data.action==="init"?(r.removeEventListener("message",s),i(r)):a.data.action==="error"&&n(a.data.error||"error initializing worker")};r.addEventListener("message",s),r.postMessage({action:"init",url:t?Ie.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}class iMt{}class rMt{}var xv;(function(r){r[r.cTFETC1=0]="cTFETC1",r[r.cTFETC2=1]="cTFETC2",r[r.cTFBC1=2]="cTFBC1",r[r.cTFBC3=3]="cTFBC3",r[r.cTFBC4=4]="cTFBC4",r[r.cTFBC5=5]="cTFBC5",r[r.cTFBC7=6]="cTFBC7",r[r.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",r[r.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",r[r.cTFASTC_4x4=10]="cTFASTC_4x4",r[r.cTFATC_RGB=11]="cTFATC_RGB",r[r.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",r[r.cTFRGBA32=13]="cTFRGBA32",r[r.cTFRGB565=14]="cTFRGB565",r[r.cTFBGR565=15]="cTFBGR565",r[r.cTFRGBA4444=16]="cTFRGBA4444",r[r.cTFFXT1_RGB=17]="cTFFXT1_RGB",r[r.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",r[r.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",r[r.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",r[r.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(xv||(xv={}));const a3={JSModuleURL:`${Ie._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Ie._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},jKe=(r,e)=>{let t;switch(r){case xv.cTFETC1:t=36196;break;case xv.cTFBC1:t=33776;break;case xv.cTFBC4:t=33779;break;case xv.cTFASTC_4x4:t=37808;break;case xv.cTFETC2:t=37496;break;case xv.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let Rae=null,nx=null,nMt=0;const sMt=!1,aMt=()=>(Rae||(Rae=new Promise((r,e)=>{nx?r(nx):Ie.LoadFileAsync(Ie.GetBabylonScriptURL(a3.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${eMt})()`],{type:"application/javascript"}));nx=new Worker(i),tMt(nx,t,a3.JSModuleURL).then(r,e)}).catch(e)})),Rae),oMt=r=>{nx=r},IZ=(r,e)=>{const t=r instanceof ArrayBuffer?new Uint8Array(r):r;return new Promise((i,n)=>{aMt().then(()=>{const s=nMt++,a=l=>{l.data.action==="transcode"&&l.data.id===s&&(nx.removeEventListener("message",a),l.data.success?i(l.data):n("Transcode is not supported on this device"))};nx.addEventListener("message",a);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),nx.postMessage({action:"transcode",id:s,imageData:o,config:e,ignoreSupportedFormats:sMt},[o.buffer])},s=>{n(s)})})},yX=(r,e)=>{var i,n;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;r.isCube&&(t=(n=e._gl)==null?void 0:n.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,r,!0)},PZ=(r,e)=>{const t=r.getEngine();for(let i=0;i{t._releaseTexture(s),yX(r,t)})}else r._invertVScale=!r.invertY,r.width=n.width+3&-4,r.height=n.height+3&-4,r.samplingMode=2,yX(r,t),t._uploadDataToTextureDirectly(r,new Uint16Array(n.transcodedPixels.buffer),i,0,4,!0);else{r.width=n.width,r.height=n.height,r.generateMipMaps=e.fileInfo.images[i].levels.length>1;const s=Bee.GetInternalFormatFromBasisFormat(e.format,t);r.format=s,yX(r,t),e.fileInfo.images[i].levels.forEach((a,o)=>{t._uploadCompressedDataToTextureDirectly(r,s,a.width,a.height,a.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(Xt.Log2(r.width)%1!==0||Xt.Log2(r.height)%1!==0)&&(Ie.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."),r._cachedWrapU=be.CLAMP_ADDRESSMODE,r._cachedWrapV=be.CLAMP_ADDRESSMODE)}}},Bee={JSModuleURL:a3.JSModuleURL,WasmModuleURL:a3.WasmModuleURL,GetInternalFormatFromBasisFormat:jKe,TranscodeAsync:IZ,LoadTextureFromTranscodeResult:PZ};Object.defineProperty(Bee,"JSModuleURL",{get:function(){return a3.JSModuleURL},set:function(r){a3.JSModuleURL=r}});Object.defineProperty(Bee,"WasmModuleURL",{get:function(){return a3.WasmModuleURL},set:function(r){a3.WasmModuleURL=r}});class $Ke{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,s){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}};IZ(e,o).then(l=>{const c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;PZ(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}).catch(l=>{Ie.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(l)})}loadData(e,t,i){const n=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};IZ(e,s).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,()=>{PZ(t,a)})}).catch(a=>{Ie.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ie.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}const lMt=Object.freeze(Object.defineProperty({__proto__:null,_BasisTextureLoader:$Ke},Symbol.toStringTag,{value:"Module"})),XKe=4,mde=4,YKe=1,c5=2,cMt=8,wZ=65536,lRe=wZ>>3,uMt=16,sx=14,tk=(1<>-c-14,i[l|256]=1024>>-c-14|32768,n[l]=-c-1,n[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,n[l]=13,n[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,n[l]=24,n[l|256]=24):(i[l]=31744,i[l|256]=64512,n[l]=13,n[l|256]=13)}const s=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,s[l]=c|u}for(let l=1024;l<2048;++l)s[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:n,mantissaTable:s,exponentTable:a,offsetTable:o}}function DZ(r,e){const t=new Uint8Array(r);let i=0;for(;t[e.value+i]!=0;)i+=1;const n=new TextDecoder().decode(t.slice(e.value,e.value+i));return e.value=e.value+i+1,n}function dg(r,e){const t=r.getInt32(e.value,!0);return e.value+=XKe,t}function y_(r,e){const t=r.getUint32(e.value,!0);return e.value+=XKe,t}function hV(r,e){const t=r.getUint8(e.value);return e.value+=YKe,t}function tU(r,e){const t=r.getUint16(e.value,!0);return e.value+=c5,t}function H_e(r,e){const t=r[e.value];return e.value+=YKe,t}function ZKe(r,e){let t;return"getBigInt64"in DataView.prototype?t=Number(r.getBigInt64(e.value,!0)):t=r.getUint32(e.value+4,!0)+Number(r.getUint32(e.value,!0)<<32),e.value+=cMt,t}function hh(r,e){const t=r.getFloat32(e.value,!0);return e.value+=mde,t}function qKe(r,e){return fMt(tU(r,e))}function fMt(r){const e=(r&31744)>>10,t=r&1023;return(r>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function pMt(r){if(Math.abs(r)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");r=za(r,-65504,65504),xX.floatView[0]=r;const e=xX.uint32View[0],t=e>>23&511;return xX.baseTable[t]+((e&8388607)>>xX.shiftTable[t])}function JKe(r,e){return pMt(hh(r,e))}function mMt(r,e,t){const i=new TextDecoder().decode(new Uint8Array(r).slice(e.value,e.value+t));return e.value=e.value+t,i}function gMt(r,e){const t=dg(r,e),i=y_(r,e);return[t,i]}function _Mt(r,e){const t=y_(r,e),i=y_(r,e);return[t,i]}function vMt(r,e){const t=hh(r,e),i=hh(r,e);return[t,i]}function yMt(r,e){const t=hh(r,e),i=hh(r,e),n=hh(r,e);return[t,i,n]}function xMt(r,e,t){const i=e.value,n=[];for(;e.values||(e[n++]=r[t++],n>s));)e[n++]=r[i++]}const EMt=20000630;function tHe(r,e){if(r.getUint32(0,!0)!=EMt)throw new Error("Incorrect OpenEXR format");const t=r.getUint8(4),i=r.getUint8(5),n={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)};e.value=8;const s={};let a=!0;for(;a;){const o=DZ(r.buffer,e);if(!o)a=!1;else{const l=DZ(r.buffer,e),c=y_(r,e),u=eHe(r,e,l,c);u===void 0?ge.Warn(`Unknown header attribute type ${l}'.`):s[o]=u}}if(i&-5)throw new Error("Unsupported file format");return{version:t,spec:n,...s}}const iHe=16,TMt=1<>3]&1<<(n&7))&&(e[t++]=n);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+wB[t]>>1;wB[t]=e,e=i}for(let t=0;t0&&(r[t]=i|wB[i]++<<6)}}function IMt(r,e,t,i,n,s){const a=e;let o=0,l=0;for(;i<=n;i++){if(a.value-e.value>t)return;let c=hRe(6,o,l,r,a);const u=c.l;if(o=c.c,l=c.lc,s[i]=u,u==QKe){if(a.value-e.value>t)throw new Error("Error in HufUnpackEncTable");c=hRe(8,o,l,r,a);let h=c.l+hMt;if(o=c.c,l=c.lc,i+h>n+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}else if(u>=gde){let h=u-gde+2;if(i+h>n+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}}RMt(s)}function nHe(r){return r&63}function sHe(r){return r>>6}function PMt(r,e,t,i){for(;e<=t;e++){const n=sHe(r[e]),s=nHe(r[e]);if(n>>s)throw new Error("Invalid table entry");if(s>sx){const a=i[n>>s-sx];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[(n<=sx;){const g=c>>u-sx&cRe,m=e[g];if(m.len){u-=m.len;const _=Iae(m.lit,s,c,u,t,i,o,l,h);_&&(c=_.c,u=_.lc)}else{if(!m.p)throw new Error("hufDecode issues");let _;for(_=0;_=y&&sHe(r[m.p[_]])==(c>>u-y&(1<>=f,u-=f;u>0;){const p=e[c<=tk||c<0||c>=tk)throw new Error("Wrong HUF_ENCSIZE");const h=new Array(tk),d=new Array(K_e);MMt(d);const f=i-(t.value-o);if(IMt(r,t,f,l,c,h),u>8*(i-(t.value-o)))throw new Error("Wrong hufUncompress");PMt(h,l,c,d),wMt(h,d,r,t,u,c,s,n,a)}function yde(r){return r&65535}function dRe(r){const e=yde(r);return e>32767?e-65536:e}function NI(r,e){const t=dRe(r),n=dRe(e),s=t+(n&1)+(n>>1),a=s,o=s-n;return{a,b:o}}function FI(r,e){const t=yde(r),i=yde(e),n=t-(i>>1)&uRe;return{a:i+n-TMt&uRe,b:n}}function oHe(r,e,t,i,n,s,a){const o=a<16384,l=t>n?n: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+s*(n-u),f=s*c,p=s*u,g=i*c,m=i*u;let _,y,v,x;for(;h<=d;h+=p){let b=h;const C=h+i*(t-u);for(;b<=C;b+=m){const A=b+g,E=b+f,P=E+g;if(o){let w=NI(r[b+e],r[E+e]);_=w.a,v=w.b,w=NI(r[A+e],r[P+e]),y=w.a,x=w.b,w=NI(_,y),r[b+e]=w.a,r[A+e]=w.b,w=NI(v,x),r[E+e]=w.a,r[P+e]=w.b}else{let w=FI(r[b+e],r[E+e]);_=w.a,v=w.b,w=FI(r[A+e],r[P+e]),y=w.a,x=w.b,w=FI(_,y),r[b+e]=w.a,r[A+e]=w.b,w=FI(v,x),r[E+e]=w.a,r[P+e]=w.b}}if(t&c){const A=b+f;let E;o?E=NI(r[b+e],r[A+e]):E=FI(r[b+e],r[A+e]),_=E.a,r[A+e]=E.b,r[b+e]=_}}if(n&c){let b=h;const C=h+i*(t-u);for(;b<=C;b+=m){const A=b+g;let E;o?E=NI(r[b+e],r[A+e]):E=FI(r[b+e],r[A+e]),_=E.a,r[A+e]=E.b,r[b+e]=_}}u=c,c>>=1}return h}function lHe(r,e,t){for(let i=0;i0;){const s=n.getInt8(i++);if(s<0){const a=-s;e-=a+1;for(let o=0;o=lRe)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(r.compression){case $1.NO_COMPRESSION:n.lines=1,n.uncompress=X_e;break;case $1.RLE_COMPRESSION:n.lines=1,n.uncompress=uHe;break;case $1.ZIPS_COMPRESSION:n.lines=1,n.uncompress=xde,await Ie.LoadScriptAsync(BS.FFLATEUrl);break;case $1.ZIP_COMPRESSION:n.lines=16,n.uncompress=xde,await Ie.LoadScriptAsync(BS.FFLATEUrl);break;case $1.PIZ_COMPRESSION:n.lines=32,n.uncompress=dHe;break;case $1.PXR24_COMPRESSION:n.lines=16,n.uncompress=hHe,await Ie.LoadScriptAsync(BS.FFLATEUrl);break;default:throw new Error($1[r.compression]+" is unsupported")}n.scanlineBlockSize=n.lines;const s={};for(const c of r.channels)switch(c.name){case"Y":case"R":case"G":case"B":case"A":s[c.name]=!0,n.type=c.pixelType}let a=!1;if(s.R&&s.G&&s.B)a=!s.A,n.outputChannels=4,n.decodeChannels={R:0,G:1,B:2,A:3};else if(s.Y)n.outputChannels=1,n.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(n.type===1)switch(i){case e_.Float:n.getter=qKe,n.inputSize=c5;break;case e_.HalfFloat:n.getter=tU,n.inputSize=c5;break}else if(n.type===2)switch(i){case e_.Float:n.getter=hh,n.inputSize=mde;break;case e_.HalfFloat:n.getter=JKe,n.inputSize=mde}else throw new Error("Unsupported pixelType "+n.type+" for "+r.compression);n.blockCount=n.height/n.scanlineBlockSize;for(let c=0;cc:n.scanOrder=c=>n.height-1-c,n.outputChannels==4?(n.format=5,n.linearSpace=!0):(n.format=6,n.linearSpace=!1),n}function pHe(r,e,t,i){const n={value:0};for(let s=0;sr.height?r.height-a:r.scanlineBlockSize;const l=r.size=r.height)continue;const d=c*r.bytesPerLine,f=(r.height-1-h)*r.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 DMt=Object.freeze(Object.defineProperty({__proto__:null,_ExrTextureLoader:mHe},Symbol.toStringTag,{value:"Module"}));class r_ extends vn{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,n,s,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 n=e.length-1;n>=0;n--)this._textures[n]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}class bde{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class N0{constructor(e,t,i,n){return this.name=e,this.meshes=t,this.scene=n,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??ee.UVKind,this.options.uvsOut=this.options.uvsOut??ee.UVKind,this.options.layout=this.options.layout??N0.LAYOUT_STRIP,this.options.layout===N0.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??N0.SUBUV_WRAP,this.options.paddingMode===N0.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new at(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new Ne(1,1).divide(t);let n=0;const s=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{n++,m.update(!1);const b=_.getImageData(0,0,u,u),C=this.sets[x];if(C.getContext().putImageData(b,t.x*y.x,t.y*y.y),m.dispose(),C.update(!1),n==s){h(),e();return}},x=o[g]||"_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 b=p[x],C=new Image;b instanceof Ep?C.src=b.getContext().canvas.toDataURL("image/png"):C.src=b.url,Ie.SetCorsBehavior(C.src,C),C.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,u,u),m.update(!1),_.setTransform(1,0,0,-1,0,0);const A=[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 E=0;E<9;E++)_.drawImage(C,0,0,C.width,C.height,c+l*A[E],c+l*A[E+1]-u,l,l);break;case 1:for(let E=0;E{a.dispose&&a.dispose()};for(let a=0;a{try{if(this.meshes.length===0){e();return}let i=0;const n=s=>{if(i++,this.options.map){for(let a=0;a{n(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:[]},n=Object.keys(this.sets),s=Object.keys(this.options);try{for(let l=0;l{try{this.setFragment(this._texturePath)}catch{ge.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",n=new oa;n.open("GET",i),n.addEventListener("load",()=>{if(n.status===200||n.responseText&&n.responseText.length>0)try{this._config=JSON.parse(n.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),n.addEventListener("error",()=>{t()},!1);try{n.send()}catch{ge.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 ot.Clone(()=>{const e=this.getScene(),t=this._texture,i=new kee(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 NMt extends be{constructor(e,t,i,n,s,a,o=!0,l=!1,c=be.TRILINEAR_SAMPLINGMODE,u=0,h){super(null,a,!o,l),this.format=s,this._texture=a.getEngine().createRawTexture3D(e,t,i,n,s,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 Y_e extends vn{constructor(e,t,i,n){super(e,t,i,n,!0),this.refractionPlane=new Dc(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 Y_e(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 FMt extends Iv{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 Cde;(function(r){r[r.Uniform=0]="Uniform",r[r.Attribute=1]="Attribute",r[r.Varying=2]="Varying",r[r.Undefined=3]="Undefined"})(Cde||(Cde={}));class ka extends oE{constructor(e,t,i,n,s){super(e,t,i),this._blockType=n,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof ka&&e._blockName===this._blockName?0:1}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class _He extends Li{constructor(e){super(e,Ee.Vertex),this.registerInput("matricesIndices",re.Vector4),this.registerInput("matricesWeights",re.Vector4),this.registerInput("matricesIndicesExtra",re.Vector4,!0),this.registerInput("matricesWeightsExtra",re.Vector4,!0),this.registerInput("world",re.Matrix),this.registerOutput("output",re.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([je(()=>Promise.resolve().then(()=>N3t),void 0),je(()=>Promise.resolve().then(()=>j3t),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>y3t),void 0),je(()=>Promise.resolve().then(()=>P3t),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(n=>n.isAttribute&&n.name==="matricesIndices"&&t(n));i||(i=new Br("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="matricesWeights"&&t(n));i||(i=new Br("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.World&&t(n));i||(i=new Br("world"),i.setAsSystemValue(Hr.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){rc(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&KJ(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 n=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 `,e.compilationString+=e._declareOutput(n)+` = ${s.associatedVariableName} * ${i}; `,e.compilationString+=`#else `,e.compilationString+=e._declareOutput(n)+` = ${s.associatedVariableName}; `,e.compilationString+=`#endif `,this}}xe("BABYLON.BonesBlock",_He);class vHe extends Li{constructor(e){super(e,Ee.Vertex),this.registerInput("world0",re.Vector4),this.registerInput("world1",re.Vector4),this.registerInput("world2",re.Vector4),this.registerInput("world3",re.Vector4),this.registerInput("world",re.Matrix,!0),this.registerOutput("output",re.Matrix),this.registerOutput("instanceID",re.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(n=>n.isAttribute&&n.name==="world0"&&t(n));i||(i=new Br("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="world1"&&t(n));i||(i=new Br("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="world2"&&t(n));i||(i=new Br("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="world3"&&t(n));i||(i=new Br("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="world"&&t(n));i||(i=new Br("world"),i.setAsSystemValue(Hr.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,n=!1,s){let a=!1;i.INSTANCES!==n&&(i.setValue("INSTANCES",n),a=!0),s&&i.THIN_INSTANCES!==!!(s!=null&&s.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(s!=null&&s.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],n=this._outputs[1],s=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}(${s.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(n)+` = ${h}(${u}); `:e.compilationString+=e._declareOutput(n)+` = 0.0; `,e.compilationString+=`#else `,e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName}; `,e.compilationString+=e._declareOutput(n)+` = 0.0; `,e.compilationString+=`#endif `,this}}xe("BABYLON.InstancesBlock",vHe);class Q_e extends Li{constructor(e){super(e,Ee.Vertex),this.registerInput("position",re.Vector3),this.registerInput("normal",re.Vector3),this.registerInput("tangent",re.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(re.Color4|re.Vector4|re.Vector3),this.registerInput("uv",re.Vector2),this.registerOutput("positionOutput",re.Vector3),this.registerOutput("normalOutput",re.Vector3),this.registerOutput("tangentOutput",re.Vector4),this.registerOutput("uvOutput",re.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([je(()=>Promise.resolve().then(()=>W3t),void 0),je(()=>Promise.resolve().then(()=>U3t),void 0),je(()=>Promise.resolve().then(()=>G3t),void 0),je(()=>Promise.resolve().then(()=>k3t),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>M3t),void 0),je(()=>Promise.resolve().then(()=>A3t),void 0),je(()=>Promise.resolve().then(()=>T3t),void 0),je(()=>Promise.resolve().then(()=>C3t),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="position"&&t(n));i||(i=new Br("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="normal"&&t(n));i||(i=new Br("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="tangent"&&t(n));i||(i=new Br("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="uv"&&t(n));i||(i=new Br("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const n=e.morphTargetManager;n!=null&&n.isUsingTextureForTargets&&(n.numMaxInfluencers||n.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&HJ(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Np(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,n){const s=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=n.NUM_MORPH_INFLUENCERS,g=i.morphTargetManager,m=g&&g.supportsNormals&&n.NORMAL,_=g&&g.supportsTangents&&n.TANGENT,y=g&&g.supportsUVs&&n.UV1;let v="";g!=null&&g.isUsingTextureForTargets&&p>0&&(v+=`${f._declareLocalVar("vertexID",re.Float)}; `),v+=`#ifdef MORPHTARGETS `;const x=f.shaderLanguage===1,b=x?"uniforms.":"";if(g!=null&&g.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) { `,v+=`if (i >= ${b}morphTargetCount) { break; } `,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${b}morphTargetTextureInfo.x; `,v+=`${c.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${s.associatedVariableName}) * ${b}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,m&&(v+=`#ifdef MORPHTARGETS_NORMAL `,v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${a.associatedVariableName}) * ${b}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,v+=`#endif `),y&&(v+=`#ifdef MORPHTARGETS_UV `,v+=`${d.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${l.associatedVariableName}) * ${b}morphTargetInfluences[i]; `,v+=`vertexID += 1.0; `,v+=`#endif `),_&&(v+=`#ifdef MORPHTARGETS_TANGENT `,v+=`${h.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[i]; `,o.type===re.Vector4?v+=`${h.associatedVariableName}.w = ${o.associatedVariableName}.w; `:v+=`${h.associatedVariableName}.w = 1.; `,v+=`#endif `),v+=`} `;else for(let C=0;C0)for(let C=0;CPromise.resolve().then(()=>_Ue),void 0),je(()=>Promise.resolve().then(()=>WCt),void 0),je(()=>Promise.resolve().then(()=>$Ct),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>tze),void 0),je(()=>Promise.resolve().then(()=>xAt),void 0),je(()=>Promise.resolve().then(()=>EAt),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],n=`//${this.name}`,s=e.shaderLanguage===1?"Vec3":"";return e._emitFunctionFromInclude("helperFunctions",n),e._emitFunctionFromInclude("imageProcessingDeclaration",n),e._emitFunctionFromInclude("imageProcessingFunctions",n),(a=t.connectedPoint)!=null&&a.isConnected&&(t.connectedPoint.type===re.Color4||t.connectedPoint.type===re.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${s}(${t.associatedVariableName}.rgb), ${t.associatedVariableName}.a); `),e.compilationString+=`#else `,e.compilationString+=`#ifdef IMAGEPROCESSING `,this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName} = vec4${e.fSuffix}(toLinearSpace${s}(${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}}V([Fi("Convert input to linear space",0,"ADVANCED")],Z_e.prototype,"convertInputToLinearSpace",void 0);xe("BABYLON.ImageProcessingBlock",Z_e);class uT extends Li{constructor(e){super(e,Ee.Fragment,!0),this.registerInput("normal",re.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(re.Color4|re.Vector4|re.Vector3),this.registerInput("tangent",re.Vector4,!1),this.registerInput("world",re.Matrix,!1),this.registerOutput("TBN",re.Object,Ee.Fragment,new ka("TBN",this,1,uT,"TBNBlock")),this.registerOutput("row0",re.Vector3,Ee.Fragment),this.registerOutput("row1",re.Vector3,Ee.Fragment),this.registerOutput("row2",re.Vector3,Ee.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 Ee.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(n=>n.isSystemValue&&n.systemValue===Hr.World&&t(n));i||(i=new Br("world"),i.setAsSystemValue(Hr.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="normal"&&t(n));i||(i=new Br("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="tangent"&&n.type===re.Vector4&&t(n));i||(i=new Br("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var c,u,h,d;const n=this.normal,s=this.tangent;let a=n.isConnected;(c=n.connectInputBlock)!=null&&c.isAttribute&&!e.isVerticesDataPresent((u=n.connectInputBlock)==null?void 0:u.name)&&(a=!1);let o=s.isConnected;(h=s.connectInputBlock)!=null&&h.isAttribute&&!e.isVerticesDataPresent((d=s.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,n=this.world,s=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===Ee.Fragment&&(e.compilationString+=` // ${this.name} ${e._declareLocalVar("tbnNormal",re.Vector3)} = normalize(${t.associatedVariableName}).xyz; ${e._declareLocalVar("tbnTangent",re.Vector3)} = normalize(${i.associatedVariableName}.xyz); ${e._declareLocalVar("tbnBitangent",re.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; ${c?"var":"mat3"} ${s.associatedVariableName} = ${u}(${n.associatedVariableName}[0].xyz, ${n.associatedVariableName}[1].xyz, ${n.associatedVariableName}[2].xyz) * ${u}(tbnTangent, tbnBitangent, tbnNormal); `,a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${h}(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); `),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${h}(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); `),l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = vec3${h}(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); `),e.sharedData.blocksWithDefines.push(this)),this}}xe("BABYLON.TBNBlock",uT);class hD extends Li{constructor(e){super(e,Ee.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",re.Vector4,!1),this.registerInput("worldNormal",re.Vector4,!1),this.registerInput("worldTangent",re.Vector4,!0),this.registerInput("uv",re.Vector2,!1),this.registerInput("normalMapColor",re.Color3,!1),this.registerInput("strength",re.Float,!1),this.registerInput("viewDirection",re.Vector3,!0),this.registerInput("parallaxScale",re.Float,!0),this.registerInput("parallaxHeight",re.Float,!0),this.registerInput("TBN",re.Object,!0,Ee.VertexAndFragment,new ka("TBN",this,0,uT,"TBNBlock")),this.registerInput("world",re.Matrix,!0),this.registerOutput("output",re.Vector4),this.registerOutput("uvOffset",re.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([je(()=>Promise.resolve().then(()=>lEt),void 0),je(()=>Promise.resolve().then(()=>kSt),void 0),je(()=>Promise.resolve().then(()=>USt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>oTt),void 0),je(()=>Promise.resolve().then(()=>N6t),void 0),je(()=>Promise.resolve().then(()=>F6t),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}prepareDefines(e,t,i){const n=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!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(n=>n.isAttribute&&n.name==="uv"&&t(n));i||(i=new Br("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new Br("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,n=this.worldPosition,s=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,re.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,re.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,re.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 g={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},m={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",re.Vector3)} = normalize(${s.associatedVariableName}.xyz); `,e.compilationString+=`${e._declareLocalVar("tbnTangent",re.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,e.compilationString+=`${e._declareLocalVar("tbnBitangent",re.Vector3)} = cross(tbnNormal, tbnTangent) * ${o?"uniforms.":""}${this._tangentCorrectionFactorName}; `,e.compilationString+=`${o?"var":"mat3"} vTBN = ${l}(tbnTangent, tbnBitangent, tbnNormal); `);let v=[g,m,_];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)`,b=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,C=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",A=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:b,replace:x},{search:A,replace:C},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const E=o?`textureSample(${h}, ${h+"Sampler"}`:`texture2D(${h}`,P=!d||!h?this.normalMapColor.associatedVariableName:`${E}, ${i.associatedVariableName} + uvOffset).xyz`,w=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(w,re.Vector3)+` = vec3${c}(0.); `,v=[{search:new RegExp(`texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\)`,"g"),replace:`${P}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",re.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, ${P}, 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:w+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${l}(normalMatrix) * `+w},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:d?this.viewDirection.associatedVariableName:`vec3${c}(0.)`},g],o?(v.push({search:/fragmentInputs.vBumpUV/g,replace:i.associatedVariableName}),v.push({search:/input.vPositionW/g,replace:n.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:n.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}(${w}, 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}}V([Fi("Invert X axis",0,"PROPERTIES",{notifiers:{update:!1}})],hD.prototype,"invertX",void 0);V([Fi("Invert Y axis",0,"PROPERTIES",{notifiers:{update:!1}})],hD.prototype,"invertY",void 0);V([Fi("Use parallax occlusion",0)],hD.prototype,"useParallaxOcclusion",void 0);V([Fi("Object Space Mode",0,"PROPERTIES",{notifiers:{update:!1}})],hD.prototype,"useObjectSpaceNormalMap",void 0);xe("BABYLON.PerturbNormalBlock",hD);class xHe extends Li{constructor(e){super(e,Ee.Fragment,!0),this.registerInput("value",re.Float,!0),this.registerInput("cutoff",re.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}}xe("BABYLON.DiscardBlock",xHe);class bHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerOutput("output",re.Float,Ee.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===Ee.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}}xe("BABYLON.FrontFacingBlock",bHe);class CHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerInput("input",re.AutoDetect,!1),this.registerOutput("dx",re.BasedOnInput),this.registerOutput("dy",re.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 n="dFdx",s="dFdy";return e.shaderLanguage===1&&(n="dpdx",s="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${n}(${this.input.associatedVariableName}); `),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${s}(${this.input.associatedVariableName}); `),this}}xe("BABYLON.DerivativeBlock",CHe);class AHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerOutput("xy",re.Vector2,Ee.Fragment),this.registerOutput("xyz",re.Vector3,Ee.Fragment),this.registerOutput("xyzw",re.Vector4,Ee.Fragment),this.registerOutput("x",re.Float,Ee.Fragment),this.registerOutput("y",re.Float,Ee.Fragment),this.registerOutput("z",re.Float,Ee.Fragment),this.registerOutput("w",re.Float,Ee.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 n of this._outputs)n.hasEndpoints&&(t+=`${e._declareOutput(n)} = ${i}.${n.name}; `);return t}_buildBlock(e){if(super._buildBlock(e),e.target===Ee.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}xe("BABYLON.FragCoordBlock",AHe);class SHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerOutput("xy",re.Vector2,Ee.Fragment),this.registerOutput("x",re.Float,Ee.Fragment),this.registerOutput("y",re.Float,Ee.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 n of this._outputs)n.hasEndpoints&&(i+=`${e._declareOutput(n)} = ${t}.${n.name}; `);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===Ee.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,re.Vector2);const t=e.shaderLanguage===1?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}xe("BABYLON.ScreenSizeBlock",SHe);class EHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerInput("vector",re.AutoDetect),this.registerInput("worldViewProjection",re.Matrix),this.registerOutput("output",re.Vector2),this.registerOutput("x",re.Float),this.registerOutput("y",re.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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(n=>n.systemValue===Hr.WorldViewProjection&&t(n));i||(i=new Br("worldViewProjection"),i.setAsSystemValue(Hr.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const n=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case re.Vector3:e.compilationString+=`${e._declareLocalVar(s,re.Vector4)} = ${n} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0); `;break;case re.Vector4:e.compilationString+=`${e._declareLocalVar(s,re.Vector4)} = ${n} * ${t.associatedVariableName}; `;break}return e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy / ${s}.w, ${s}.zw);`,e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${s}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${s}.xy; `),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${s}.x; `),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${s}.y; `),this}}xe("BABYLON.ScreenSpaceBlock",EHe);class THe extends Li{constructor(e){super(e,Ee.Fragment),this.registerInput("input",re.Vector2),this.registerInput("strength",re.Float),this.registerInput("center",re.Vector2),this.registerInput("offset",re.Vector2),this.registerOutput("output",re.Vector2),this.registerOutput("x",re.Float),this.registerOutput("y",re.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 Br("center");e.value=new Ne(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Br("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Br("offset");e.value=new Ne(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),n=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),a=e._getFreeVariableName("result");return e.compilationString+=` ${e._declareLocalVar(t,re.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; ${e._declareLocalVar(i,re.Float)} = ${this.strength.associatedVariableName} * length(${t}); ${e._declareLocalVar(n,re.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; ${e._declareLocalVar(s,re.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; ${e._declareLocalVar(a,re.Vector2)} = vec2(${n} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${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}}xe("BABYLON.TwirlBlock",THe);class dV extends Li{constructor(e){super(e,Ee.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",re.Float),this.registerInput("worldPosition",re.Vector3),this.registerInput("worldNormal",re.Vector3),this.registerInput("worldTangent",re.AutoDetect,!0),this.registerOutput("output",re.Vector4),this.registerOutput("xyz",re.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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,n=e.fSuffix;!this.generateInWorldSpace&&!this.worldTangent.isConnected&&ge.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const s=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;"} ${s} 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${n}(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}}V([Fi("Generate in world space instead of tangent space",0,"PROPERTIES",{notifiers:{update:!0}})],dV.prototype,"generateInWorldSpace",void 0);V([Fi("Force normalization for the worldNormal input",0,"PROPERTIES",{notifiers:{update:!0}})],dV.prototype,"automaticNormalizationNormal",void 0);V([Fi("Force normalization for the worldTangent input",0,"PROPERTIES",{notifiers:{update:!0}})],dV.prototype,"automaticNormalizationTangent",void 0);xe("BABYLON.HeightToNormalBlock",dV);class MHe extends Li{constructor(e){super(e,Ee.Fragment,!0),this.registerInput("depth",re.Float,!0),this.registerInput("worldPos",re.Vector4,!0),this.registerInput("viewProjection",re.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",re.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; ${e._declareLocalVar("v",re.Float)} = p.z / p.w; #ifndef IS_NDC_HALF_ZRANGE v = v * 0.5 + 0.5; #endif ${t} = v; `:ge.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}xe("BABYLON.FragDepthBlock",MHe);class RHe extends Li{constructor(e){super(e,Ee.Fragment),this.registerInput("worldPosition",re.Vector4,!1),this.registerInput("viewProjection",re.Matrix,!1),this.registerInput("worldNormal",re.AutoDetect,!0),this.registerOutput("depth",re.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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([je(()=>Promise.resolve().then(()=>Fbt),void 0),je(()=>Promise.resolve().then(()=>Ebt),void 0),je(()=>Promise.resolve().then(()=>Pbt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>lCt),void 0),je(()=>Promise.resolve().then(()=>mbt),void 0),je(()=>Promise.resolve().then(()=>Kbt),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",re.Vector3),e._emitUniformFromString("lightDataSM",re.Vector3),e._emitUniformFromString("depthValuesSM",re.Vector2),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`${e._declareLocalVar("worldPos",re.Vector4)} = ${this.worldPosition.associatedVariableName}; `,e.compilationString+=`${e._declareLocalVar("vPositionWSM",re.Vector3)}; `,e.compilationString+=`${e._declareLocalVar("vDepthMetricSM",re.Float)} = 0.0; `,e.compilationString+=`${e._declareLocalVar("zSM",re.Float)}; `,this.worldNormal.isConnected&&(e.compilationString+=`${e._declareLocalVar("vNormalW",re.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`${e._declareLocalVar("clipPos",re.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 n=i?"fragmentOutputs.fragDepth":"gl_FragDepth";return e.compilationString+=` #if SM_DEPTHTEXTURE == 1 #ifdef IS_NDC_HALF_ZRANGE ${n} = (clipPos.z / clipPos.w); #else ${n} = (clipPos.z / clipPos.w) * 0.5 + 0.5; #endif #endif `,e.compilationString+=`${e._declareOutput(this.depth)} = vec3${e.fSuffix}(depthSM, 1., 1.); `,this}}xe("BABYLON.ShadowMapBlock",RHe);class IHe extends Li{constructor(e){super(e,Ee.Fragment,!0),this.registerInput("viewDepth",re.Float,!0),this.registerInput("viewDepthLinear",re.Float,!0),this.registerInput("worldPosition",re.AutoDetect,!0),this.registerInput("localPosition",re.AutoDetect,!0),this.registerInput("viewNormal",re.AutoDetect,!0),this.registerInput("worldNormal",re.AutoDetect,!0),this.registerInput("reflectivity",re.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4|re.Color3|re.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]}get worldNormal(){return this._inputs[4]}get localPosition(){return this._inputs[5]}get viewDepthNDC(){return this._inputs[6]}_getFragData(e,t){return e?`fragmentOutputs.fragData${t}`:`gl_FragData[${t}]`}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.localPosition,n=this.viewNormal,s=this.worldNormal,a=this.viewDepth,o=this.reflectivity,l=this.viewDepthNDC;e.sharedData.blocksWithDefines.push(this);const c=`//${this.name}`,u=e._getShaderType(re.Vector4),h=e.shaderLanguage===1;return e._emitFunctionFromInclude("helperFunctions",c),e.compilationString+=`#if defined(PREPASS)\r `,e.compilationString+=h?`var fragData: array, SCENE_MRT_COUNT>;\r `:`vec4 fragData[SCENE_MRT_COUNT];\r `,e.compilationString+=`#ifdef PREPASS_DEPTH\r `,a.connectedPoint?e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${u}(${a.associatedVariableName}, 0.0, 0.0, 1.0);\r `:e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${u}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_NDC_DEPTH\r `,l.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NDC_DEPTH_INDEX] = vec4(${l.associatedVariableName}, 0.0, 0.0, 1.0);\r `:e.compilationString+=` gl_FragData[PREPASS_NDC_DEPTH_INDEX] = vec4(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] = ${u}(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===re.Vector4?t.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_POSITION_INDEX] = ${u}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_LOCAL_POSITION\r `,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===re.Vector4?i.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_NORMAL\r `,n.connectedPoint?e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${u}(${n.associatedVariableName}.rgb, ${n.connectedPoint.type===re.Vector4?n.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${u}(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_WORLD_NORMAL\r `,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===re.Vector4?s.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r `,o.connectedPoint?e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${u}(${o.associatedVariableName}.rgb, ${o.connectedPoint.type===re.Vector4?o.associatedVariableName+".a":"1.0"});\r `:e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${u}(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(h,1)} = fragData[1];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 2\r `,e.compilationString+=`${this._getFragData(h,2)} = fragData[2];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 3\r `,e.compilationString+=`${this._getFragData(h,3)} = fragData[3];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 4\r `,e.compilationString+=`${this._getFragData(h,4)} = fragData[4];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 5\r `,e.compilationString+=`${this._getFragData(h,5)} = fragData[5];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 6\r `,e.compilationString+=`${this._getFragData(h,6)} = fragData[6];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#if SCENE_MRT_COUNT > 7\r `,e.compilationString+=`${this._getFragData(h,7)} = fragData[7];\r `,e.compilationString+=`#endif\r `,e.compilationString+=`#endif\r `,this}}xe("BABYLON.PrePassOutputBlock",IHe);class PHe extends Li{constructor(e){super(e,Ee.VertexAndFragment,!1),this.registerInput("worldPosition",re.Vector4,!1,Ee.Vertex),this.registerInput("view",re.Matrix,!1,Ee.Vertex),this.registerInput("input",re.AutoDetect,!1,Ee.Fragment),this.registerInput("fogColor",re.AutoDetect,!1,Ee.Fragment),this.registerOutput("output",re.Color3,Ee.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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 je(()=>Promise.resolve().then(()=>XCt),void 0):await je(()=>Promise.resolve().then(()=>TAt),void 0),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.View&&t(n));i||(i=new Br("view"),i.setAsSystemValue(Hr.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.FogColor&&t(n));i||(i=new Br("fogColor",void 0,re.Color3),i.setAsSystemValue(Hr.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const n=e.getScene();i.setValue("FOG",t.fogEnabled&&WJ(e,n))}bind(e,t,i){if(!i)return;const n=i.getScene();e.setFloat4(this._fogParameters,n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===Ee.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",n="";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.",n="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 s=e._getFreeVariableName("fog"),a=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const l=this._outputs[0];e._emitUniformFromString(this._fogParameters,re.Vector4),e.compilationString+=`#ifdef FOG `,e.compilationString+=`${e._declareLocalVar(s,re.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${n}${this._fogParameters}); `,e.compilationString+=e._declareOutput(l)+` = ${s} * ${a.associatedVariableName}.rgb + (1.0 - ${s}) * ${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,re.Vector3);const n=e.shaderLanguage===1?"vertexOutputs.":"";e.compilationString+=`${n}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; `}return this}}xe("BABYLON.FogBlock",PHe);class OZ extends Li{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,ge.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Ee.Fragment:Ee.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ee.Fragment:Ee.Vertex}constructor(e){super(e,Ee.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",re.Vector4,!1,Ee.Vertex),this.registerInput("worldNormal",re.Vector4,!1,Ee.Fragment),this.registerInput("cameraPosition",re.Vector3,!1,Ee.Fragment),this.registerInput("glossiness",re.Float,!0,Ee.Fragment),this.registerInput("glossPower",re.Float,!0,Ee.Fragment),this.registerInput("diffuseColor",re.Color3,!0,Ee.Fragment),this.registerInput("specularColor",re.Color3,!0,Ee.Fragment),this.registerInput("view",re.Matrix,!0),this.registerOutput("diffuseOutput",re.Color3,Ee.Fragment),this.registerOutput("specularOutput",re.Color3,Ee.Fragment),this.registerOutput("shadow",re.Float,Ee.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([je(()=>Promise.resolve().then(()=>YCt),void 0),je(()=>Promise.resolve().then(()=>KCt),void 0),je(()=>Promise.resolve().then(()=>OCt),void 0),je(()=>Promise.resolve().then(()=>_Ue),void 0),je(()=>Promise.resolve().then(()=>HCt),void 0),je(()=>Promise.resolve().then(()=>jCt),void 0),je(()=>Promise.resolve().then(()=>kCt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>bAt),void 0),je(()=>Promise.resolve().then(()=>MAt),void 0),je(()=>Promise.resolve().then(()=>CAt),void 0),je(()=>Promise.resolve().then(()=>lAt),void 0),je(()=>Promise.resolve().then(()=>oAt),void 0),je(()=>Promise.resolve().then(()=>tze),void 0),je(()=>Promise.resolve().then(()=>AAt),void 0),je(()=>Promise.resolve().then(()=>SAt),void 0),je(()=>Promise.resolve().then(()=>fAt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.CameraPosition&&t(n));i||(i=new Br("cameraPosition"),i.setAsSystemValue(Hr.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const n=e.getScene();if(!this.light)Xu(n,e,i,!0,t.maxSimultaneousLights);else{const s={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};wz(n,e,this.light,this._lightId,i,!0,s),s.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;Oz(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,a)}}bind(e,t,i){if(!i)return;const n=i.getScene();this.light?Pz(this.light,this._lightId,n,e,!0):$u(n,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 n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,re.Vector4)&&(e.compilationString+=(e.shaderLanguage===1?"vertexOutputs.":"")+`${n} = ${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",re.Vector4)} = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",re.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":"",n=`//${this.name}`;if(e.target!==Ee.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const s=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,re.Vector3)}; `,n),e.compilationString+=`${o} = ${a.associatedVariableName}.xyz; `,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",n,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${a.associatedVariableName}`:void 0})):o=s+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",n),e._emitFunctionFromInclude("lightsFragmentFunctions",n,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",n,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",re.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o}); `),e.compilationString+=t?`var info: lightingInfo; `:`lightingInfo info; `,e.compilationString+=`${e._declareLocalVar("shadow",re.Float)} = 1.; `,e.compilationString+=`${e._declareLocalVar("aggShadow",re.Float)} = 0.; `,e.compilationString+=`${e._declareLocalVar("numLights",re.Float)} = 0.; `,e.compilationString+=`${e._declareLocalVar("glossiness",re.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; `,e.compilationString+=`${e._declareLocalVar("diffuseBase",re.Vector3)} = vec3${i}(0., 0., 0.); `,e.compilationString+=`${e._declareLocalVar("specularBase",re.Vector3)} = vec3${i}(0., 0., 0.); `,e.compilationString+=`${e._declareLocalVar("normalW",re.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz; `),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{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()}}V([Fi("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:OZ._OnGenerateOnlyFragmentCodeChanged}})],OZ.prototype,"generateOnlyFragmentCode",void 0);xe("BABYLON.LightBlock",OZ);class U0 extends Li{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??ei.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,Ee.VertexAndFragment),this.registerOutput("source",re.Object,Ee.VertexAndFragment,new ka("source",this,1,U0,"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===Ee.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,n){super._deserialize(e,t,i,n),e.texture&&!Yn.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(e.texture.url.indexOf("data:")===0?i="":n&&(e.texture.url=n(e.texture.url),e.texture.name=e.texture.url),this.texture=be.Parse(e.texture,t,i))}}xe("BABYLON.ImageSourceBlock",U0);class rU extends Li{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())??ei.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 rU._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!rU._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()??ei.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()??ei.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?Ee.Fragment:Ee.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",re.AutoDetect,!1,Ee.VertexAndFragment),this.registerInput("source",re.Object,!0,Ee.VertexAndFragment,new ka("source",this,0,U0,"ImageSourceBlock")),this.registerInput("layer",re.Float,!0),this.registerInput("lod",re.Float,!0),this.registerOutput("rgba",re.Color4,Ee.Neutral),this.registerOutput("rgb",re.Color3,Ee.Neutral),this.registerOutput("r",re.Float,Ee.Neutral),this.registerOutput("g",re.Float,Ee.Neutral),this.registerOutput("b",re.Float,Ee.Neutral),this.registerOutput("a",re.Float,Ee.Neutral),this.registerOutput("level",re.Float,Ee.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector2|re.Vector3|re.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 Ee.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return Ee.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===Ee.Fragment)return Ee.Fragment;if(e.target===Ee.Vertex)return Ee.VertexAndFragment;if(e.target===Ee.Neutral||e.target===Ee.VertexAndFragment){const t=e.ownerBlock;if(t.target===Ee.Fragment)return Ee.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return Ee.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===ah.PostProcess){const i=e.getBlockByPredicate(n=>n.name==="uv"&&t(n));i&&i.connectTo(this)}else{const i=e.mode===ah.Particle?"particle_uv":"uv";let n=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name===i&&t(s));n||(n=new Br("uv"),n.setAsAttribute(i)),n.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 n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!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!==Ee.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,re.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,re.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,re.Matrix,this._defineName);const i=e._getShaderType(re.Vector4),n=e._getShaderType(re.Vector2);e.compilationString+=`#ifdef ${this._defineName} `,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${n}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0)); `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `;let s="";if(e.shaderLanguage===1&&t.isConnectedToInputBlock&&t.associatedVariableName.indexOf("vertexInputs.")===-1&&(s="vertexInputs."),e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${s}${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 s,a,o,l;let t=e;const i=((a=(s=this._texture)==null?void 0:s._texture)==null?void 0:a.is2DArray)??!1,n=((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(n){const c=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${c})`}return t}_samplerFunc(e){return e.shaderLanguage===1?e.target===Ee.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===Ee.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,re.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)}; `,e.compilationString+=`#elif defined(${this._mainUVDefineName}) `,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.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===Ee.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===Ee.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.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,n=!1){if(n){if(e.target===Ee.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===Ee.Fragment){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${(e.shaderLanguage===1?"uniforms.":"")+this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s}; `,this._generateConversionCode(e,t,i)}_buildBlock(e){var i,n,s,a;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===Ee.Vertex||this._fragmentOnly||e.target===Ee.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===Ee.Fragment||this._isMixed&&e.target===Ee.Vertex){if(!this._imageSource){const o=e._getFreeVariableName(this.name);this._samplerName=o+"Texture",(n=(i=this._texture)==null?void 0:i._texture)!=null&&n.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!==Ee.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((a=(s=this._texture)==null?void 0:s._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,re.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,n){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Yn.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(e.texture.url.indexOf("data:")===0?i="":n&&(e.texture.url=n(e.texture.url),e.texture.name=e.texture.url),this.texture=be.Parse(e.texture,t,i))}}xe("BABYLON.TextureBlock",rU);class dw extends Li{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??ei.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?Ee.Fragment:Ee.VertexAndFragment)}constructor(e){super(e,Ee.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 je(()=>Promise.resolve().then(()=>GCt),void 0):await je(()=>Promise.resolve().then(()=>yAt),void 0),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(n=>n.isAttribute&&n.name==="position"&&t(n));i||(i=new Br("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.World&&t(n));i||(i=new Br("world"),i.setAsSystemValue(Hr.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.View&&t(n));i||(i=new Br("view"),i.setAsSystemValue(Hr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this._getTexture();!n||!n.getTextureMatrix||(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLocalCubicName,!!n.boundingBoxSize,!0),i.setValue(this._defineExplicitName,n.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,n.coordinatesMode===5,!0),i.setValue(this._defineCubicName,n.coordinatesMode===3||n.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",n.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,n.coordinatesMode===1,!0),i.setValue(this._definePlanarName,n.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,n.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,n.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,n.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,n.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,n){const s=this._getTexture();if(!(!i||!s)&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const a=s;e.setVector3(this._reflectionPositionName,a.boundingBoxPosition),e.setVector3(this._reflectionSizeName,a.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===Ee.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,re.Matrix);let i="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const n=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(n,re.Vector4))&&(this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(n,re.Vector4)} = ${this.worldPosition.associatedVariableName}; `:i+=`${t?"vertexOutputs.":""}${n} = ${this.worldPosition.associatedVariableName}; `),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,re.Vector3,this._defineSkyboxName))&&(i+=`#ifdef ${this._defineSkyboxName} `,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._positionUVWName,re.Vector3)} = ${this.position.associatedVariableName}.xyz; `:i+=`${t?"vertexOutputs.":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; `,i+=`#endif `),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,re.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(i+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) `,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._directionWName,re.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,re.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,re.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i,n=!1,s=!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,re.Vector3)} = computeMirroredFixedEquirectangularCoords(${i}, ${t}, ${l}); #endif #ifdef ${this._defineEquirectangularFixedName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeFixedEquirectangularCoords(${i}, ${t}, ${l}); #endif #ifdef ${this._defineEquirectangularName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeEquirectangularCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #ifdef ${this._defineSphericalName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeSphericalCoords(${i}, ${t}, ${h}, ${o}); #endif #ifdef ${this._definePlanarName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computePlanarCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #ifdef ${this._defineCubicName} #ifdef ${this._defineLocalCubicName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeCubicLocalCoords(${i}, ${t}, ${u}.xyz, ${o}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); #else ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeCubicCoords(${i}, ${t}, ${u}.xyz, ${o}); #endif #endif #ifdef ${this._defineProjectionName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeProjectionCoords(${i}, ${h}, ${o}); #endif #ifdef ${this._defineSkyboxName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = computeSkyBoxCoords(${c}, ${o}); #endif #ifdef ${this._defineExplicitName} ${e._declareLocalVar(this._reflectionVectorName,re.Vector3)} = vec3(0, 0, 0); #endif `;return s||(d+=`#ifdef ${this._defineOppositeZ} ${this._reflectionVectorName}.z *= -1.0; #endif `),n||(d+=` #ifdef ${this._define3DName} ${e._declareLocalVar(this._reflectionCoordsName,re.Vector3)} = ${this._reflectionVectorName}; #else ${e._declareLocalVar(this._reflectionCoordsName,re.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 n=re.Vector4;i.length===3&&(n=re.Vector3);let s=`${e._declareLocalVar(this._reflectionColorName,n)}; #ifdef ${this._define3DName} `;return t?s+=`${this._reflectionColorName} = ${e._generateTextureSampleCubeLOD(this._reflectionVectorName,this._cubeSamplerName,t)}${i}; `:s+=`${this._reflectionColorName} = ${e._generateTextureSampleCube(this._reflectionVectorName,this._cubeSamplerName)}${i}; `,s+=` #else `,t?s+=`${this._reflectionColorName} =${e._generateTextureSampleLOD(this._reflectionCoordsName,this._2DSamplerName,t)}${i}; `:s+=`${this._reflectionColorName} = ${e._generateTextureSample(this._reflectionCoordsName,this._2DSamplerName)}${i}; `,s+=`#endif `,s}writeOutputs(e,t){let i="";if(e.target===Ee.Fragment)for(const n of this._outputs)n.hasEndpoints&&(i+=`${e._declareOutput(n)} = ${t}.${n.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&&!Yn.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Za.Parse(e.texture,t,i):this.texture=be.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}V([Fi("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:dw._OnGenerateOnlyFragmentCodeChanged}})],dw.prototype,"generateOnlyFragmentCode",void 0);xe("BABYLON.ReflectionTextureBaseBlock",dw);class wHe extends dw{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ge.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ge.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?Ee.Fragment:Ee.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ee.Fragment:Ee.Vertex}constructor(e){super(e),this.registerInput("position",re.AutoDetect,!1,Ee.Vertex),this.registerInput("worldPosition",re.Vector4,!1,Ee.Vertex),this.registerInput("worldNormal",re.Vector4,!1,Ee.Fragment),this.registerInput("world",re.Matrix,!1,Ee.Vertex),this.registerInput("cameraPosition",re.Vector3,!1,Ee.Fragment),this.registerInput("view",re.Matrix,!1,Ee.Fragment),this.registerOutput("rgb",re.Color3,Ee.Fragment),this.registerOutput("rgba",re.Color4,Ee.Fragment),this.registerOutput("r",re.Float,Ee.Fragment),this.registerOutput("g",re.Float,Ee.Fragment),this.registerOutput("b",re.Float,Ee.Fragment),this.registerOutput("a",re.Float,Ee.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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(n=>n.systemValue===Hr.CameraPosition&&t(n));i||(i=new Br("cameraPosition"),i.setAsSystemValue(Hr.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!==Ee.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,re.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}}xe("BABYLON.ReflectionTextureBlock",wHe);class fV extends Li{constructor(e){super(e,Ee.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",re.AutoDetect,!1,Ee.VertexAndFragment),this.registerOutput("depth",re.Float,Ee.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector2|re.Vector3|re.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?Ee.VertexAndFragment:Ee.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===re.Vector3?re.Vector3:t.type===re.Vector4?re.Vector4:re.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,re.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===Ee.Fragment)return;const s=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,a=e.shaderLanguage===0?"":", 0";e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)}= ${s} ${i.associatedVariableName}.xy${a}); `;return}const n=e.shaderLanguage===0?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;if(this.uv.ownerBlock.target===Ee.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = ${n} ${i.associatedVariableName}.xy); `;return}e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = ${n} ${this._mainUVName}); `}_writeOutput(e,t,i,n=!1){if(n){if(e.target===Ee.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; `;return}if(this.uv.ownerBlock.target===Ee.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!==Ee.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}}V([Fi("Use non linear depth",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(r,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),r&&r.disableDepthRenderer(),i}}})],fV.prototype,"useNonLinearDepth",void 0);V([Fi("Store Camera space Z",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(r,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),r&&r.disableDepthRenderer(),i}}})],fV.prototype,"storeCameraSpaceZ",void 0);V([Fi("Force 32 bits float",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:r=>r==null?void 0:r.disableDepthRenderer()}})],fV.prototype,"force32itsFloat",void 0);xe("BABYLON.SceneDepthBlock",fV);class DHe extends Li{constructor(e){super(e,Ee.VertexAndFragment,!0),this.registerInput("worldPosition",re.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([je(()=>Promise.resolve().then(()=>ibt),void 0),je(()=>Promise.resolve().then(()=>tbt),void 0),je(()=>Promise.resolve().then(()=>sbt),void 0),je(()=>Promise.resolve().then(()=>nbt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>Qxt),void 0),je(()=>Promise.resolve().then(()=>Yxt),void 0),je(()=>Promise.resolve().then(()=>Jxt),void 0),je(()=>Promise.resolve().then(()=>qxt),void 0)]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get target(){return Ee.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const n=e.getScene(),s=!!(t.clipPlane??n.clipPlane),a=!!(t.clipPlane2??n.clipPlane2),o=!!(t.clipPlane3??n.clipPlane3),l=!!(t.clipPlane4??n.clipPlane4),c=!!(t.clipPlane5??n.clipPlane5),u=!!(t.clipPlane6??n.clipPlane6);i.setValue("CLIPPLANE",s,!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 n=i.getScene();wo(e,t,n)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==Ee.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",re.Vector4),e._emitUniformFromString("vClipPlane2",re.Vector4),e._emitUniformFromString("vClipPlane3",re.Vector4),e._emitUniformFromString("vClipPlane4",re.Vector4),e._emitUniformFromString("vClipPlane5",re.Vector4),e._emitUniformFromString("vClipPlane6",re.Vector4);return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}xe("BABYLON.ClipPlanesBlock",DHe);class OHe extends Li{get texture(){return null}set texture(e){}constructor(e,t=Ee.VertexAndFragment){super(e,t,!1),this.registerOutput("position",re.Object,Ee.VertexAndFragment,new ka("position",this,1,U0,"ImageSourceBlock")),this.registerOutput("depth",re.Object,Ee.VertexAndFragment,new ka("depth",this,1,U0,"ImageSourceBlock")),this.registerOutput("normal",re.Object,Ee.VertexAndFragment,new ka("normal",this,1,U0,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:e===this._outputs[3]?this._worldNormalSamplerName:e===this._outputs[4]?this._localPositionSamplerName:e===this._outputs[5]?this._clipSpaceDepthSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get worldNormal(){return this._outputs[3]}get localPosition(){return this._outputs[4]}get clipSpaceDepth(){return this._outputs[5]}get positionSamplerName(){return this._positionSamplerName}get localPositionSamplerName(){return this._localPositionSamplerName}get normalSamplerName(){return this._normalSamplerName}get worldNormalSamplerName(){return this._worldNormalSamplerName}get depthSamplerName(){return this._depthSamplerName}get linearDepthSamplerName(){return this._clipSpaceDepthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==Ee.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",this._worldNormalSamplerName="prepassWorldNormalSampler",this._localPositionSamplerName="prepassLocalPositionSampler",this._clipSpaceDepthSamplerName="prepassClipSpaceDepthSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.variableNames.prepassWorldNormalSampler=0,e.sharedData.variableNames.prepassLocalPositionSampler=0,e.sharedData.variableNames.prepassClipSpaceDepthSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),e._emit2DSampler(this._worldNormalSamplerName),e._emit2DSampler(this._localPositionSamplerName),e._emit2DSampler(this._clipSpaceDepthSamplerName),this}bind(e,t){const n=t.getScene().enablePrePassRenderer();if(!n)return;const s=n.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[n.getIndex(1)]),this.localPosition.isConnected&&e.setTexture(this._localPositionSamplerName,s.textures[n.getIndex(9)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[n.getIndex(5)]),this.clipSpaceDepth.isConnected&&e.setTexture(this._clipSpaceDepthSamplerName,s.textures[n.getIndex(10)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[n.getIndex(6)]),this.worldNormal.isConnected&&e.setTexture(this._worldNormalSamplerName,s.textures[n.getIndex(8)]),this.localPosition.isConnected&&e.setTexture(this._localPositionSamplerName,s.textures[n.getIndex(9)]),this.clipSpaceDepth.isConnected&&e.setTexture(this._clipSpaceDepthSamplerName,s.textures[n.getIndex(10)]))}}xe("BABYLON.PrePassTextureBlock",OHe);class LHe extends Li{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==Ee.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Ee.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,Ee.Neutral),this._endpoints=[],this.registerInput("input",re.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 n of this.endpoints)t.indexOf(n)===-1&&(i+=n._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=[]}}xe("BABYLON.NodeMaterialTeleportInBlock",LHe);class NHe extends Li{constructor(e){super(e,Ee.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",re.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}}xe("BABYLON.NodeMaterialTeleportOutBlock",NHe);class FHe 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}}xe("BABYLON.AddBlock",FHe);class BHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("input",re.AutoDetect),this.registerInput("factor",re.Float),this.registerOutput("output",re.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}}xe("BABYLON.ScaleBlock",BHe);class Uee extends Li{constructor(e){super(e,Ee.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",re.AutoDetect),this.registerOutput("output",re.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}}V([Fi("Minimum",1)],Uee.prototype,"minimum",void 0);V([Fi("Maximum",1)],Uee.prototype,"maximum",void 0);xe("BABYLON.ClampBlock",Uee);class kHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(re.Float),this._inputs[0].excludedConnectionPointTypes.push(re.Matrix),this._inputs[0].excludedConnectionPointTypes.push(re.Vector2),this._inputs[1].excludedConnectionPointTypes.push(re.Float),this._inputs[1].excludedConnectionPointTypes.push(re.Matrix),this._inputs[1].excludedConnectionPointTypes.push(re.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}}xe("BABYLON.CrossBlock",kHe);class UHe extends Li{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(s=>{const a=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),o=e._getGLType(s.type);t=t.replace(a,o),i=i.replace(a,o)}),this._outputs.forEach(s=>{const a=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),o=e._getGLType(s.type);t=t.replace(a,o),i=i.replace(a,o)}),e._emitFunction(i,t,""),this._outputs.forEach(s=>{e.compilationString+=e._declareOutput(s)+`; `}),e.compilationString+=i+"(";let n=!1;return this._inputs.forEach((s,a)=>{var o,l;a>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(s.name)!==-1?e.compilationString+=((l=(o=s.connectedPoint)==null?void 0:o.ownerBlock)==null?void 0:l.samplerName)??s.associatedVariableName:e.compilationString+=s.associatedVariableName,n=!0}),this._outputs.forEach((s,a)=>{(a>0||n)&&(e.compilationString+=", "),e.compilationString+=s.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,n;this._options=e,this._code=e.code.join(` `)+` `,this.name=this.name||e.name,this.target=Ee[e.target],(t=e.inParameters)==null||t.forEach((s,a)=>{const o=re[s.type];s.type==="sampler2D"||s.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(s.name),this.registerInput(s.name,re.Object,!0,Ee.VertexAndFragment,new ka(s.name,this,0,U0,"ImageSourceBlock"))):this.registerInput(s.name,o),Object.defineProperty(this,s.name,{get:function(){return this._inputs[a]},enumerable:!0,configurable:!0})}),(i=e.outParameters)==null||i.forEach((s,a)=>{this.registerOutput(s.name,re[s.type]),Object.defineProperty(this,s.name,{get:function(){return this._outputs[a]},enumerable:!0,configurable:!0}),s.type==="BasedOnInput"&&(this._outputs[a]._typeConnectionSource=this._findInputByName(s.typeFromInput)[0])}),(n=e.inLinkedConnectionTypes)==null||n.forEach(s=>{this._linkConnectionTypes(this._findInputByName(s.input1)[1],this._findInputByName(s.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.CameraPosition&&t(n));i||(i=new Br("cameraPosition"),i.setAsSystemValue(Hr.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}}xe("BABYLON.ViewDirectionBlock",J_e);const BMt="fresnelFunction",kMt=`#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 `;me.IncludesShadersStore[BMt]=kMt;class XHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("worldNormal",re.Vector4),this.registerInput("viewDirection",re.Vector3),this.registerInput("bias",re.Float),this.registerInput("power",re.Float),this.registerOutput("fresnel",re.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 J_e("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new Br("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new Br("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}}xe("BABYLON.FresnelBlock",XHe);class YHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.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}}xe("BABYLON.MaxBlock",YHe);class QHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.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}}xe("BABYLON.MinBlock",QHe);class ZHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(re.Float),this._inputs[0].excludedConnectionPointTypes.push(re.Matrix),this._inputs[1].excludedConnectionPointTypes.push(re.Float),this._inputs[1].excludedConnectionPointTypes.push(re.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}}xe("BABYLON.DistanceBlock",ZHe);class qHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerOutput("output",re.Float),this._inputs[0].excludedConnectionPointTypes.push(re.Float),this._inputs[0].excludedConnectionPointTypes.push(re.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}}xe("BABYLON.LengthBlock",qHe);class JHe extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerOutput("output",re.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}}xe("BABYLON.NegateBlock",JHe);class eje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerInput("power",re.AutoDetect),this.registerOutput("output",re.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}}xe("BABYLON.PowBlock",eje);class tje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("seed",re.AutoDetect),this.registerOutput("output",re.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector2|re.Vector3|re.Vector4|re.Color3|re.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}}xe("BABYLON.RandomNumberBlock",tje);class ije extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("x",re.Float),this.registerInput("y",re.Float),this.registerOutput("output",re.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}}xe("BABYLON.ArcTan2Block",ije);class rje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerInput("edge0",re.Float),this.registerInput("edge1",re.Float),this.registerOutput("output",re.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}}xe("BABYLON.SmoothStepBlock",rje);class nje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("input",re.AutoDetect),this.registerOutput("output",re.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===re.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName}); `:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName}; `,this}}xe("BABYLON.ReciprocalBlock",nje);class sje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerInput("reference",re.AutoDetect),this.registerInput("distance",re.Float),this.registerInput("replacement",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(re.Float),this._inputs[0].excludedConnectionPointTypes.push(re.Matrix),this._inputs[1].excludedConnectionPointTypes.push(re.Float),this._inputs[1].excludedConnectionPointTypes.push(re.Matrix),this._inputs[3].excludedConnectionPointTypes.push(re.Float),this._inputs[3].excludedConnectionPointTypes.push(re.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}}xe("BABYLON.ReplaceColorBlock",sje);class aje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("value",re.AutoDetect),this.registerInput("steps",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(re.Matrix),this._inputs[1].excludedConnectionPointTypes.push(re.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(re.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}}xe("BABYLON.PosterizeBlock",aje);var Ade;(function(r){r[r.SawTooth=0]="SawTooth",r[r.Square=1]="Square",r[r.Triangle=2]="Triangle"})(Ade||(Ade={}));class oje extends Li{constructor(e){super(e,Ee.Neutral),this.kind=0,this.registerInput("input",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(re.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}}xe("BABYLON.WaveBlock",oje);class tQ{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 lje extends Li{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,Ee.Neutral),this.colorSteps=[new tQ(0,Pe.Black()),new tQ(1,Pe.White())],this.onValueChangedObservable=new Ce,this.registerInput("gradient",re.AutoDetect),this.registerOutput("output",re.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Float|re.Vector2|re.Vector3|re.Vector4|re.Color3|re.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(re.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.); `;return}const n=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(n,re.Vector3)} = ${this._writeColorConstant(0,i)}; `,e.compilationString+=`${e._declareLocalVar(s,re.Float)}; `;let a=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==re.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,re.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}}V([Fi("Use Manhattan Distance",0,"PROPERTIES",{notifiers:{update:!1}})],e2e.prototype,"manhattanDistance",void 0);xe("BABYLON.WorleyNoise3DBlock",e2e);class uje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("seed",re.Vector3),this.registerOutput("output",re.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}}xe("BABYLON.SimplexPerlin3DBlock",uje);class hje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("normalMap0",re.AutoDetect),this.registerInput("normalMap1",re.AutoDetect),this.registerOutput("output",re.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Color4|re.Vector3|re.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Color4|re.Vector3|re.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],n=this._inputs[1],s=e._getFreeVariableName("stepR"),a=e._getFreeVariableName("stepG");return e.compilationString+=`${e._declareLocalVar(s,re.Float)} = step(0.5, ${i.associatedVariableName}.r); `,e.compilationString+=`${e._declareLocalVar(a,re.Float)} = step(0.5, ${i.associatedVariableName}.g); `,e.compilationString+=e._declareOutput(t)+`; `,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${s}) * ${i.associatedVariableName}.r * ${n.associatedVariableName}.r * 2.0 + ${s} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${n.associatedVariableName}.r) * 2.0); `,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${a}) * ${i.associatedVariableName}.g * ${n.associatedVariableName}.g * 2.0 + ${a} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${n.associatedVariableName}.g) * 2.0); `,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${n.associatedVariableName}.b; `,this}}xe("BABYLON.NormalBlendBlock",hje);class dje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("input",re.Vector2),this.registerInput("angle",re.Float),this.registerOutput("output",re.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 Br("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.angle,n=this.input;return e.compilationString+=e._declareOutput(t)+` = vec2(cos(${i.associatedVariableName}) * ${n.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${n.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${n.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${n.associatedVariableName}.y); `,this}}xe("BABYLON.Rotate2dBlock",dje);class fje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("incident",re.AutoDetect),this.registerInput("normal",re.AutoDetect),this.registerOutput("output",re.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4|re.Color3|re.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4|re.Color3|re.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}}xe("BABYLON.ReflectBlock",fje);class pje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("incident",re.AutoDetect),this.registerInput("normal",re.AutoDetect),this.registerInput("ior",re.Float),this.registerOutput("output",re.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4|re.Color3|re.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(re.Vector3|re.Vector4|re.Color3|re.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}}xe("BABYLON.RefractBlock",pje);class mje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("color",re.Color3),this.registerInput("level",re.Float),this.registerOutput("output",re.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],n=this.color.associatedVariableName,s=e._getFreeVariableName("colorMin"),a=e._getFreeVariableName("colorMax"),o=e._getFreeVariableName("colorMerge");return e.compilationString+=`${e._declareLocalVar(s,re.Float)} = min(min(${n}.x, ${n}.y), ${n}.z); `,e.compilationString+=`${e._declareLocalVar(a,re.Float)} = max(max(${n}.x, ${n}.y), ${n}.z); `,e.compilationString+=`${e._declareLocalVar(o,re.Float)} = 0.5 * (${s} + ${a}); `,e.compilationString+=e._declareOutput(t)+` = mix(${n}, ${e._getShaderType(re.Vector3)}(${o}, ${o}, ${o}), ${this.level.associatedVariableName}); `,this}}xe("BABYLON.DesaturateBlock",mje);class hT extends Li{constructor(e){super(e,Ee.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",re.Float,!0,Ee.Fragment),this.registerInput("color",re.Color3,!0,Ee.Fragment),this.registerInput("roughness",re.Float,!0,Ee.Fragment),this.registerOutput("sheen",re.Object,Ee.Fragment,new ka("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 n=this.color.isConnected?this.color.associatedVariableName:`vec3${t.fSuffix}(1.)`,s=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",re.Vector4)} = vec4${t.fSuffix}(${n}, ${s}); 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===Ee.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}}V([Fi("Albedo scaling",0,"PROPERTIES",{notifiers:{update:!0}})],hT.prototype,"albedoScaling",void 0);V([Fi("Link sheen with albedo",0,"PROPERTIES",{notifiers:{update:!0}})],hT.prototype,"linkSheenWithAlbedo",void 0);xe("BABYLON.SheenBlock",hT);class pV extends Li{constructor(e){super(e,Ee.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",re.Float,!0,Ee.Fragment),this.registerInput("direction",re.Vector2,!0,Ee.Fragment),this.registerInput("uv",re.Vector2,!0),this.registerInput("worldTangent",re.Vector4,!0),this.registerInput("TBN",re.Object,!0,Ee.VertexAndFragment,new ka("TBN",this,0,uT,"TBNBlock")),this.registerInput("roughness",re.Float,!0,Ee.Fragment),this.registerOutput("anisotropy",re.Object,Ee.Fragment,new ka("anisotropy",this,1,pV,"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}`,n=this.uv,s=this.worldPositionConnectionPoint,a=this.worldNormalConnectionPoint,o=this.worldTangent,l=e.shaderLanguage===1;n.isConnected||ge.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",re.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,t+=`${e._declareLocalVar("tbnTangent",re.Vector3)} = normalize(${o.associatedVariableName}.xyz); `,t+=`${e._declareLocalVar("tbnBitangent",re.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_"+s.associatedVariableName+".xyz"}, ${n.isConnected?n.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 n=e.shaderLanguage===1,s=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+=`${n?"var anisotropicOut: anisotropicOutParams":"anisotropicOutParams anisotropicOut"}; anisotropicOut = anisotropicBlock( vec3(${a}, ${s}), ${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===Ee.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,re.Float)),this}}xe("BABYLON.AnisotropyBlock",pV);class dT extends dw{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ge.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?Ee.Fragment:Ee.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",re.AutoDetect,!1,Ee.Vertex),this.registerInput("world",re.Matrix,!1,Ee.Vertex),this.registerInput("color",re.Color3,!0,Ee.Fragment),this.registerOutput("reflection",re.Object,Ee.Fragment,new ka("reflection",this,1,dT,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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 n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!n.invertZ:n.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",n.gammaSpace,!0),i.setValue("RGBDREFLECTION",n.isRGBD,!0),n&&n.coordinatesMode!==be.SKYBOX_MODE&&n.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,n){super.bind(e,t,i);const s=this._getTexture();if(!s||!n)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);const a=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,a,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,a,Xt.Log2(a));const o=n.materialDefines,l=s.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 n=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,re.Vector3,"defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22",re.Vector3,"SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ",re.Vector3,"SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX",re.Vector3,"SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) ${e._declareLocalVar(n,re.Vector3)} = (${(i?"uniforms.":"")+this._reflectionMatrixName} * vec4${e.fSuffix}(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; #ifdef ${this._defineOppositeZ} ${n}.z *= -1.0; #endif ${i?"vertexOutputs.":""}${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${n}); #endif `,t}getCode(e,t){let i="";this.handleFragmentSideInits(e);const n=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:""}]}),n||(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 s=n?` 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",s,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,re.Vector3),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,re.Vector2),i+=`#ifdef REFLECTION ${e._declareLocalVar(this._vReflectionInfosName,re.Vector2)} = vec2${e.fSuffix}(1., 0.); ${n?"var reflectionOut: reflectionOutParams":"reflectionOutParams reflectionOut"}; reflectionOut = reflectionBlock( ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:(n?"input.":"")+"v_"+this.worldPosition.associatedVariableName}.xyz , ${t} , alphaG , ${(n?"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} ${n?`, ${this._cubeSamplerName}Sampler`:""} #else , ${this._2DSamplerName} ${n?`, ${this._2DSamplerName}Sampler`:""} #endif #if defined(NORMAL) && defined(USESPHERICALINVERTEX) , ${n?"input.":""}${this._vEnvironmentIrradianceName} #endif #ifdef USESPHERICALFROMREFLECTIONMAP #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) , ${this._reflectionMatrixName} #endif #endif #ifdef USEIRRADIANCEMAP , irradianceSampler // ** not handled ** ${n?", irradianceSamplerSampler":""} #endif #ifndef LODBASEDMICROSFURACE #ifdef ${this._define3DName} , ${this._cubeSamplerName} ${n?`, ${this._cubeSamplerName}Sampler`:""} , ${this._cubeSamplerName} ${n?`, ${this._cubeSamplerName}Sampler`:""} #else , ${this._2DSamplerName} ${n?`, ${this._2DSamplerName}Sampler`:""} , ${this._2DSamplerName} ${n?`, ${this._2DSamplerName}Sampler`:""} #endif #endif #ifdef REALTIME_FILTERING , ${this._vReflectionFilteringInfoName} #endif ); #endif `,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==Ee.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)}}V([Fi("Spherical Harmonics",0,"ADVANCED",{notifiers:{update:!0}})],dT.prototype,"useSphericalHarmonics",void 0);V([Fi("Force irradiance in fragment",0,"ADVANCED",{notifiers:{update:!0}})],dT.prototype,"forceIrradianceInFragment",void 0);xe("BABYLON.ReflectionBlock",dT);class lE extends Li{constructor(e){super(e,Ee.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",re.Float,!1,Ee.Fragment),this.registerInput("roughness",re.Float,!0,Ee.Fragment),this.registerInput("indexOfRefraction",re.Float,!0,Ee.Fragment),this.registerInput("normalMapColor",re.Color3,!0,Ee.Fragment),this.registerInput("uv",re.Vector2,!0,Ee.Fragment),this.registerInput("tintColor",re.Color3,!0,Ee.Fragment),this.registerInput("tintAtDistance",re.Float,!0,Ee.Fragment),this.registerInput("tintThickness",re.Float,!0,Ee.Fragment),this.registerInput("worldTangent",re.Vector4,!0),this.registerInput("worldNormal",re.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(re.Color4|re.Vector4|re.Vector3),this.registerInput("TBN",re.Object,!0,Ee.VertexAndFragment,new ka("TBN",this,0,uT,"TBNBlock")),this.registerOutput("clearcoat",re.Object,Ee.Fragment,new ka("clearcoat",this,1,lE,"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 Br("ClearCoat intensity",Ee.Fragment,re.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===Ll._DefaultIndexOfRefraction:!0,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var h;super.bind(e,t,i);const n=((h=this.indexOfRefraction.connectInputBlock)==null?void 0:h.value)??Ll._DefaultIndexOfRefraction,s=1-n,a=1+n,o=Math.pow(-s/a,2),l=1/n;e.setFloat4("vClearCoatRefractionParams",o,l,s,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 n="";const s=`//${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&&(n+=`${e._declareLocalVar("tbnNormal",re.Vector3)} = normalize(${i}.xyz); `,n+=`${e._declareLocalVar("tbnTangent",re.Vector3)} = normalize(${a.associatedVariableName}.xyz); `,n+=`${e._declareLocalVar("tbnBitangent",re.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; `,n+=`${o?"var vTBN":"mat3 vTBN"} = ${o?"mat3x3f":"mat3"}(tbnTangent, tbnBitangent, tbnNormal); `),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[l]}),n}static GetCode(e,t,i,n,s,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.",g=t!=null&&t.tintAtDistance.isConnected?t.tintAtDistance.associatedVariableName:"1.",m=`vec4${e.fSuffix}(0.)`;if(t){e._emitUniformFromString("vClearCoatRefractionParams",re.Vector4),e._emitUniformFromString("vClearCoatTangentSpaceParams",re.Vector2);const y=t.worldNormal;l+=`${e._declareLocalVar("vGeometricNormaClearCoatW",re.Vector3)} = ${y.isConnected?"normalize("+y.associatedVariableName+".xyz)":"geometricNormalW"}; `}else l+=`${e._declareLocalVar("vGeometricNormaClearCoatW",re.Vector3)} = geometricNormalW; `;s&&t&&(l+=t._generateTBNSpace(e,n,o),a=t.worldTangent.isConnected);const _=e.shaderLanguage===1;return l+=`${_?"var clearcoatOut: clearcoatOutParams":"clearcoatOutParams clearcoatOut"}; #ifdef CLEARCOAT ${e._declareLocalVar("vClearCoatParams",re.Vector2)} = vec2${e.fSuffix}(${c}, ${u}); ${e._declareLocalVar("vClearCoatTintParams",re.Vector4)} = vec4${e.fSuffix}(${f}, ${p}); clearcoatOut = clearcoatBlock( ${n}.xyz , vGeometricNormaClearCoatW , viewDirectionW , vClearCoatParams , specularEnvironmentR0 #ifdef CLEARCOAT_TEXTURE , vec2${e.fSuffix}(0.) #endif #ifdef CLEARCOAT_TINT , vClearCoatTintParams , ${g} , ${_?"uniforms.":""}vClearCoatRefractionParams #ifdef CLEARCOAT_TINT_TEXTURE , ${m} #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===Ee.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,re.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}}V([Fi("Remap F0 on interface change",0,"ADVANCED")],lE.prototype,"remapF0OnInterfaceChange",void 0);xe("BABYLON.ClearCoatBlock",lE);class nU extends Li{constructor(e){super(e,Ee.Fragment),this._isUnique=!0,this.registerInput("intensity",re.Float,!0,Ee.Fragment),this.registerInput("indexOfRefraction",re.Float,!0,Ee.Fragment),this.registerInput("thickness",re.Float,!0,Ee.Fragment),this.registerOutput("iridescence",re.Object,Ee.Fragment,new ka("iridescence",this,1,nU,"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 Br("Iridescence intensity",Ee.Fragment,re.Float);e.value=1,e.output.connectTo(this.intensity);const t=new Br("Iridescence ior",Ee.Fragment,re.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new Br("Iridescence thickness",Ee.Fragment,re.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 n=e!=null&&e.intensity.isConnected?e.intensity.associatedVariableName:"1.",s=e!=null&&e.indexOfRefraction.isConnected?e.indexOfRefraction.associatedVariableName:Cu._DefaultIndexOfRefraction,a=e!=null&&e.thickness.isConnected?e.thickness.associatedVariableName:Cu._DefaultMaximumThickness,o=t.shaderLanguage===1;return i+=`${o?"var iridescenceOut: iridescenceOutParams":"iridescenceOutParams iridescenceOut"}; #ifdef IRIDESCENCE iridescenceOut = iridescenceBlock( vec4(${n}, ${s}, 1., ${a}) , NdotV , specularEnvironmentR0 #ifdef CLEARCOAT , NdotVUnclamped #endif ); float iridescenceIntensity = iridescenceOut.iridescenceIntensity; specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; #endif `,i}_buildBlock(e){return e.target===Ee.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)}}xe("BABYLON.IridescenceBlock",nU);class ab extends Li{constructor(e){super(e,Ee.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",re.Float,!1,Ee.Fragment),this.registerInput("tintAtDistance",re.Float,!0,Ee.Fragment),this.registerInput("volumeIndexOfRefraction",re.Float,!0,Ee.Fragment),this.registerOutput("refraction",re.Object,Ee.Fragment,new ka("refraction",this,1,ab,"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 Br("Refraction intensity",Ee.Fragment,re.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.View&&t(n));i||(i=new Br("view"),i.setAsSystemValue(Hr.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLODRefractionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",n.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",n.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!n.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 n=this._getTexture();if(!n)return;n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),e.setMatrix(this._refractionMatrixName,n.getRefractionTextureMatrix());let s=1;n.isCube||n.depth&&(s=n.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,n.level,1/a,s,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,n.getSize().width,n.lodGenerationScale,n.lodGenerationOffset,1/a);const o=n.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,Xt.Log2(o)),n.boundingBoxSize){const u=n;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,re.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,re.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,re.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,re.Vector2),e._emitUniformFromString("vRefractionPosition",re.Vector3),e._emitUniformFromString("vRefractionSize",re.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=Za.Parse(e.texture,t,i):this.texture=be.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}V([Fi("Link refraction to transparency",0,"ADVANCED",{notifiers:{update:!0}})],ab.prototype,"linkRefractionWithTransparency",void 0);V([Fi("Invert refraction Y",0,"ADVANCED",{notifiers:{update:!0}})],ab.prototype,"invertRefractionY",void 0);V([Fi("Use thickness as depth",0,"ADVANCED",{notifiers:{update:!0}})],ab.prototype,"useThicknessAsDepth",void 0);xe("BABYLON.RefractionBlock",ab);class fw extends Li{constructor(e){super(e,Ee.Fragment),this._isUnique=!0,this.registerInput("thickness",re.Float,!1,Ee.Fragment),this.registerInput("tintColor",re.Color3,!0,Ee.Fragment),this.registerInput("translucencyIntensity",re.Float,!0,Ee.Fragment),this.registerInput("translucencyDiffusionDist",re.Color3,!0,Ee.Fragment),this.registerInput("refraction",re.Object,!0,Ee.Fragment,new ka("refraction",this,0,ab,"RefractionBlock")),this.registerInput("dispersion",re.Float,!0,Ee.Fragment),this.registerOutput("subsurface",re.Object,Ee.Fragment,new ka("subsurface",this,1,fw,"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 Br("SubSurface thickness",Ee.Fragment,re.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",n||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",n,!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,n){var m;let s="";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?(m=t==null?void 0:t.refraction.connectedPoint)==null?void 0:m.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",g=e.shaderLanguage===1;return s+=(u==null?void 0:u.getCode(e))??"",s+=`${g?"var subSurfaceOut: subSurfaceOutParams":"subSurfaceOutParams subSurfaceOut"}; #ifdef SUBSURFACE ${e._declareLocalVar("vThicknessParam",re.Vector2)} = vec2${e.fSuffix}(0., ${a}); ${e._declareLocalVar("vTintColor",re.Vector4)} = vec4${e.fSuffix}(${o}, ${h}); ${e._declareLocalVar("vSubSurfaceIntensity",re.Vector3)} = vec3(${d}, ${l}, 0.); ${e._declareLocalVar("dispersion",re.Float)} = ${p}; subSurfaceOut = subSurfaceBlock( vSubSurfaceIntensity , vThicknessParam , vTintColor , normalW , specularEnvironmentReflectance #ifdef SS_THICKNESSANDMASK_TEXTURE , vec4${e.fSuffix}(0.) #endif #ifdef REFLECTION #ifdef SS_TRANSLUCENCY , ${(g?"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} ${g?`, ${i==null?void 0:i._cubeSamplerName}Sampler`:""} , ${i==null?void 0:i._vReflectionFilteringInfoName} #endif #endif #ifdef USEIRRADIANCEMAP , irradianceSampler ${g?", irradianceSamplerSampler":""} #endif #endif #endif #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) , surfaceAlbedo #endif #ifdef SS_REFRACTION , ${n}.xyz , viewDirectionW , ${f} , ${(g?"uniforms.":"")+(u==null?void 0:u._vRefractionInfosName)} , ${(g?"uniforms.":"")+(u==null?void 0:u._refractionMatrixName)} , ${(g?"uniforms.":"")+(u==null?void 0:u._vRefractionMicrosurfaceInfosName)} , ${g?"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)??""} ${g?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} #else , ${(u==null?void 0:u._2DSamplerName)??""} ${g?`, ${u==null?void 0:u._2DSamplerName}Sampler`:""} #endif #ifndef LODBASEDMICROSFURACE #ifdef ${(u==null?void 0:u._define3DName)??"IGNORE"} , ${(u==null?void 0:u._cubeSamplerName)??""} ${g?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} , ${(u==null?void 0:u._cubeSamplerName)??""} ${g?`, ${u==null?void 0:u._cubeSamplerName}Sampler`:""} #else , ${(u==null?void 0:u._2DSamplerName)??""} ${g?`, ${u==null?void 0:u._2DSamplerName}Sampler`:""} , ${(u==null?void 0:u._2DSamplerName)??""} ${g?`, ${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 `,s}_buildBlock(e){return e.target===Ee.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}xe("BABYLON.SubSurfaceBlock",fw);const UMt={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 Fl extends Li{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,ge.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Ee.Fragment:Ee.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Ee.Fragment:Ee.Vertex}constructor(e){super(e,Ee.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Pe.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",re.Vector4,!1,Ee.Vertex),this.registerInput("worldNormal",re.Vector4,!1,Ee.Vertex),this.registerInput("view",re.Matrix,!1),this.registerInput("cameraPosition",re.Vector3,!1,Ee.Fragment),this.registerInput("perturbedNormal",re.Vector4,!0,Ee.Fragment),this.registerInput("baseColor",re.Color3,!0,Ee.Fragment),this.registerInput("metallic",re.Float,!1,Ee.Fragment),this.registerInput("roughness",re.Float,!1,Ee.Fragment),this.registerInput("ambientOcc",re.Float,!0,Ee.Fragment),this.registerInput("opacity",re.Float,!0,Ee.Fragment),this.registerInput("indexOfRefraction",re.Float,!0,Ee.Fragment),this.registerInput("ambientColor",re.Color3,!0,Ee.Fragment),this.registerInput("reflection",re.Object,!0,Ee.Fragment,new ka("reflection",this,0,dT,"ReflectionBlock")),this.registerInput("clearcoat",re.Object,!0,Ee.Fragment,new ka("clearcoat",this,0,lE,"ClearCoatBlock")),this.registerInput("sheen",re.Object,!0,Ee.Fragment,new ka("sheen",this,0,hT,"SheenBlock")),this.registerInput("subsurface",re.Object,!0,Ee.Fragment,new ka("subsurface",this,0,fw,"SubSurfaceBlock")),this.registerInput("anisotropy",re.Object,!0,Ee.Fragment,new ka("anisotropy",this,0,pV,"AnisotropyBlock")),this.registerInput("iridescence",re.Object,!0,Ee.Fragment,new ka("iridescence",this,0,nU,"IridescenceBlock")),this.registerOutput("ambientClr",re.Color3,Ee.Fragment),this.registerOutput("diffuseDir",re.Color3,Ee.Fragment),this.registerOutput("specularDir",re.Color3,Ee.Fragment),this.registerOutput("clearcoatDir",re.Color3,Ee.Fragment),this.registerOutput("sheenDir",re.Color3,Ee.Fragment),this.registerOutput("diffuseInd",re.Color3,Ee.Fragment),this.registerOutput("specularInd",re.Color3,Ee.Fragment),this.registerOutput("clearcoatInd",re.Color3,Ee.Fragment),this.registerOutput("sheenInd",re.Color3,Ee.Fragment),this.registerOutput("refraction",re.Color3,Ee.Fragment),this.registerOutput("lighting",re.Color3,Ee.Fragment),this.registerOutput("shadow",re.Float,Ee.Fragment),this.registerOutput("alpha",re.Float,Ee.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([je(()=>Promise.resolve().then(()=>dKe),void 0),je(()=>Promise.resolve().then(()=>EKe),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>IKe),void 0),je(()=>Promise.resolve().then(()=>GKe),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(n=>n.systemValue===Hr.CameraPosition&&t(n));i||(i=new Br("cameraPosition"),i.setAsSystemValue(Hr.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(n=>n.systemValue===Hr.View&&t(n));i||(i=new Br("view"),i.setAsSystemValue(Hr.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===an.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===an.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const n=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",n.indexOf(".")<0?n+".":n,!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 s=e.getScene();if(s.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&<.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)Xu(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,rD(s,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};wz(s,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;Oz(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,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 n=i.getScene();this.light?Pz(this.light,this._lightId,n,e,!0):$u(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const s=this._scene.ambientColor;s&&e.setColor3("ambientFromScene",s);const a=n.useRightHandedSystem===(n._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,En.Color3[0]);const u=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,En.Color3[0],u),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var c;const t=this.worldPosition,i=this.worldNormal,n=`//${this.name}`,s=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",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",n,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const a="v_"+t.associatedVariableName;e._emitVaryingFromString(a,re.Vector4)&&(e.compilationString+=(s?"vertexOutputs.":"")+`${a} = ${t.associatedVariableName}; `);const o="v_"+i.associatedVariableName;e._emitVaryingFromString(o,re.Vector4)&&(e.compilationString+=(s?"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",re.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 `,e._injectAtEnd+=(s?"vertexOutputs.":"")+`vClipSpacePosition = ${s?"vertexOutputs.position":"gl_Position"}; `,e._injectAtEnd+=`#endif `),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",re.Vector4)} = ${t.associatedVariableName}; `,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",re.Matrix)} = ${this.view.associatedVariableName}; `),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",n,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(e){let i=e.shaderLanguage===1?`var albedoOpacityOut: albedoOpacityOutParams; `:`albedoOpacityOutParams albedoOpacityOut; `;const n=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",s=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return i+=`albedoOpacityOut = albedoOpacityBlock( vec4${e.fSuffix}(${n}, 1.) #ifdef ALBEDO ,vec4${e.fSuffix}(1.) ,vec2${e.fSuffix}(1., 1.) #endif #ifdef OPACITY ,vec4${e.fSuffix}(${s}) ,vec2${e.fSuffix}(1., 1.) #endif ); ${e._declareLocalVar("surfaceAlbedo",re.Vector3)} = albedoOpacityOut.surfaceAlbedo; ${e._declareLocalVar("alpha",re.Float)} = albedoOpacityOut.alpha; `,i}_getAmbientOcclusionCode(e){let i=e.shaderLanguage===1?`var aoOut: ambientOcclusionOutParams; `:`ambientOcclusionOutParams aoOut; `;const n=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return i+=`aoOut = ambientOcclusionBlock( #ifdef AMBIENT vec3${e.fSuffix}(${n}), 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 n="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,re.Vector4),i+=`${e._declareLocalVar("baseColor",re.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., ${n}) , vec4${e.fSuffix}(1.) #endif #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) , aoOut.ambientOcclusionColor #endif #ifdef MICROSURFACEMAP , microSurfaceTexel <== not handled! #endif ); ${e._declareLocalVar("microSurface",re.Float)} = reflectivityOut.microSurface; ${e._declareLocalVar("roughness",re.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 C,A,E,P,w,M,R,I,D,k,z;super._buildBlock(e),this._scene=e.sharedData.scene;const t=e.shaderLanguage===1;this._environmentBRDFTexture||(this._environmentBRDFTexture=oV(this._scene));const i=this.reflection.isConnected?(C=this.reflection.connectedPoint)==null?void 0:C.ownerBlock:null;if(i&&(i.worldPositionConnectionPoint=this.worldPosition,i.cameraPositionConnectionPoint=this.cameraPosition,i.worldNormalConnectionPoint=this.worldNormal,i.viewConnectionPoint=this.view),e.target!==Ee.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 n=`//${this.name}`,s=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",n,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 `,e.compilationString+=`${e._declareLocalVar("vClipSpacePosition",re.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",re.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",re.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",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",n,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",n),e._emitFunctionFromInclude("importanceSampling",n),e._emitFunctionFromInclude("pbrHelperFunctions",n),e._emitFunctionFromInclude("imageProcessingDeclaration",n),e._emitFunctionFromInclude("imageProcessingFunctions",n),e._emitFunctionFromInclude("shadowsFragmentFunctions",n),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",n),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",n),e._emitFunctionFromInclude("pbrBRDFFunctions",n,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(i==null?void 0:i._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",n),e._emitFunctionFromInclude("pbrDirectLightingFunctions",n),e._emitFunctionFromInclude("pbrIBLFunctions",n),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",n),e._emitFunctionFromInclude("pbrBlockReflectivity",n),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",n),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",n),e._emitFunctionFromInclude("pbrBlockAnisotropic",n),e._emitUniformFromString("vLightingIntensity",re.Vector4),i!=null&&i.generateOnlyFragmentCode&&(e.compilationString+=i.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`${e._declareLocalVar(this._vNormalWName,re.Vector4)} = normalize(${o}); `,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",re.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${a}.xyz); `),e.compilationString+=`${e._declareLocalVar("geometricNormalW",re.Vector3)} = ${this._vNormalWName}.xyz; `,e.compilationString+=`${e._declareLocalVar("normalW",re.Vector3)} = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"}; `,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,re.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",n,{replaceStrings:[{search:/vPositionW/g,replace:a+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(e),e.compilationString+=e._emitCodeFromInclude("depthPrePass",n),e.compilationString+=this._getAmbientOcclusionCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",n),e.compilationString+=`#ifdef UNLIT ${e._declareLocalVar("diffuseBase",re.Vector3)} = vec3${e.fSuffix}(1., 1., 1.); #else `,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",n,{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?(A=this.anisotropy.connectedPoint)==null?void 0:A.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",n,{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",n,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}]});const c=this.sheen.isConnected?(E=this.sheen.connectedPoint)==null?void 0:E.ownerBlock:null;c&&(e.compilationString+=c.getCode(i,e)),e._emitFunctionFromInclude("pbrBlockSheen",n,{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?(P=this.iridescence.connectedPoint)==null?void 0:P.ownerBlock:null;e.compilationString+=nU.GetCode(u,e),e._emitFunctionFromInclude("pbrBlockIridescence",n,{replaceStrings:[]});const h=this.clearcoat.isConnected?(w=this.clearcoat.connectedPoint)==null?void 0:w.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 g=f||!this.perturbedNormal.isConnected&&p;e.compilationString+=lE.GetCode(e,h,i,a,d,g,o),d&&(g=(h==null?void 0:h.worldTangent.isConnected)??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",n,{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:g?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",n,{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 m=this.subsurface.isConnected?(D=this.subsurface.connectedPoint)==null?void 0:D.ownerBlock:null,_=this.subsurface.isConnected?(z=((k=this.subsurface.connectedPoint)==null?void 0:k.ownerBlock).refraction.connectedPoint)==null?void 0:z.ownerBlock:null;_&&(_.viewConnectionPoint=this.view,_.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=fw.GetCode(e,m,i,a),e._emitFunctionFromInclude("pbrBlockSubSurface",n,{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",n),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:new RegExp(`${t?"input.":""}vPositionW`,"g"),replace:a+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",n,{repeatKey:"maxSimultaneousLights",substitutionVars:`${t?"input.":""}vPositionW,${a}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",n),e.compilationString+=`#endif `;const y=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:`vec3${e.fSuffix}(0., 0., 0.)`;let v=an.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",n,{replaceStrings:x}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",n,{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",n,{replaceStrings:x});const b=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.); ${b}.rgb = toGammaSpace(${b}.rgb); `}],e.compilationString+=e._emitCodeFromInclude("pbrDebug",n,{replaceStrings:x});for(const W of this._outputs)if(W.hasEndpoints){const K=UMt[W.name];if(K){const[U,j]=K;j&&(e.compilationString+=`#if ${j} `),e.compilationString+=`${e._declareOutput(W)} = ${U}; `,j&&(e.compilationString+=`#else `,e.compilationString+=`${e._declareOutput(W)} = vec3${e.fSuffix}(0.); `,e.compilationString+=`#endif `)}else ge.Error(`There's no remapping for the ${W.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()}}V([Fi("Direct lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Fl.prototype,"directIntensity",void 0);V([Fi("Environment lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Fl.prototype,"environmentIntensity",void 0);V([Fi("Specular highlights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Fl.prototype,"specularIntensity",void 0);V([Fi("Light falloff",4,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:an.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:an.LIGHTFALLOFF_GLTF},{label:"Standard",value:an.LIGHTFALLOFF_STANDARD}]})],Fl.prototype,"lightFalloff",void 0);V([Fi("Alpha Testing",0,"OPACITY")],Fl.prototype,"useAlphaTest",void 0);V([Fi("Alpha CutOff",1,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],Fl.prototype,"alphaTestCutoff",void 0);V([Fi("Alpha blending",0,"OPACITY")],Fl.prototype,"useAlphaBlending",void 0);V([Fi("Radiance over alpha",0,"RENDERING",{notifiers:{update:!0}})],Fl.prototype,"useRadianceOverAlpha",void 0);V([Fi("Specular over alpha",0,"RENDERING",{notifiers:{update:!0}})],Fl.prototype,"useSpecularOverAlpha",void 0);V([Fi("Specular anti-aliasing",0,"RENDERING",{notifiers:{update:!0}})],Fl.prototype,"enableSpecularAntiAliasing",void 0);V([Fi("Realtime filtering",0,"RENDERING",{notifiers:{update:!0}})],Fl.prototype,"realTimeFiltering",void 0);V([Fi("Realtime filtering quality",4,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],Fl.prototype,"realTimeFilteringQuality",void 0);V([Fi("Energy Conservation",0,"ADVANCED",{notifiers:{update:!0}})],Fl.prototype,"useEnergyConservation",void 0);V([Fi("Radiance occlusion",0,"ADVANCED",{notifiers:{update:!0}})],Fl.prototype,"useRadianceOcclusion",void 0);V([Fi("Horizon occlusion",0,"ADVANCED",{notifiers:{update:!0}})],Fl.prototype,"useHorizonOcclusion",void 0);V([Fi("Unlit",0,"ADVANCED",{notifiers:{update:!0}})],Fl.prototype,"unlit",void 0);V([Fi("Force normal forward",0,"ADVANCED",{notifiers:{update:!0}})],Fl.prototype,"forceNormalForward",void 0);V([Fi("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Fl._OnGenerateOnlyFragmentCodeChanged}})],Fl.prototype,"generateOnlyFragmentCode",void 0);V([Fi("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}]})],Fl.prototype,"debugMode",void 0);V([Fi("Split position",1,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],Fl.prototype,"debugLimit",void 0);V([Fi("Output factor",1,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],Fl.prototype,"debugFactor",void 0);xe("BABYLON.PBRMetallicRoughnessBlock",Fl);class gje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("left",re.AutoDetect),this.registerInput("right",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(re.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}}xe("BABYLON.ModBlock",gje);class _je extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("row0",re.Vector4),this.registerInput("row1",re.Vector4),this.registerInput("row2",re.Vector4),this.registerInput("row3",re.Vector4),this.registerOutput("output",re.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 Br("row0");e.value=new It(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Br("row1");e.value=new It(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Br("row2");e.value=new It(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Br("row3");e.value=new It(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,n=this.row1,s=this.row2,a=this.row3,o=e.shaderLanguage===1?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${n.associatedVariableName}, ${s.associatedVariableName}, ${a.associatedVariableName}); `,this}}xe("BABYLON.MatrixBuilder",_je);var nf;(function(r){r[r.Equal=0]="Equal",r[r.NotEqual=1]="NotEqual",r[r.LessThan=2]="LessThan",r[r.GreaterThan=3]="GreaterThan",r[r.LessOrEqual=4]="LessOrEqual",r[r.GreaterOrEqual=5]="GreaterOrEqual",r[r.Xor=6]="Xor",r[r.Or=7]="Or",r[r.And=8]="And"})(nf||(nf={}));class vje extends Li{constructor(e){super(e,Ee.Neutral),this.condition=nf.LessThan,this.registerInput("a",re.Float),this.registerInput("b",re.Float),this.registerInput("true",re.AutoDetect,!0),this.registerInput("false",re.AutoDetect,!0),this.registerOutput("output",re.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=re.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",n=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case nf.Equal:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)}; `;break}case nf.NotEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)}; `;break}case nf.LessThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)}; `;break}case nf.LessOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)}; `;break}case nf.GreaterThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)}; `;break}case nf.GreaterOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)}; `;break}case nf.Xor:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)}; `;break}case nf.Or:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)}; `;break}case nf.And:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,n,`(${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.${nf[this.condition]}; `}}xe("BABYLON.ConditionalBlock",vje);class t2e extends Li{constructor(e){super(e,Ee.Neutral),this.octaves=6,this.registerInput("seed",re.AutoDetect),this.registerInput("chaos",re.AutoDetect,!0),this.registerInput("offsetX",re.Float,!0),this.registerInput("offsetY",re.Float,!0),this.registerInput("offsetZ",re.Float,!0),this.registerOutput("output",re.Float),this._inputs[0].acceptedConnectionPointTypes.push(re.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(re.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 n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,n).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const s=e._getFreeVariableName("st"),a=((l=this.seed.connectedPoint)==null?void 0:l.type)||re.Vector3;e.compilationString+=`${e._declareLocalVar(s,a)} = ${this.seed.associatedVariableName}; `,this.offsetX.isConnected&&(e.compilationString+=`${s}.x += 0.1 * ${this.offsetX.associatedVariableName}; `),this.offsetY.isConnected&&(e.compilationString+=`${s}.y += 0.1 * ${this.offsetY.associatedVariableName}; `),this.offsetZ.isConnected&&a===re.Vector3&&(e.compilationString+=`${s}.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)===re.Vector2?`vec2${h}(0., 0.)`:`vec3${h}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${n}${((u=this.seed.connectedPoint)==null?void 0:u.type)===re.Vector2?"2":"3"}(${s}, ${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}}V([Fi("Octaves",2)],t2e.prototype,"octaves",void 0);xe("BABYLON.CloudBlock",t2e);class yje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("seed",re.Vector2),this.registerInput("offset",re.Float),this.registerInput("density",re.Float),this.registerOutput("output",re.Float),this.registerOutput("cells",re.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()??ei.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()??ei.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,Ee.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",re.AutoDetect,!1),this.registerInput("normal",re.AutoDetect,!1),this.registerInput("sharpness",re.Float,!0),this.registerInput("source",re.Object,!0,Ee.VertexAndFragment,new ka("source",this,0,U0,"ImageSourceBlock")),this.registerInput("sourceY",re.Object,!0,Ee.VertexAndFragment,new ka("sourceY",this,0,U0,"ImageSourceBlock")),t||this.registerInput("sourceZ",re.Object,!0,Ee.VertexAndFragment,new ka("sourceZ",this,0,U0,"ImageSourceBlock")),this.registerOutput("rgba",re.Color4,Ee.Neutral),this.registerOutput("rgb",re.Color3,Ee.Neutral),this.registerOutput("r",re.Float,Ee.Neutral),this.registerOutput("g",re.Float,Ee.Neutral),this.registerOutput("b",re.Float,Ee.Neutral),this.registerOutput("a",re.Float,Ee.Neutral),this.registerOutput("level",re.Float,Ee.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(re.Color3|re.Vector3|re.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 n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!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,n=this.samplerZName??t,s=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,re.Vector3)} = ${this.normal.associatedVariableName}.xyz; ${e._declareLocalVar(h,re.Vector2)} = ${this.position.associatedVariableName}.yz; ${e._declareLocalVar(d,re.Vector2)} = ${this.position.associatedVariableName}.zx; ${e._declareLocalVar(f,re.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,re.Vector4)} = ${this._generateTextureSample(t,h,e)}; ${e._declareLocalVar(o,re.Vector4)} = ${this._generateTextureSample(i,d,e)}; ${e._declareLocalVar(l,re.Vector4)} = ${this._generateTextureSample(n,f,e)}; // blend weights ${e._declareLocalVar(c,re.Vector3)} = pow(abs(${u}), vec3${p}(${s})); // blend and return ${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = (${a}*${c}.x + ${o}*${c}.y + ${l}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); `}_generateConversionCode(e,t,i){let n="";e.shaderLanguage===1&&(t.type===re.Vector3||t.type===re.Color3)&&(n="Vec3"),i!=="a"&&((!this.texture||!this.texture.gammaSpace)&&(e.compilationString+=`#ifdef ${this._linearDefineName} ${t.associatedVariableName} = toGammaSpace${n}(${t.associatedVariableName}); #endif `),e.compilationString+=`#ifdef ${this._gammaDefineName} ${t.associatedVariableName} = toLinearSpace${n}(${t.associatedVariableName}); #endif `)}_writeOutput(e,t,i){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){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,re.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&&!Yn.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=be.Parse(e.texture,t,i))}}V([Fi("Project as cube",0,"ADVANCED",{notifiers:{update:!0}})],zee.prototype,"projectAsCube",void 0);xe("BABYLON.TriPlanarBlock",zee);class bje extends zee{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,n=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",s=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",g="dFdx",m="dFdy";const _=e.fSuffix;e.shaderLanguage===1&&(p="vec3",g="dpdx",m="dpdy"),e.compilationString+=` // grab coord derivatives for texturing ${e._declareLocalVar(s,re.Vector3)} = ${g}(${this.position.associatedVariableName}.xyz); ${e._declareLocalVar(a,re.Vector3)} = ${m}(${this.position.associatedVariableName}.xyz); ${e._declareLocalVar(o,re.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,re.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${_}(${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), vec2${_}(${s}[${l}.y],${s}[${l}.z]), vec2${_}(${a}[${l}.y],${a}[${l}.z])); ${e._declareLocalVar(d,re.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${_}(${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), vec2${_}(${s}[${u}.y],${s}[${u}.z]), vec2${_}(${a}[${u}.y],${a}[${u}.z])); // blend factors ${e._declareLocalVar(f,re.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${_}(${n}/8.0) ); // blend and return ${e._declareLocalVar(this._tempTextureRead,re.Vector4)} = (${h}*${f}.x + ${d}*${f}.y) / (${f}.x + ${f}.y); `}}xe("BABYLON.BiPlanarBlock",bje);class Cje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("input",re.Matrix),this.registerOutput("output",re.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}}xe("BABYLON.MatrixDeterminantBlock",Cje);class Aje extends Li{constructor(e){super(e,Ee.Neutral),this.registerInput("input",re.Matrix),this.registerOutput("output",re.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}}xe("BABYLON.MatrixTransposeBlock",Aje);var Sde;(function(r){r[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Tangent=2]="Tangent",r[r.VertexColor=3]="VertexColor",r[r.UV1=4]="UV1",r[r.UV2=5]="UV2",r[r.UV3=6]="UV3",r[r.UV4=7]="UV4",r[r.UV5=8]="UV5",r[r.UV6=9]="UV6"})(Sde||(Sde={}));class i2e extends Li{constructor(e){super(e,Ee.Neutral),this.attributeType=0,this.registerInput("input",re.AutoDetect),this.registerInput("fallback",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var n;if(this.attributeType)return;const i=t.ownerBlock;if(i instanceof Br&&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 Q_e)switch((n=this.input.connectedPoint)==null?void 0:n.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}}V([Fi("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}]})],i2e.prototype,"attributeType",void 0);xe("BABYLON.MeshAttributeExistsBlock",i2e);var Qs;(function(r){r[r.EaseInSine=0]="EaseInSine",r[r.EaseOutSine=1]="EaseOutSine",r[r.EaseInOutSine=2]="EaseInOutSine",r[r.EaseInQuad=3]="EaseInQuad",r[r.EaseOutQuad=4]="EaseOutQuad",r[r.EaseInOutQuad=5]="EaseInOutQuad",r[r.EaseInCubic=6]="EaseInCubic",r[r.EaseOutCubic=7]="EaseOutCubic",r[r.EaseInOutCubic=8]="EaseInOutCubic",r[r.EaseInQuart=9]="EaseInQuart",r[r.EaseOutQuart=10]="EaseOutQuart",r[r.EaseInOutQuart=11]="EaseInOutQuart",r[r.EaseInQuint=12]="EaseInQuint",r[r.EaseOutQuint=13]="EaseOutQuint",r[r.EaseInOutQuint=14]="EaseInOutQuint",r[r.EaseInExpo=15]="EaseInExpo",r[r.EaseOutExpo=16]="EaseOutExpo",r[r.EaseInOutExpo=17]="EaseInOutExpo",r[r.EaseInCirc=18]="EaseInCirc",r[r.EaseOutCirc=19]="EaseOutCirc",r[r.EaseInOutCirc=20]="EaseInOutCirc",r[r.EaseInBack=21]="EaseInBack",r[r.EaseOutBack=22]="EaseOutBack",r[r.EaseInOutBack=23]="EaseInOutBack",r[r.EaseInElastic=24]="EaseInElastic",r[r.EaseOutElastic=25]="EaseOutElastic",r[r.EaseInOutElastic=26]="EaseInOutElastic"})(Qs||(Qs={}));class Sje extends Li{constructor(e){super(e,Ee.Neutral),this.type=Qs.EaseInOutSine,this.registerInput("input",re.AutoDetect),this.registerOutput("output",re.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(re.Matrix),this._inputs[0].excludedConnectionPointTypes.push(re.Object),this._inputs[0].excludedConnectionPointTypes.push(re.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 n=parseInt(t.replace("vec",""));let s=i?` var ret: vec${n}f = vec${n}f(0.0); `:` vec${n} ret = vec${n}(0.0); `;for(let a=1;a<=n;a++)s+=this._duplicateEntry(e,a===1?"x":a===2?"y":a===3?"z":"w")+`; `;return s+=`return ret; `,s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",n="";const s=e._getShaderType(this.input.type),a=e.shaderLanguage===1;switch(n=Qs[this.type]+"_"+s.replace("<","").replace(">",""),this.type){case Qs.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case Qs.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case Qs.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case Qs.EaseInQuad:i="return v * v";break;case Qs.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case Qs.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,s,a);break}case Qs.EaseInCubic:i="return v * v * v";break;case Qs.EaseOutCubic:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s,a);break}case Qs.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,s,a);break}case Qs.EaseInQuart:i="return v * v * v * v";break;case Qs.EaseOutQuart:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s,a);break}case Qs.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,s,a);break}case Qs.EaseInQuint:i="return v * v * v * v * v";break;case Qs.EaseOutQuint:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s,a);break}case Qs.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,s,a);break}case Qs.EaseInExpo:{const o=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(o,s,a);break}case Qs.EaseOutExpo:{const o=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(o,s,a);break}case Qs.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,s,a);break}case Qs.EaseInCirc:{i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s,a);break}case Qs.EaseOutCirc:{i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s,a);break}case Qs.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,s,a);break}case Qs.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case Qs.EaseOutBack:{i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s,a);break}case Qs.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,s,a);break}case Qs.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,s,a);break}case Qs.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,s,a);break}case Qs.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,s,a);break}}return a?e._emitFunction(n,`fn ${n}(v: ${s}) -> ${s} {${i};} `,""):e._emitFunction(n,`${s} ${n}(${s} v) {${i};} `,""),e.compilationString+=e._declareOutput(t)+` = ${n}(${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.${Qs[this.type]}; `}}xe("BABYLON.CurveBlock",Sje);class zMt{optimize(e,t){}}class VMt{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 n=this.mm.get(e);n===void 0&&this.mm.set(e,n=new Map),n.set(t,i)}}class GMt{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??ei.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new VMt,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add(n=>{var a,o;const s=(a=n.subMesh)==null?void 0:a.getMesh();s&&!this._meshes.has(s)&&this._meshes.set(s,s.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(n.subMesh))==null?void 0:o[0])!==n.effect&&(this._subMeshToEffect.set(n.subMesh,[n.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(n.subMesh))})}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach(i=>{var n;(n=i.mainDrawWrapper.effect)==null||n.dispose()}),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){var a;const n=(a=this._subMeshToDepthWrapper.mm.get(e))==null?void 0:a.get(t);if(!n)return null;let s=n.drawWrapper[i];return s||(s=n.drawWrapper[i]=new pl(this._scene.getEngine()),s.setEffect(n.mainDrawWrapper.effect,n.mainDrawWrapper.defines)),s}isReadyForSubMesh(e,t,i,n,s){var a;return this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,n)?!1:((a=this._makeEffect(e,t,i,s))==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,n]=t.value;i.onDisposeObservable.remove(n)}}_makeEffect(e,t,i,n){var p,g;const s=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 m=new pl(s);m.defines=((p=e._getDrawWrapper(l))==null?void 0:p.defines)??null,c={drawWrapper:[],mainDrawWrapper:m,depthDefines:"",token:Xh()},c.drawWrapper[n]=m,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 m=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,m),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 b=f.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||f.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,C=f.indexOf("#define SHADOWDEPTH_FRAGMENT")!==-1;let A="";b?f=f.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,y):A=y+` `,f=f.replace(/void\s+?main/g,Sr.IncludesShadersStore.shadowMapFragmentExtraDeclaration+` void main`),C?f=f.replace(/#define SHADOWDEPTH_FRAGMENT/g,v):A+=v+` `,A&&(f=f.replace(/}\s*$/g,A+"}")),h.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}c.mainDrawWrapper.effect=s.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},s);for(let m=0;m0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof O){const t=[];return e.forEach(n=>{t.push(n.flatMap(s=>[s.x,s.y,s.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 n=[];return t.subtract(e).lengthSquared()>0&&n.push([e,t]),i.subtract(t).lengthSquared()>0&&n.push([t,i]),e.subtract(i).lengthSquared()>0&&n.push([i,e]),n.length===0?null:n}static OmitDuplicatesPredicate(e,t,i,n){const s=[];return Xn._SearchInPoints(e,t,n)||s.push([e,t]),Xn._SearchInPoints(t,i,n)||s.push([t,i]),Xn._SearchInPoints(i,e,n)||s.push([i,e]),s.length===0?null:s}static _SearchInPoints(e,t,i){var n,s,a;for(const o of i)for(let l=0;l{const a=n.getVerticesData(ee.PositionKind),o=n.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 n=e.length;n--;)t[n]=e[n].length/3,i+=t[n];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=Xn.ToVector3Array(e):t=e;const i=oe.Vector3[0];let n=0;for(let s=0;s{s.length>t?Xn.SegmentizeSegmentByCount(s.point1,s.point2,Math.ceil(s.length/t)).forEach(o=>{n.push(o)}):(n.push(s.point1),n.push(s.point2))}),n}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?Xn.ToVector3Array(e):e,n=Xn.GetLineLength(i)/t;return Xn.SegmentizeLineBySegmentLength(i,n)}static GetLineSegments(e){const t=[];for(let i=0;in.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,n=!1){const s=t*i;let a=0,o=0;const l=e.length;for(let u=0;u[s.x,s.y,s.z])}static GetArrowCap(e,t,i,n,s,a=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[n,s,a,o]}}static GetPointsFromText(e,t,i,n,s=0,a=!0){const o=[],l=a_e(e,t,i,n);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,s);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,s);o.push(h)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,n=0;is?s:t.length,o=Math.ceil(t.length/s);o>1&&(t=[...t,...Array(a*o-t.length).fill(t[0])]);const l=Xn.Color3toRGBAUint8(t),c=new Vs(l,a,o,Vt.TEXTUREFORMAT_RGBA,n,!1,!0,i);return c.name=e,c}static PrepareEmptyColorsTexture(e){if(!_c.EmptyColorsTexture){const t=new Uint8Array(4);_c.EmptyColorsTexture=new Vs(t,1,1,Vt.TEXTUREFORMAT_RGBA,e,!1,!1,Vs.NEAREST_NEAREST),_c.EmptyColorsTexture.name="grlEmptyColorsTexture"}return _c.EmptyColorsTexture}static DisposeEmptyColorsTexture(){var e;(e=_c.EmptyColorsTexture)==null||e.dispose(),_c.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class Tje extends Kn{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 D_ extends Yu{constructor(e,t,i){i=i||{color:_c.DEFAULT_COLOR};const n=new Tje;n.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,n.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,n.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===1,n.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,n.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,D_.GREASED_LINE_MATERIAL_NAME,200,n),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?_c.DEFAULT_WIDTH_ATTENUATED:_c.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??Vs.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new Ne(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=Xn.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??_c.DEFAULT_COLOR,Xn.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{Xn.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 s=this._scene.activeCamera;if(s){const o=s.getProjectionMatrix();e.updateMatrix("grl_projection",o)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const a=oe.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=oe.Vector4[0];t.x=Xn.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=oe.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=Xn.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const n=this.colorsTexture??_c.EmptyColorsTexture;e.setTexture("grl_colors",n),e.updateFloat2("grl_textureSize",(n==null?void 0:n.getSize().width)??1,(n==null?void 0:n.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 D_.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 s,a,o;const n=((s=this._colors)==null?void 0:s.length)??0;if(this._colors=e,e===null||e.length===0){(a=this.colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this.colorsTexture&&n===e.length&&!i){const l=Xn.Color3toRGBAUint8(e);this.colorsTexture.update(l)}else(o=this.colorsTexture)==null||o.dispose(),this.colorsTexture=Xn.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 s;super.parse(e,t,i);const n=e.greasedLineMaterialOptions;(s=this.colorsTexture)==null||s.dispose(),n.color&&this.setColor(n.color,!0),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colors&&(this.colors=n.colors),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),this.colors?this.colorsTexture=Xn.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Xn.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var i;const t=e;(i=t.colorsTexture)==null||i.dispose(),this._colors&&(t.colorsTexture=Xn.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()}}D_.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";xe(`BABYLON.${D_.GREASED_LINE_MATERIAL_NAME}`,D_);const QMt="greasedLinePixelShader",ZMt=`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;}}} `;me.ShadersStore[QMt]=ZMt;const qMt="greasedLineVertexShader",JMt=`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 } `;me.ShadersStore[qMt]=JMt;class r2e extends ua{constructor(e,t,i){const n=["COLOR_DISTRIBUTION_TYPE_LINE 1.","COLOR_DISTRIBUTION_TYPE_SEGMENT 0.","COLOR_MODE_SET 0.","COLOR_MODE_ADD 1.","COLOR_MODE_MULTIPLY 2."],s=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&n.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(n.push("GREASED_LINE_CAMERA_FACING"),s.push("grl_previousAndSide","grl_nextAndCounters")):(s.push("grl_slopes"),s.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:s,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:n}),this._color=Pe.White(),this._colorsDistributionType=0,this._colorsTexture=null,i=i||{color:_c.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?_c.DEFAULT_WIDTH_ATTENUATED:_c.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Pe.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??Vs.NEAREST_NEAREST,this.colorMode=i.colorMode??0,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new Ne(a.getRenderWidth(),a.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Xn.PrepareEmptyColorsTexture(t),this._colors&&this.useColors&&(this.colorsTexture=Xn.CreateColorsTexture(`${this.name}-colors-texture`,this._colors,this.colorsSampling,t)),a.onDisposeObservable.add(()=>{Xn.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)==null||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new Ne(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 s,a,o;const n=((s=this._colors)==null?void 0:s.length)??0;if(this._colors=e,e===null||e.length===0){(a=this._colorsTexture)==null||a.dispose();return}if(!(t&&!i))if(this._colorsTexture&&n===e.length&&!i){const l=Xn.Color3toRGBAUint8(e);this._colorsTexture.update(l)}else(o=this._colorsTexture)==null||o.dispose(),this.colorsTexture=Xn.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",Xn.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",Xn.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",Xn.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??_c.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 s;const n=e.greasedLineMaterialOptions;(s=this._colorsTexture)==null||s.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=Xn.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Xn.PrepareEmptyColorsTexture(t),this._cameraFacing=n.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}var Tde;(function(r){r[r.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",r[r.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",r[r.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(Tde||(Tde={}));var Mde;(function(r){r[r.COLOR_MODE_SET=0]="COLOR_MODE_SET",r[r.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",r[r.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(Mde||(Mde={}));var Rde;(function(r){r[r.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",r[r.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(Rde||(Rde={}));const eRt=`#if defined(DBG_ENABLED) attribute float dbg_initialPass; varying vec3 dbg_vBarycentric; flat varying vec3 dbg_vVertexWorldPos; flat varying float dbg_vPass; #endif`,tRt=`#if defined(DBG_ENABLED) attribute dbg_initialPass: f32; varying dbg_vBarycentric: vec3f; varying dbg_vVertexWorldPos: vec3f; varying dbg_vPass: f32; #endif`,iRt=`#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`,rRt=`#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`,nRt=`#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`,sRt=`#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`,aRt=`#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`,oRt=`#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`,lRt=`#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`,cRt=`#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`,Mje=[new Pe(.98,.26,.38),new Pe(.47,.75,.3),new Pe(0,.26,.77),new Pe(.97,.6,.76),new Pe(.19,.63,.78),new Pe(.98,.8,.6),new Pe(.65,.43,.15),new Pe(.15,.47,.22),new Pe(.67,.71,.86),new Pe(.09,.46,.56),new Pe(.8,.98,.02),new Pe(.39,.29,.13),new Pe(.53,.63,.06),new Pe(.95,.96,.41),new Pe(1,.72,.94),new Pe(.63,.08,.31),new Pe(.66,.96,.95),new Pe(.22,.14,.19),new Pe(.14,.65,.59),new Pe(.93,1,.68),new Pe(.93,.14,.44),new Pe(.47,.86,.67),new Pe(.85,.07,.78),new Pe(.53,.64,.98),new Pe(.43,.37,.56),new Pe(.71,.65,.25),new Pe(.66,.19,.01),new Pe(.94,.53,.12),new Pe(.41,.44,.44),new Pe(.24,.71,.96),new Pe(.57,.28,.56),new Pe(.44,.98,.42)];var Ide;(function(r){r[r.NONE=0]="NONE",r[r.TRIANGLES=1]="TRIANGLES",r[r.VERTICES=2]="VERTICES",r[r.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",r[r.UV0=4]="UV0",r[r.UV1=5]="UV1",r[r.VERTEXCOLORS=6]="VERTEXCOLORS",r[r.MATERIALIDS=7]="MATERIALIDS"})(Ide||(Ide={}));class uRt extends Kn{constructor(){super(...arguments),this.DBG_MODE=0,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Jl extends Yu{_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 uRt;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 Pe(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Pe(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Pe(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Pe(.8,.8,.8),this.vertexColor=t.vertexColor??new Pe(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Pe(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Pe(.5,.5,.5),this._materialColor=Jl.MaterialColors[Jl._PluginCount++%Jl.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){ge.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")&&ge.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?nRt:sRt}}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:tRt,CUSTOM_VERTEX_MAIN_END:rRt}:{CUSTOM_FRAGMENT_DEFINITIONS:oRt,CUSTOM_FRAGMENT_MAIN_END:cRt}:e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:eRt,CUSTOM_VERTEX_MAIN_END:iRt}:{CUSTOM_FRAGMENT_DEFINITIONS:aRt,CUSTOM_FRAGMENT_MAIN_END:lRt}}static Reset(){this._PluginCount=0,this.MaterialColors=Mje}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 n=Array.from(e.getIndices());const s=[];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);} `;me.ShadersStore[hRt]=dRt;const fRt="gaussianSplattingVertexDeclaration",pRt=`uniform mat4 world;uniform mat4 view;uniform mat4 projection; `;me.IncludesShadersStore[fRt]=pRt;const mRt="gaussianSplattingUboDeclaration",gRt=`#include #include `;me.IncludesShadersStore[mRt]=gRt;const _Rt="gaussianSplattingVertexShader",vRt=`#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 } `;me.ShadersStore[_Rt]=vRt;class yRt extends Kn{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 pw extends Va{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===!0)return!0;t.materialDefines||(t.materialDefines=new yRt);const s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(Tu(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,a),Mu(s,o,this,a,!0,null,!0),xo(e,a,!1,!1),a.isDirty){a.markAsProcessed(),s.resetCachedMaterial();const l=[ee.PositionKind,"splatIndex"];Do(l,a);const c=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal"],u=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],h=["Scene","Mesh"];Qo({uniformsNames:c,uniformBuffersNames:h,samplers:u,defines:a}),Yo(c);const d=a.toString(),f=s.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=s.getRenderId(),n._wasPreviouslyReady=!0,n._wasPreviouslyUsingInstances=!0,!0)}bindForSubMesh(e,t,i){var l;const n=this.getScene(),s=i.materialDefines;if(!s)return;const a=i.effect;if(!a)return;if(this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._mustRebind(n,a,i,t.visibility)){this.bindView(a),this.bindViewProjection(a);const c=n.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 m=u.getProjectionMatrix().m[5];u.fovMode==di.FOVMODE_VERTICAL_FIXED?p=d*m/2:p=h*m/2}this._activeEffect.setFloat2("focal",p,p);const g=t;if(g.covariancesATexture){const m=g.covariancesATexture.getSize();a.setFloat2("dataTextureSize",m.width,m.height),a.setTexture("covariancesATexture",g.covariancesATexture),a.setTexture("covariancesBTexture",g.covariancesBTexture),a.setTexture("centersTexture",g.centersTexture),a.setTexture("colorsTexture",g.colorsTexture)}wo(a,this,n)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);ic(n,t,a),this.useLogarithmicDepth&&Xo(s,a,n),this._afterBind(t,this._activeEffect,i)}clone(e){return ot.Clone(()=>new pw(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return ot.Parse(()=>new pw(e.name,t),e,t,i)}}xe("BABYLON.GaussianSplattingMaterial",pw);Object.defineProperty(ct.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new dD(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(an.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new dD(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(vr.prototype,"decalMap",{get:function(){return this._decalMap},set:function(r){this._decalMap=r},enumerable:!0,configurable:!0});const xRt="defaultFragmentDeclaration",bRt=`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 `;me.IncludesShadersStore[xRt]=bRt;const CRt="defaultUboDeclaration",ARt=`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 `;me.IncludesShadersStore[CRt]=ARt;const Rje="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_LOCAL_POSITION gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(vPosition*0.5+0.5,writeGeometryInfo); #endif #if defined(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); #elif defined(PREPASS_VELOCITY_LINEAR) vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) - (vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_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_NDC_DEPTH gl_FragData[PREPASS_NDC_DEPTH_INDEX]=vec4( gl_FragCoord.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_WORLD_NORMAL gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(normalW*0.5+0.5,writeGeometryInfo); #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 } `;me.ShadersStore[Rje]=Ije;const Pje={name:Rje,shader:Ije},SRt=Object.freeze(Object.defineProperty({__proto__:null,defaultPixelShader:Pje},Symbol.toStringTag,{value:"Module"})),ERt="defaultVertexDeclaration",TRt=`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 `;me.IncludesShadersStore[ERt]=TRt;const wje="defaultVertexShader",Dje=`#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) || defined(PREPASS_VELOCITY_LINEAR)) 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 } `;me.ShadersStore[wje]=Dje;const Oje={name:wje,shader:Dje},MRt=Object.freeze(Object.defineProperty({__proto__:null,defaultVertexShader:Oje},Symbol.toStringTag,{value:"Module"})),RRt="defaultUboDeclaration",IRt=`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 `;me.IncludesShadersStoreWGSL[RRt]=IRt;const Lje="defaultPixelShader",Nje=`#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_LOCAL_POSITION fragData[PREPASS_LOCAL_POSITION_INDEX] = vec4f(fragmentInputs.vPosition*0.5+0.5,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); #elif defined(PREPASS_VELOCITY_LINEAR) var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy / fragmentInputs.vPreviousPosition.w) - (fragmentInputs.vCurrentPosition.xy / fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_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_WORLD_NORMAL fragData[PREPASS_WORLD_NORMAL_INDEX] = vec4f(normalW*0.5+0.5,writeGeometryInfo); #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 } `;me.ShadersStoreWGSL[Lje]=Nje;const Fje={name:Lje,shader:Nje},PRt=Object.freeze(Object.defineProperty({__proto__:null,defaultPixelShaderWGSL:Fje},Symbol.toStringTag,{value:"Module"})),wRt="lightVxFragmentDeclaration",DRt=`#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 `;me.IncludesShadersStoreWGSL[wRt]=DRt;const Bje="defaultVertexShader",kje=`#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) || defined(PREPASS_VELOCITY_LINEAR)) 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 } `;me.ShadersStoreWGSL[Bje]=kje;const Uje={name:Bje,shader:kje},ORt=Object.freeze(Object.defineProperty({__proto__:null,defaultVertexShaderWGSL:Uje},Symbol.toStringTag,{value:"Module"}));class m0{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 m0(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 m0(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 m0(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 m0(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 m0(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new m0(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 m0(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 Ne(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 m0(0,0);return m0.FromVector2ToRef(e,t),t}static FromArray(e){return new m0(e[0],e[1])}}class g0{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 g0(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 g0(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,n){return n.radius=this.radius-e,n.theta=this.theta-t,n.phi=this.phi-i,n}subtractFromFloats(e,t,i){const n=new g0(0,0,0);return this.subtractFromFloatsToRef(e,t,i,n),n}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 g0(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 g0(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new g0(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 g0(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),n=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,n),e}toVector3(){const e=new O(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 g0(0,0,0);return g0.FromVector3ToRef(e,t),t}static FromArray(e){return new g0(e[0],e[1],e[2])}}class zje{constructor(e,t=2,i=3,n=1,s=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=n,this._height=s,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,n=0;for(;e>0;)i/=t,n+=i*(e%t),e=~~(e/t);return n}}function Vje(r,e){return`{X: ${r.x.toFixed(e)} Y: ${r.y.toFixed(e)}}`}function Gje(r,e){return`{X: ${r._x.toFixed(e)} Y: ${r._y.toFixed(e)} Z: ${r._z.toFixed(e)}}`}function Wje(r,e){return`{X: ${r.x.toFixed(e)} Y: ${r.y.toFixed(e)} Z: ${r.z.toFixed(e)} W: ${r.w.toFixed(e)}}`}function Pde(r,e,t,i,n){let s=null,a=null,o=null;try{s=new r.Decoder,a=new r.DecoderBuffer,a.Init(e,e.byteLength);let l;const c=s.GetEncodedGeometryType(a);switch(c){case r.TRIANGULAR_MESH:{const d=new r.Mesh;if(l=s.DecodeBufferToMesh(a,d),!l.ok()||d.ptr===0)throw new Error(l.error_msg());const p=d.num_faces()*3,g=p*4,m=r._malloc(g);try{s.GetTrianglesUInt32Array(d,g,m);const _=new Uint32Array(p);_.set(new Uint32Array(r.HEAPF32.buffer,m,p)),i(_)}finally{r._free(m)}o=d;break}case r.POINT_CLOUD:{const d=new r.PointCloud;if(l=s.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,g)=>{const m=g.data_type(),_=g.num_components(),y=g.normalized(),v=g.byte_stride(),x=g.byte_offset(),C={[r.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:r.HEAPF32},[r.DT_INT8]:{typedArrayConstructor:Int8Array,heap:r.HEAP8},[r.DT_INT16]:{typedArrayConstructor:Int16Array,heap:r.HEAP16},[r.DT_INT32]:{typedArrayConstructor:Int32Array,heap:r.HEAP32},[r.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:r.HEAPU8},[r.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:r.HEAPU16},[r.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:r.HEAPU32}}[m];if(!C)throw new Error(`Invalid data type ${m}`);const A=u*_,E=A*C.typedArrayConstructor.BYTES_PER_ELEMENT,P=r._malloc(E);try{d.GetAttributeDataArrayForAllPoints(f,g,m,E,P);const w=new C.typedArrayConstructor(C.heap.buffer,P,A);n(p,w.slice(),_,x,v,y)}finally{r._free(P)}};if(t)for(const d in t){const f=t[d],p=s.GetAttributeByUniqueId(o,f);h(s,o,d,p)}else{const d={position:r.POSITION,normal:r.NORMAL,color:r.COLOR,uv:r.TEX_COORD};for(const f in d){const p=s.GetAttributeId(o,d[f]);if(p!==-1){const g=s.GetAttribute(o,p);h(s,o,f,g)}}}return u}finally{o&&r.destroy(o),a&&r.destroy(a),s&&r.destroy(s)}}function LRt(){let r;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&importScripts(i.url);const n=i.wasmBinary?{wasmBinary:i.wasmBinary}:{};r=DracoDecoderModule(n),postMessage({id:"initDone"});break}case"decodeMesh":{if(!r)throw new Error("Draco decoder module is not available");r.then(i=>{const n=Pde(i,t.dataView,t.attributes,s=>{postMessage({id:"indices",data:s},[s.buffer])},(s,a,o,l,c,u)=>{postMessage({id:"attribute",kind:s,data:a,size:o,byteOffset:l,byteStride:c,normalized:u},[a.buffer])});postMessage({id:"decodeMeshDone",totalVertices:n})});break}}}}function NRt(r,e,t){return new Promise((i,n)=>{const s=o=>{r.removeEventListener("error",s),r.removeEventListener("message",a),n(o)},a=o=>{o.data.id==="initDone"&&(r.removeEventListener("error",s),r.removeEventListener("message",a),i(r))};if(r.addEventListener("error",s),r.addEventListener("message",a),!e)r.postMessage({id:"init",decoder:{url:t}});else{const o=e.slice(0);r.postMessage({id:"init",decoder:{url:t,wasmBinary:o}},[o])}})}function FRt(r,e){return new Promise(t=>{(e||DracoDecoderModule)({wasmBinary:r}).then(i=>{t({module:i})})})}class Ic{static get DecoderAvailable(){const e=Ic.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 Ic._Default||(Ic._Default=new Ic),Ic._Default}static ResetDefault(e){Ic._Default&&(e||Ic._Default.dispose(),Ic._Default=null)}constructor(e=Ic.DefaultNumWorkers){const t=Ic.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,n=typeof e=="number"?e:e.numWorkers,s=n&&typeof Worker=="function"&&typeof URL=="function",a=s||!s&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:a?Ie.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ie.LoadFileAsync(Ie.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:a?Ie.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};s?this._workerPoolPromise=o.wasmBinaryPromise.then(l=>{const c=`${Pde}(${LRt})()`,u=URL.createObjectURL(new Blob([c],{type:"application/javascript"}));return new cD(n,()=>{const h=new Worker(u);return NRt(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 Ie.LoadBabylonScriptAsync(o.url)}return await FRt(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 n=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),s=(a,o)=>i&&i[a]!==void 0?(o!==i[a]&&ge.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=m=>{c.removeEventListener("error",f),c.removeEventListener("message",p),l(m),u()},p=m=>{const _=m.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:s(_.kind,_.normalized)});break}}};c.addEventListener("error",f),c.addEventListener("message",p);const g=n.slice();c.postMessage({id:"decodeMesh",dataView:g,attributes:t},[g.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(a=>{let o=null;const l=[],c=Pde(a.module,n,t,u=>{o=u},(u,h,d,f,p,g)=>{l.push({kind:u,data:h,size:d,byteOffset:f,byteStride:p,normalized:g})});return{indices:o,attributes:l,totalVertices:c}});throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,n){const s=await this.decodeMeshToMeshDataAsync(i,n),a=new ul(e,t);s.indices&&a.setIndices(s.indices);for(const o of s.attributes)a.setVerticesBuffer(new ee(t.getEngine(),o.data,o.kind,!1,void 0,o.byteStride,void 0,o.byteOffset,o.size,void 0,o.normalized,!0),s.totalVertices);return a}async _decodeMeshToGeometryForGltfAsync(e,t,i,n,s){const a=await this.decodeMeshToMeshDataAsync(i,n,s),o=new ul(e,t);a.indices&&o.setIndices(a.indices);for(const l of a.attributes)o.setVerticesBuffer(new ee(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),n=new vt;i.indices&&(n.indices=i.indices);for(const s of i.attributes){const a=ee.GetFloatData(s.data,s.size,ee.GetDataType(s.data),s.byteOffset,s.byteStride,s.normalized,i.totalVertices);n.set(a,s.kind)}return n}}Ic.Configuration={decoder:{wasmUrl:`${Ie._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ie._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ie._DefaultCdnUrl}/draco_decoder_gltf.js`}};Ic.DefaultNumWorkers=Ic.GetDefaultNumWorkers();Ic._Default=null;class n_{static get Default(){return n_._Default||(n_._Default=new n_),n_._Default}constructor(){const e=n_.Configuration.decoder;this._decoderModulePromise=Ie.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,s){return this._decoderModulePromise.then(async()=>{MeshoptDecoder.useWorkers(1);const a=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,n,s);return MeshoptDecoder.useWorkers(0),a})}}n_.Configuration={decoder:{url:`${Ie._DefaultCdnUrl}/meshopt_decoder.js`}};n_._Default=null;let bX=0;class sU{constructor(e,t,i,n){this.pos=e,this.normal=t,this.uv=i,this.vertColor=n}clone(){var e,t;return new sU(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 sU(O.Lerp(this.pos,e.pos,t),O.Lerp(this.normal,e.normal,t),this.uv&&e.uv?Ne.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?at.Lerp(this.vertColor,e.vertColor,t):void 0)}}class vS{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const n=i.subtract(e),s=t.subtract(e);if(n.lengthSquared()===0||s.lengthSquared()===0)return null;const a=O.Normalize(O.Cross(n,s));return new vS(a,O.Dot(a,e))}clone(){return new vS(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,n,s){let u=0;const h=[];let d,f;for(d=0;dvS.EPSILON?1:0;u|=p,h.push(p)}switch(u){case 0:(O.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:n.push(e);break;case 2:s.push(e);break;case 3:{const p=[],g=[];for(d=0;d=3&&(m=new mw(p,e.shared),m.plane&&n.push(m)),g.length>=3&&(m=new mw(g,e.shared),m.plane&&s.push(m));break}}}}vS.EPSILON=1e-5;class mw{constructor(e,t){this.vertices=e,this.shared=t,this.plane=vS.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new mw(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let a0=class iQ{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new iQ;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 a0(this.clone()._polygons),i=new a0(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Zm._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new a0(this._polygons),i=new a0(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 a0(this.clone()._polygons),i=new a0(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(),Zm._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new a0(this._polygons),i=new a0(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 a0(this.clone()._polygons),i=new a0(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Zm._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new a0(this._polygons),i=new a0(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 n=this._polygons,s=[],a=[],o=[];let l=null,c=null;const u=O.Zero(),h=O.Zero(),d=Ne.Zero(),f=new at(0,0,0,0),p=[0,0,0],g={};let m;for(let y=0,v=n.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(n),i){let u=0,h;n.subMeshes=[];for(const d in o){h=-1;for(const f in o[d])l=o[d][f],yc.CreateFromIndices(l.materialIndex+u,l.indexStart,l.indexEnd-l.indexStart+1,n),h=Math.max(l.materialIndex,h);u+=++h}}return n}toMesh(e,t=null,i,n){const s=this.buildMeshGeometry(e,i,n);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}class z1{static _GetShader(e,t){if(!e._meshUVSpaceRendererShader){const i=new ua("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 n;(n=e._meshUVSpaceRendererShader)==null||n.dispose(),e._meshUVSpaceRendererShader=null}),e._meshUVSpaceRendererShader=i}return e._meshUVSpaceRendererShader}static _GetMaskShader(e,t){if(!e._meshUVSpaceRendererMaskShader){const i=new ua("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"],shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add(()=>{var n;(n=e._meshUVSpaceRendererMaskShader)==null||n.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 at(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([je(()=>Promise.resolve().then(()=>ZRt),void 0),je(()=>Promise.resolve().then(()=>qRt),void 0),je(()=>Promise.resolve().then(()=>JRt),void 0),je(()=>Promise.resolve().then(()=>e8t),void 0),je(()=>Promise.resolve().then(()=>i8t),void 0),je(()=>Promise.resolve().then(()=>t8t),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>HRt),void 0),je(()=>Promise.resolve().then(()=>jRt),void 0),je(()=>Promise.resolve().then(()=>$Rt),void 0),je(()=>Promise.resolve().then(()=>XRt),void 0),je(()=>Promise.resolve().then(()=>QRt),void 0),je(()=>Promise.resolve().then(()=>YRt),void 0)]),this._shadersLoaded=!0,this._createDiffuseRTT()}isReady(){var n,s;if(!this._shadersLoaded)return!1;this.texture||this._createDiffuseRTT();const e=z1._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=((n=this._maskTexture)==null?void 0:n.isReadyForRendering())??!0,i=((s=this._finalPostProcess)==null?void 0:s.isReady())??!0;return e&&t&&i}renderTexture(e,t,i,n,s=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),z1._IsRenderTargetTexture(this.texture)){const a=this._createProjectionMatrix(t,i,n,s),o=z1._GetShader(this._scene,this._shaderLanguage);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",a),this.texture.render()}}clear(){var e,t,i;if(z1._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const n=this._scene.getEngine();n.bindFramebuffer(this.texture.renderTarget),n.clear(this.clearColor,!0,!0,!0),n.unBindFramebuffer(this.texture.renderTarget)}if((e=this._finalPostProcess)!=null&&e.inputTexture){const n=this._scene.getEngine();n.bindFramebuffer((t=this._finalPostProcess)==null?void 0:t.inputTexture),n.clear(this.clearColor,!0,!0,!0),n.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,z1._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,z1._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,z1._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 vn(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 at(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,z1._GetMaskShader(this._scene,this._shaderLanguage)),this._maskTexture.refreshRate=vn.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new ii(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 vn(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,n=0){const s=-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=pe.RotationYawPitchRoll(s,o,n).multiply(pe.Translation(l.x,l.y,l.z)),u=pe.Invert(c),h=pe.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),d=pe.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return u.multiply(h).multiply(d)}}Re._TrailMeshParser=(r,e)=>aU.Parse(r,e);class aU extends Re{constructor(e,t,i,n,s=60,a=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,typeof n=="object"&&n!==null?(this.diameter=n.diameter||1,this._length=n.length||60,this._segments=n.segments?n.segments>this._length?this._length:n.segments:this._length,this._sectionPolygonPointsCount=n.sections||4,this._doNotTaper=n.doNotTaper||!1,this._autoStart=n.autoStart||!0):(this.diameter=n||1,this._length=s,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]=O.Zero(),this._sectionNormalVectors[o]=O.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new vt,t=[],i=[],n=[],s=[];let a=O.Zero();this._generator instanceof vr&&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),s.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),s.push(u/this._sectionPolygonPointsCount,l/this._segments)}const c=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let u=0;u<=this._sectionPolygonPointsCount;u++)n.push(c+u,c+u+this._sectionPolygonPointsCount,c+u+this._sectionPolygonPointsCount+1),n.push(c+u,c+u+this._sectionPolygonPointsCount+1,c+u+1)}vt.ComputeNormals(t,n,i),e.positions=t,e.normals=i,e.indices=n,e.uvs=s,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 n=i!==this._sectionPolygonPointsCount?i*t:0;this._sectionVectors[i].copyFromFloats(Math.cos(n)*this.diameter,Math.sin(n)*this.diameter,0),this._sectionNormalVectors[i].copyFromFloats(Math.cos(n),Math.sin(n),0),O.TransformCoordinatesToRef(this._sectionVectors[i],e,this._sectionVectors[i]),O.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(ee.PositionKind),t=this.getVerticesData(ee.NormalKind),i=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let s=i;s{this._getSimplifier(e).simplify(t,n=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,n),n.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(n,s)=>{t.simplify(n,a=>{n.distance!==void 0&&e.mesh.addLODLevel(n.distance,a),a.isVisible=!0,s()})};lp.Run(e.settings.length,n=>{i(e.settings[n.index],()=>{n.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case 0:default:return new Hje(e.mesh)}}}var wde;(function(r){r[r.QUADRATIC=0]="QUADRATIC"})(wde||(wde={}));class kRt{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class URt{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new u5,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class u5{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,n,s,a,o,l,c){return this.data[e]*this.data[s]*this.data[c]+this.data[i]*this.data[n]*this.data[l]+this.data[t]*this.data[a]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[a]*this.data[l]-this.data[t]*this.data[n]*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 u5;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,n){return new u5(u5.DataFromNumbers(e,t,i,n))}static DataFromNumbers(e,t,i,n){return[e*e,e*t,e*i,e*n,t*t,t*i,t*n,i*i,i*n,n*n]}}class zRt{constructor(e,t){this.vertexId=e,this.triangleId=t}}class Hje{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=Ki}simplify(e,t){this._initDecimatedMesh(),lp.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 n=~~(this._triangles.length*e.quality);let s=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 g=0;g<3;++g)if(p.error[g]{C.indexOf(P)===-1&&(P.deletePending=!0,C.push(P))}),C.length%2!==0)continue;y.q=v.q.add(y.q),y.updatePosition(x);const A=this._references.length;s=this._updateTriangles(y,y,m,s),s=this._updateTriangles(y,v,_,s);const E=this._references.length-A;if(E<=y.triangleCount){if(E)for(let P=0;Pa-s<=n)},0)};lp.Run(this.decimationIterations,l=>{a-s<=n?l.breakLoop():o(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const n=this._mesh.getVerticesData(ee.PositionKind),s=this._mesh.getIndices(),a=this._mesh.subMeshes[e],o=h=>{if(i){for(let d=0;d{if(!n)return;const d=h+a.verticesStart,f=O.FromArray(n,d*3),p=o(f)||new URt(f,this._vertices.length);p.originalOffsets.push(d),p.id===this._vertices.length&&this._vertices.push(p),l.push(p.id)},u=a.verticesCount;lp.SyncAsyncForLoop(u,this.syncIterations/4>>0,c,()=>{const h=d=>{if(!s)return;const p=(a.indexStart/3+d)*3,g=s[p+0],m=s[p+1],_=s[p+2],y=this._vertices[l[g-a.verticesStart]],v=this._vertices[l[m-a.verticesStart]],x=this._vertices[l[_-a.verticesStart]],b=new kRt([y,v,x]);b.originalOffset=p,this._triangles.push(b)};lp.SyncAsyncForLoop(a.indexCount/3,this.syncIterations,h,()=>{this._init(t)})})}_init(e){const t=i=>{const n=this._triangles[i];n.normal=O.Cross(n._vertices[1].position.subtract(n._vertices[0].position),n._vertices[2].position.subtract(n._vertices[0].position)).normalize();for(let s=0;s<3;s++)n._vertices[s].q.addArrayInPlace(u5.DataFromNumbers(n.normal.x,n.normal.y,n.normal.z,-O.Dot(n.normal,n._vertices[0].position)))};lp.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=n=>{const s=this._triangles[n];for(let a=0;a<3;++a)s.error[a]=this._calculateError(s._vertices[a],s._vertices[(a+1)%3]);s.error[3]=Math.min(s.error[0],s.error[1],s.error[2])};lp.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[b*3]),o.push(u[b*3+1]),o.push(u[b*3+2])),h&&h.length&&(l.push(h[b*2]),l.push(h[b*2+1])),d&&d.length&&(c.push(d[b*4]),c.push(d[b*4+1]),c.push(d[b*4+2]),c.push(d[b*4+3])),++f})}const p=this._reconstructedMesh.getTotalIndices(),g=this._reconstructedMesh.getTotalVertices(),m=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const _=this._reconstructedMesh.getIndices(),y=this._mesh.getIndices();for(i=0;i{const b=y[n.originalOffset+x];let C=n._vertices[x].originalOffsets.indexOf(b);C<0&&(C=0),_.push(n._vertices[x].id+C+g)});this._reconstructedMesh.setIndices(_),this._reconstructedMesh.setVerticesData(ee.PositionKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(ee.NormalKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(ee.UVKind,l),c.length>0&&this._reconstructedMesh.setVerticesData(ee.ColorKind,c);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],m.forEach(x=>{yc.AddToMesh(x.materialIndex,x.verticesStart,x.verticesCount,x.indexStart,x.indexCount,x.getMesh())}),yc.AddToMesh(v.materialIndex,g,f,p,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Re(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,n,s){for(let a=0;a.999)return!0;const f=O.Cross(h,d).normalize();if(n[a]=!1,O.Dot(f,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,n){let s=n;for(let a=0;aMath.max(f,p.getTotalVertices()),0),o=Array.from({length:a},()=>new O),l=Array.from({length:a},()=>new O);for(const f of r){const p=f.getVerticesData(ee.PositionKind);if(!p)continue;const g=f.getTotalVertices();o.length=Math.max(o.length,g),l.length=Math.max(o.length,g);for(let x=0,b=0;x4,b=x?f.getVerticesData(ee.MatricesWeightsExtraKind):null,C=x?f.getVerticesData(ee.MatricesIndicesExtraKind):null,A=s.get(f.uniqueId)||new Map;s.set(f.uniqueId,A);const E=(P,w,M,R)=>{for(let I=w;I0){const D=R[I],k=A.get(D);k?(k.minimum.minimizeInPlace(o[P]),k.maximum.maximizeInPlace(l[P])):A.set(D,{minimum:o[P].clone(),maximum:l[P].clone()})}};for(let P=0,w=0;P{const x=fRe(y),b=m[v].getAbsoluteInverseBindMatrix();for(const C of x)O.TransformCoordinatesToRef(C,b,C);_.set(v,x)})}}}const h=Array.from({length:r.length},()=>({minimum:new O().setAll(Number.POSITIVE_INFINITY),maximum:new O().setAll(Number.NEGATIVE_INFINITY)})),d=()=>{for(let f=0;f{for(const b of v){const C=_[x].getFinalMatrix().multiplyToRef(g,oe.Matrix[0]);O.TransformCoordinatesToRef(b,C,i),h[f].minimum.minimizeInPlace(i),h[f].maximum.maximizeInPlace(i)}})}else for(const _ of c.get(p.uniqueId))O.TransformCoordinatesToRef(_,g,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 Dde;(function(r){r[r.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",r[r.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"})(Dde||(Dde={}));var Ode;(function(r){r[r.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",r[r.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",r[r.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"})(Ode||(Ode={}));var Lde;(function(r){r[r.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",r[r.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",r[r.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",r[r.AUTO_DIRECTIONS_FACE_TO=3]="AUTO_DIRECTIONS_FACE_TO",r[r.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"})(Lde||(Lde={}));class n2e extends Re{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 n of this._points)t+=n.length;const i=t/3*2-this._widths.length;for(let n=0;nuc.Parse(r,e);class uc extends n2e{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Xn.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,n+=(_.length-3)*2,s+=_.length*4/3,a+=_.length*8/3});const o=new Float32Array(i),l=i>65535?new Uint32Array(n):new Uint16Array(n),c=new Float32Array(s),u=new Float32Array(a),h=new Float32Array(a);let d=0,f=0,p=0,g=0,m=0;e.forEach(_=>{const y=Xn.GetLineLengthArray(_),v=y[y.length-1];for(let w=0,M=0;M<_.length;w++,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=w*2+t,D=f+M*2;l[D+0]=I,l[D+1]=I+1,l[D+2]=I+2,l[D+3]=I+2,l[D+4]=I+1,l[D+5]=I+3}}t+=_.length/3*2;const x=_.length*2,b=o.subarray(d,d+x);d+=x,f+=(_.length-3)*2;const C=new Float32Array(b.length),A=new Float32Array(b.length),E=b.length/6;let P;uc._CompareV3(0,E-1,b)?P=b.subarray((E-2)*6,(E-1)*6):P=b.subarray(0,6),C.set(P),C.set(b.subarray(0,b.length-6),6),A.set(b.subarray(6)),uc._CompareV3(E-1,0,b)?P=b.subarray(6,12):P=b.subarray((E-1)*6,E*6),A.set(P,A.length-6);for(let w=0,M=b.length/3;w>1]/v;if(this._options.uvs)for(let w=0;wuo.Parse(r,e);class uo extends n2e{constructor(e,t,i,n){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=n??[],i.points&&this.addPoints(Xn.ConvertPoints(i.points),i,!!n)}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=uo._ConvertToRibbonPath(d,c.ribbonOptions,this._scene.useRightHandedSystem,n&&n[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 n=[],s=[],a=e[0];for(let d=0;d2)for(let d=0;d0&&(o[0]+=1,o[1]+=1),s.push(o[1]+(f%2!==0?i:0),o[0],o[2]),l&&s.push(o[0],o[1]+(f%2!==0?i:0),o[2])}else for(let d=0;dp.y&&p.x>p.z?i?uo._RightHandedForwardReadOnlyQuaternion:uo._LeftHandedForwardReadOnlyQuaternion:uo._LeftReadOnlyQuaternion),c=p.normalize()}u=c.multiplyByFloats(o,o,o),s.push(d.add(u)),a.push(d.subtract(u))}n||(s.push(l[l.length-1].add(u)),a.push(l[l.length-1].subtract(u)))}return[s,a]}static _GetDirectionFromPoints(e,t,i){return e.x===t.x&&(!i||(i==null?void 0:i.x)===1)?uo.DIRECTION_YZ:e.y===t.y?uo.DIRECTION_XZ:e.z===t.z?uo.DIRECTION_XY:uo.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),n={},s=[];bc.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),bc.DeepCopy(i,n,["instance"],void 0,!0);const a=new uo(e,this._scene,n,s);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,n=e.name,s=e.pathOptions;return new uo(n,t,i,s)}_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,r*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[r]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};Re.prototype.thinInstanceSetAttributeAt=function(r,e,t,i=!0){return r===ee.ColorKind&&(r=ee.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[r]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(r,0),this._userThinInstanceBuffersStorage.data[r].set(t,e*this._userThinInstanceBuffersStorage.strides[r]),i&&this.thinInstanceBufferUpdated(r),!0)};Object.defineProperty(Re.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(r){var i;const e=this._thinInstanceDataStorage.matrixData??((i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData),t=e?e.length/16:0;r<=t&&(this._thinInstanceDataStorage.instancesCount=r)},enumerable:!0,configurable:!0});Re.prototype._thinInstanceCreateMatrixBuffer=function(r,e,t=!0){const i=new fl(this.getEngine(),e,!t,16,!1,!0);for(let n=0;n<4;n++)this.setVerticesBuffer(i.createVertexBuffer(r+n,n*4,4));return i};Re.prototype.thinInstanceSetBuffer=function(r,e,t=0,i=!0){var n,s,a;t=t||16,r==="matrix"?((n=this._thinInstanceDataStorage.matrixBuffer)==null||n.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())):r==="previousMatrix"?((s=this._thinInstanceDataStorage.previousMatrixBuffer)==null||s.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(r===ee.ColorKind&&(r=ee.ColorInstanceKind),e===null?(a=this._userThinInstanceBuffersStorage)!=null&&a.data[r]&&(this.removeVerticesData(r),delete this._userThinInstanceBuffersStorage.data[r],delete this._userThinInstanceBuffersStorage.strides[r],delete this._userThinInstanceBuffersStorage.sizes[r],delete this._userThinInstanceBuffersStorage.vertexBuffers[r]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[r]=e,this._userThinInstanceBuffersStorage.strides[r]=t,this._userThinInstanceBuffersStorage.sizes[r]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[r]=new ee(this.getEngine(),e,r,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[r])))};Re.prototype.thinInstanceBufferUpdated=function(r){var e,t,i;r==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(r),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):r==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(r),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(r===ee.ColorKind&&(r=ee.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[r]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[r].isUpdatable()&&this._thinInstanceRecreateBuffer(r),this._userThinInstanceBuffersStorage.vertexBuffers[r].updateDirectly(this._userThinInstanceBuffersStorage.data[r],0)))};Re.prototype.thinInstancePartialBufferUpdate=function(r,e,t){var i;r==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(r===ee.ColorKind&&(r=ee.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[r]&&this._userThinInstanceBuffersStorage.vertexBuffers[r].updateDirectly(e,t))};Re.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const r=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=_e.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new Ce,this.onDisconnectionObservable=new Ce,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!==_e.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?0:1;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return 1;let n=i,s=t;return this.direction===0&&(n=t,s=i),n.isAnAncestorOf(s)?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<_e.All;)e&t||this.excludedConnectionPointTypes.push(t),t=t<<1}serialize(e=!0){const t={};return t.name=this.name,t.displayName=this.displayName,this.value!==void 0&&this.value!==null&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class ur{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 n=i.ownerBlock.getDescendantOfPredicate(e);if(n)return n}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 Ce,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Rz.UniqueId}registerInput(e,t,i=!1,n,s,a){const o=new Ude(e,this,0);return o.type=t,o.isOptional=i,o.defaultValue=n,o.value=n,o.valueMin=s,o.valueMax=a,this._inputs.push(o),this}registerOutput(e,t,i){return i=i??new Ude(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 n=i.connectedPoint.ownerBlock;n&&n!==this&&n.build(e)}this._customBuildStep(e),e.verbose&&ge.Log(`Building ${this.name} [${this.getClassName()}]`);const t=hn.Now;this._buildBlock(e),this._buildExecutionTime=hn.Now-t;for(const i of this._outputs)for(const n of i.endpoints){const s=n.ownerBlock;s&&s.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(n=>{const s=this.inputs.find(a=>a.name===n.name);if(s&&(n.displayName&&(s.displayName=n.displayName),n.isExposedOnFrame&&(s.isExposedOnFrame=n.isExposedOnFrame,s.exposedPortPosition=n.exposedPortPosition),n.value!==void 0&&n.value!==null))if(n.valueType==="number")s.value=n.value;else{const a=Sa(n.valueType);a&&(s.value=a.FromArray(n.value))}}),i&&i.forEach((n,s)=>{n.displayName&&(this.outputs[s].displayName=n.displayName),n.isExposedOnFrame&&(this.outputs[s].isExposedOnFrame=n.isExposedOnFrame,this.outputs[s].exposedPortPosition=n.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 n=i.connectedPoint,s=n.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(n.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 n=` // ${this.getClassName()} `;this.comments&&(n+=`// ${this.comments} `);const s=this.getClassName();if(s==="GeometryInputBlock"){const o=this.type;n+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${o}); `}else n+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}"); `;n+=this._dumpPropertiesCode();for(const a of this.inputs){if(!a.isConnected)continue;const l=a.connectedPoint.ownerBlock;t.indexOf(l)===-1&&(n+=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&&(n+=l._dumpCode(e,t))}return n}clone(){const e=this.serialize(),t=Sa(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()}}V([Q("comment")],ur.prototype,"comments",void 0);class s2e extends ur{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",_e.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}xe("BABYLON.GeometryOutputBlock",s2e);var On;(function(r){r[r.None=0]="None",r[r.Positions=1]="Positions",r[r.Normals=2]="Normals",r[r.Tangents=3]="Tangents",r[r.UV=4]="UV",r[r.UV2=5]="UV2",r[r.UV3=6]="UV3",r[r.UV4=7]="UV4",r[r.UV5=8]="UV5",r[r.UV6=9]="UV6",r[r.Colors=10]="Colors",r[r.VertexID=11]="VertexID",r[r.FaceID=12]="FaceID",r[r.GeometryID=13]="GeometryID",r[r.CollectionID=14]="CollectionID",r[r.LoopID=15]="LoopID",r[r.InstanceID=16]="InstanceID"})(On||(On={}));class Zje{constructor(){this._rotationMatrix=new pe,this._scalingMatrix=new pe,this._positionMatrix=new pe,this._scalingRotationMatrix=new pe,this._transformMatrix=new pe,this._tempVector3=new O,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 On.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?O.Zero():O.FromArray(this.geometryContext.positions,i*3);case On.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?O.Zero():O.FromArray(this.geometryContext.normals,i*3);case On.Colors:return!this.geometryContext||!this.geometryContext.colors?It.Zero():It.FromArray(this.geometryContext.colors,i*4);case On.Tangents:return!this.geometryContext||!this.geometryContext.tangents?It.Zero():It.FromArray(this.geometryContext.tangents,i*4);case On.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?Ne.Zero():Ne.FromArray(this.geometryContext.uvs,i*2);case On.UV2:return!this.geometryContext||!this.geometryContext.uvs2?Ne.Zero():Ne.FromArray(this.geometryContext.uvs2,i*2);case On.UV3:return!this.geometryContext||!this.geometryContext.uvs3?Ne.Zero():Ne.FromArray(this.geometryContext.uvs3,i*2);case On.UV4:return!this.geometryContext||!this.geometryContext.uvs4?Ne.Zero():Ne.FromArray(this.geometryContext.uvs4,i*2);case On.UV5:return!this.geometryContext||!this.geometryContext.uvs5?Ne.Zero():Ne.FromArray(this.geometryContext.uvs5,i*2);case On.UV6:return!this.geometryContext||!this.geometryContext.uvs6?Ne.Zero():Ne.FromArray(this.geometryContext.uvs6,i*2);case On.VertexID:return i;case On.FaceID:return this.executionContext.getExecutionFaceIndex();case On.LoopID:return this.executionContext.getExecutionLoopIndex();case On.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case On.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case On.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 _e.Vector2:return new Ne(i,i);case _e.Vector3:return new O(i,i,i);case _e.Vector4:return new It(i,i,i,i)}return null}adaptInput(e,t,i){var s;if(!e.isConnected)return e.value||i;const n=e.getConnectedValue(this);if(((s=e._connectedPoint)==null?void 0:s.type)===t)return n;switch(t){case _e.Vector2:return new Ne(n,n);case _e.Vector3:return new O(n,n,n);case _e.Vector4:return new It(n,n,n,n)}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 ${On[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,n,s){pe.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),pe.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),pe.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.${On[this._contextualSource]}; `;const t=[];let i="";switch(this.type){case _e.Float:case _e.Int:i=`${this.value}`;break;case _e.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case _e.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case _e.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===_e.Float||this.type===_e.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=Sa(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}xe("BABYLON.GeometryInputBlock",jo);class Vee extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",_e.Float,!0,1),this.registerInput("width",_e.Float,!0,0),this.registerInput("height",_e.Float,!0,0),this.registerInput("depth",_e.Float,!0,0),this.registerInput("subdivisions",_e.Int,!0,1),this.registerInput("subdivisionsX",_e.Int,!0,0),this.registerInput("subdivisionsY",_e.Int,!0,0),this.registerInput("subdivisionsZ",_e.Int,!0,0),this.registerOutput("geometry",_e.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 jo("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new jo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new jo("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new jo("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=n=>{t.size=this.size.getConnectedValue(n),t.width=this.width.getConnectedValue(n),t.height=this.height.getConnectedValue(n),t.depth=this.depth.getConnectedValue(n);const s=this.subdivisions.getConnectedValue(n),a=this.subdivisionsX.getConnectedValue(n),o=this.subdivisionsY.getConnectedValue(n),l=this.subdivisionsZ.getConnectedValue(n);return s&&(t.segments=s),a&&(t.widthSegments=a),o&&(t.heightSegments=o),l&&(t.depthSegments=l),Hke(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Vee.prototype,"evaluateContext",void 0);xe("BABYLON.BoxBlock",Vee);class Sd{_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=Sd._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new Ce,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 Ie.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:Sd.EditorURL;Ie.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 n=hn.Now;this._initializeBlock(this.outputBlock,i);const s=new Zje;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=Sd._BuildIdGenerator++),this._buildExecutionTime=hn.Now-n,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Re(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 n=i.connectedPoint;if(n){const s=n.ownerBlock;s!==e&&this._initializeBlock(s,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 n of e.blocks){const s=Sa(n.customType);if(s){const a=new s;a._deserialize(n),i[n.id]=a,this.attachedBlocks.push(a)}}for(const n of this.attachedBlocks)if(n.isTeleportOut){const s=n,a=s._tempEntryPointUniqueId;if(a){const o=i[a];o&&o.attachToEndpoint(s)}}for(let n=0;no.targetConnectionName)&&!t||this._restoreConnections(a,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const n=e.locations||e.editorData.locations;for(const a of n)i[a.blockId]&&(a.blockId=i[a.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&n.concat(this.editorData.locations),e.locations?this.editorData={locations:n}:(this.editorData=e.editorData,this.editorData.locations=n);const s=[];for(const a in i)s[a]=i[a].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const n of e.outputs)for(const s of t.blocks){const a=i[s.id];if(a){for(const o of s.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===n.name){const l=a.getInputByName(o.inputName);if(!l||l.isConnected)continue;n.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 n=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); `;for(const s of t)s.isInput&&e.indexOf(s)===-1&&(n+=s._dumpCode(i,e));return this.outputBlock&&(e=[],n+=`// Connections `,n+=this.outputBlock._dumpCodeForOutputConnections(e),n+=`// Output nodes `,n+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; `,n+=`nodeGeometry.build(); `),n}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const n=i.connectedPoint;if(n){const s=n.ownerBlock;s!==e&&this._gatherBlocks(s,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Vee("Box");e.autoConfigure();const t=new s2e("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=ot.Clone(()=>new Sd(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:ot.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 n of i)t.blocks.push(n.serialize());if(!e)for(const n of this.attachedBlocks)i.indexOf(n)===-1&&t.blocks.push(n.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 Sd(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=ot.Parse(()=>new Sd(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Sd.CreateDefault("blank")):new Promise((n,s)=>{const a=new oa;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=ot.Parse(()=>new Sd(e),l,null)),t.parseSerializedObject(l),t.snippetId=e;try{i||t.build(),n(t)}catch(c){s(c)}}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}}Sd._BuildIdGenerator=0;Sd.EditorURL=`${Ie._DefaultCdnUrl}/v${Qe.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;Sd.SnippetUrl="https://snippet.babylonjs.com";V([Q()],Sd.prototype,"name",void 0);V([Q("comment")],Sd.prototype,"comment",void 0);class Gee extends ur{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=Ki,this.registerInput("geometry",_e.Geometry),this.registerOutput("output",_e.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 n=this.geometry.getConnectedValue(i),s=[],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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Gee.prototype,"evaluateContext",void 0);V([Fi("Epsilon",1,"ADVANCED",{notifiers:{rebuild:!0}})],Gee.prototype,"epsilon",void 0);xe("BABYLON.GeometryOptimizeBlock",Gee);class a2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",_e.Float,!0,1),this.registerInput("width",_e.Float,!0,0),this.registerInput("height",_e.Float,!0,0),this.registerOutput("geometry",_e.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 jo("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new jo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new jo("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=n=>(t.size=this.size.getConnectedValue(n),t.width=this.width.getConnectedValue(n),t.height=this.height.getConnectedValue(n),Nz(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],a2e.prototype,"evaluateContext",void 0);xe("BABYLON.PlaneBlock",a2e);class o2e extends ur{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",_e.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=vt.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=vt.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=vt.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}V([Fi("Serialize cached data",0,"ADVANCED",{notifiers:{rebuild:!0}})],o2e.prototype,"serializedCachedData",void 0);xe("BABYLON.MeshBlock",o2e);class l2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",_e.Float,!0,1),this.registerInput("radiusX",_e.Float,!0,0),this.registerInput("radiusY",_e.Float,!0,0),this.registerInput("radiusZ",_e.Float,!0,0),this.registerInput("subdivisions",_e.Int,!0,4),this.registerOutput("geometry",_e.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 jo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=n=>(t.radius=this.radius.getConnectedValue(n),t.subdivisions=this.subdivisions.getConnectedValue(n),t.radiusX=this.radiusX.getConnectedValue(n),t.radiusY=this.radiusY.getConnectedValue(n),t.radiusZ=this.radiusZ.getConnectedValue(n),gee(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],l2e.prototype,"evaluateContext",void 0);xe("BABYLON.IcoSphereBlock",l2e);class c2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",_e.Int,!0,32),this.registerInput("diameter",_e.Float,!0,1),this.registerInput("diameterX",_e.Float,!0,0),this.registerInput("diameterY",_e.Float,!0,0),this.registerInput("diameterZ",_e.Float,!0,0),this.registerInput("arc",_e.Float,!0,1),this.registerInput("slice",_e.Float,!0,1),this.registerOutput("geometry",_e.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 jo("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=n=>(t.segments=this.segments.getConnectedValue(n),t.diameter=this.diameter.getConnectedValue(n),t.diameterX=this.diameterX.getConnectedValue(n),t.diameterY=this.diameterY.getConnectedValue(n),t.diameterZ=this.diameterZ.getConnectedValue(n),t.arc=this.arc.getConnectedValue(n),t.slice=this.slice.getConnectedValue(n),cee(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],c2e.prototype,"evaluateContext",void 0);xe("BABYLON.SphereBlock",c2e);class u2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",_e.Float,!0,1),this.registerInput("height",_e.Float,!0,1),this.registerInput("subdivisions",_e.Int,!0,1),this.registerInput("subdivisionsX",_e.Int,!0,0),this.registerInput("subdivisionsY",_e.Int,!0,0),this.registerOutput("geometry",_e.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 jo("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new jo("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=n=>(t.width=this.width.getConnectedValue(n),t.height=this.height.getConnectedValue(n),t.subdivisions=this.subdivisions.getConnectedValue(n),t.subdivisionsX=this.subdivisionsX.getConnectedValue(n),t.subdivisionsY=this.subdivisionsY.getConnectedValue(n),q1(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],u2e.prototype,"evaluateContext",void 0);xe("BABYLON.GridBlock",u2e);class h2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",_e.Float,!0,1),this.registerInput("thickness",_e.Float,!0,.5),this.registerInput("tessellation",_e.Int,!0,16),this.registerOutput("geometry",_e.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 jo("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=n=>(t.thickness=this.thickness.getConnectedValue(n),t.diameter=this.diameter.getConnectedValue(n),t.tessellation=this.tessellation.getConnectedValue(n),see(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],h2e.prototype,"evaluateContext",void 0);xe("BABYLON.TorusBlock",h2e);class d2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",_e.Float,!0,25),this.registerInput("diameter",_e.Float,!0,1),this.registerInput("diameterTop",_e.Float,!0,-1),this.registerInput("diameterBottom",_e.Float,!0,-1),this.registerInput("subdivisions",_e.Int,!0,1),this.registerInput("tessellation",_e.Int,!0,24),this.registerInput("arc",_e.Float,!0,1),this.registerOutput("geometry",_e.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 jo("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new jo("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=n=>(t.height=this.height.getConnectedValue(n),t.diameter=this.diameter.getConnectedValue(n),t.diameterTop=this.diameterTop.getConnectedValue(n),t.diameterBottom=this.diameterBottom.getConnectedValue(n),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(n),t.subdivisions=this.subdivisions.getConnectedValue(n),t.arc=this.arc.getConnectedValue(n),oee(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],d2e.prototype,"evaluateContext",void 0);xe("BABYLON.CylinderBlock",d2e);class f2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",_e.Float,!0,1),this.registerInput("radius",_e.Float,!0,.25),this.registerInput("tessellation",_e.Int,!0,16),this.registerInput("subdivisions",_e.Int,!0,2),this.registerOutput("geometry",_e.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 jo("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new jo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=n=>(t.height=this.height.getConnectedValue(n),t.radius=this.radius.getConnectedValue(n),t.tessellation=this.tessellation.getConnectedValue(n),t.subdivisions=this.subdivisions.getConnectedValue(n),uee(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],f2e.prototype,"evaluateContext",void 0);xe("BABYLON.CapsuleBlock",f2e);class p2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",_e.Float,!0,.5),this.registerInput("tessellation",_e.Int,!0,64),this.registerInput("arc",_e.Float,!0,1),this.registerOutput("geometry",_e.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 jo("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=n=>(t.radius=this.radius.getConnectedValue(n),t.tessellation=this.tessellation.getConnectedValue(n),t.arc=this.arc.getConnectedValue(n),hee(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const n=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],p2e.prototype,"evaluateContext",void 0);xe("BABYLON.DiscBlock",p2e);class qje extends ur{constructor(e){super(e),this.registerOutput("geometry",_e.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}xe("BABYLON.NullBlock",qje);class m2e extends ur{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",_e.Geometry),this.registerInput("positions",_e.Vector3),this.registerOutput("output",_e.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 n=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 n=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 n=[],s=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{var s;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 n=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 n=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 n=t.type===_e.Float||t.type===_e.Int,s=i.type===_e.Float||i.type===_e.Int,a=n&&s;switch(this.operation){case dh.Add:{a?e=o=>t.getConnectedValue(o)+i.getConnectedValue(o):n?e=o=>o.adapt(t,i.type).add(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).add(o.adapt(i,t.type));break}case dh.Subtract:{a?e=o=>t.getConnectedValue(o)-i.getConnectedValue(o):n?e=o=>o.adapt(t,i.type).subtract(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).subtract(o.adapt(i,t.type));break}case dh.Multiply:{a?e=o=>t.getConnectedValue(o)*i.getConnectedValue(o):n?e=o=>o.adapt(t,i.type).multiply(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).multiply(o.adapt(i,t.type));break}case dh.Divide:{a?e=o=>t.getConnectedValue(o)/i.getConnectedValue(o):n?e=o=>o.adapt(t,i.type).divide(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).divide(o.adapt(i,t.type));break}case dh.Min:{if(a)e=o=>Math.min(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=n?[i,t]:[t,i];switch(o.type){case _e.Vector2:{e=c=>Ne.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}case _e.Vector3:{e=c=>O.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}case _e.Vector4:{e=c=>It.Minimize(o.getConnectedValue(c),c.adapt(l,o.type));break}}}break}case dh.Max:if(a)e=o=>Math.max(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=n?[i,t]:[t,i];switch(o.type){case _e.Vector2:{e=c=>Ne.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}case _e.Vector3:{e=c=>O.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}case _e.Vector4:{e=c=>It.Maximize(o.getConnectedValue(c),c.adapt(l,o.type));break}}break}}this.output._storedFunction=o=>t.type===_e.Int?e(o)|0:e(o)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${dh[this.operation]}; `}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===_e.Int||this.left.type===_e.Float&&this.right.type!==_e.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=[_e.Int,_e.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===_e.Int||t.type===_e.Float)&&e.acceptedConnectionPointTypes.push(_e.Vector2,_e.Vector3,_e.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}}V([Fi("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:dh.Add},{label:"Subtract",value:dh.Subtract},{label:"Multiply",value:dh.Multiply},{label:"Divide",value:dh.Divide},{label:"Max",value:dh.Max},{label:"Min",value:dh.Min}]})],y2e.prototype,"operation",void 0);xe("BABYLON.MathBlock",y2e);class Jje extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("fromMin",_e.Float,!0,0),this.registerInput("fromMax",_e.Float,!0,1),this.registerInput("toMin",_e.Float,!0,0),this.registerInput("toMax",_e.Float,!0,1),this.registerOutput("output",_e.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(_e.Vector2),this._inputs[0].excludedConnectionPointTypes.push(_e.Vector3),this._inputs[0].excludedConnectionPointTypes.push(_e.Vector4),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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),n=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),a=this.toMax.getConnectedValue(e),o=(t-i)/(n-i)*(a-s)+s;return this.output.type===_e.Int?Math.floor(o):o}}}xe("BABYLON.MapRangeBlock",Jje);var Hl;(function(r){r[r.Equal=0]="Equal",r[r.NotEqual=1]="NotEqual",r[r.LessThan=2]="LessThan",r[r.GreaterThan=3]="GreaterThan",r[r.LessOrEqual=4]="LessOrEqual",r[r.GreaterOrEqual=5]="GreaterOrEqual",r[r.Xor=6]="Xor",r[r.Or=7]="Or",r[r.And=8]="And"})(Hl||(Hl={}));class x2e extends ur{constructor(e){super(e),this.test=Hl.Equal,this.registerInput("left",_e.Float),this.registerInput("right",_e.Float,!0,0),this.registerInput("ifTrue",_e.AutoDetect,!0,1),this.registerInput("ifFalse",_e.AutoDetect,!0,0),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=_e.Float,this._inputs[0].acceptedConnectionPointTypes.push(_e.Int),this._inputs[1].acceptedConnectionPointTypes.push(_e.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),n=this.right.getConnectedValue(t);let s=!1;switch(this.test){case Hl.Equal:s=Xt.WithinEpsilon(i,n,Ki);break;case Hl.NotEqual:s=i!==n;break;case Hl.LessThan:s=in;break;case Hl.LessOrEqual:s=i<=n;break;case Hl.GreaterOrEqual:s=i>=n;break;case Hl.Xor:s=!!i&&!n||!i&&!!n;break;case Hl.Or:s=!!i||!!n;break;case Hl.And:s=!!i&&!!n;break}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Hl[this.test]}; `}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}V([Fi("Test",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Hl.Equal},{label:"NotEqual",value:Hl.NotEqual},{label:"LessThan",value:Hl.LessThan},{label:"GreaterThan",value:Hl.GreaterThan},{label:"LessOrEqual",value:Hl.LessOrEqual},{label:"GreaterOrEqual",value:Hl.GreaterOrEqual},{label:"Xor",value:Hl.Xor},{label:"Or",value:Hl.Or},{label:"And",value:Hl.And}]})],x2e.prototype,"test",void 0);xe("BABYLON.ConditionBlock",x2e);var cf;(function(r){r[r.None=0]="None",r[r.LoopID=1]="LoopID",r[r.InstanceID=2]="InstanceID",r[r.Once=3]="Once"})(cf||(cf={}));class b2e extends ur{constructor(e){super(e),this._currentLockId=-1,this.lockMode=cf.None,this.registerInput("min",_e.AutoDetect),this.registerInput("max",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.Texture),this._inputs[1].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[1].excludedConnectionPointTypes.push(_e.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 jo("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new jo("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case _e.Int:case _e.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,n=this.max.getConnectedValue(t)||0;return i+Math.random()*(n-i)};break}case _e.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||Ne.Zero(),n=this.max.getConnectedValue(t)||Ne.Zero();return new Ne(i.x+Math.random()*(n.x-i.x),i.y+Math.random()*(n.y-i.y))};break}case _e.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||O.Zero(),n=this.max.getConnectedValue(t)||O.Zero();return new O(i.x+Math.random()*(n.x-i.x),i.y+Math.random()*(n.y-i.y),i.z+Math.random()*(n.z-i.z))};break}case _e.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||It.Zero(),n=this.max.getConnectedValue(t)||It.Zero();return new It(i.x+Math.random()*(n.x-i.x),i.y+Math.random()*(n.y-i.y),i.z+Math.random()*(n.z-i.z),i.w+Math.random()*(n.w-i.w))};break}}this.lockMode===cf.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case cf.InstanceID:i=t.getContextualValue(On.InstanceID,!0)||0;break;case cf.LoopID:i=t.getContextualValue(On.LoopID,!0)||0;break;case cf.Once:i=t.buildId||0;break}return(this._currentLockId!==i||this.lockMode===cf.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${cf[this.lockMode]}; `}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}V([Fi("LockMode",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:cf.None},{label:"LoopID",value:cf.LoopID},{label:"InstanceID",value:cf.InstanceID},{label:"Once",value:cf.Once}]})],b2e.prototype,"lockMode",void 0);xe("BABYLON.RandomBlock",b2e);class e$e extends ur{constructor(e){super(e),this.registerInput("offset",_e.Vector3,!0,O.Zero()),this.registerInput("scale",_e.Float,!0,1),this.registerInput("octaves",_e.Float,!0,2,0,16),this.registerInput("roughness",_e.Float,!0,.5,0,1),this.registerOutput("output",_e.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,n){const s=e&15,a=s<8?t:i,o=s===12||s==14?t:n,l=s<4?i:o;return this._negateIf(a,s&a)+this._negateIf(l,s&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let n,s,a;return n=s=a=3735928584,a+=i,s+=t,n+=e,a^=s,a-=this._hashBitRotate(s,14),n^=a,n-=this._hashBitRotate(a,11),s^=n,s-=this._hashBitRotate(n,25),a^=s,a-=this._hashBitRotate(s,16),n^=a,n-=this._hashBitRotate(a,4),s^=n,s-=this._hashBitRotate(n,14),a^=s,a-=this._hashBitRotate(s,24),a}_mix(e,t,i,n,s,a,o,l,c,u,h){const d=1-c,f=1-u;return(1-h)*(f*(e*d+t*c)+u*(i*d+n*c))+h*(f*(s*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),n=(e.z|0)-(e.z<0?1:0),s=e.x-t,a=e.y-i,o=e.z-n,l=this._fade(s),c=this._fade(a),u=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,n),s,a,o),this._noiseGrad(this._hash(t+1,i,n),s-1,a,o),this._noiseGrad(this._hash(t,i+1,n),s,a-1,o),this._noiseGrad(this._hash(t+1,i+1,n),s-1,a-1,o),this._noiseGrad(this._hash(t,i,n+1),s,a,o-1),this._noiseGrad(this._hash(t+1,i,n+1),s-1,a,o-1),this._noiseGrad(this._hash(t,i+1,n+1),s,a-1,o-1),this._noiseGrad(this._hash(t+1,i+1,n+1),s-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,n,s){const a=new O(i.x*s+n.x,i.y*s+n.y,i.z*s+n.z);let o=1,l=1,c=0,u=0;e=Xt.Clamp(e,0,15);const h=e|0;for(let g=0;g<=h;g++){const m=this._perlin(a.scale(o));u+=m*l,c+=l,l*=Xt.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(On.Positions),i=this.octaves.getConnectedValue(e),n=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),a=this.scale.getConnectedValue(e);return this.noise(i,n,t,s,a)}}}xe("BABYLON.NoiseBlock",e$e);class C2e extends ur{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",_e.Geometry),this.registerInput("geometry1",_e.Geometry,!0),this.registerInput("geometry2",_e.Geometry,!0),this.registerInput("geometry3",_e.Geometry,!0),this.registerInput("geometry4",_e.Geometry,!0),this.registerOutput("output",_e.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 n=[];if(this.geometry0.isConnected){const o=this.geometry0.getConnectedValue(i);o&&n.push(o)}if(this.geometry1.isConnected){const o=this.geometry1.getConnectedValue(i);o&&n.push(o)}if(this.geometry2.isConnected){const o=this.geometry2.getConnectedValue(i);o&&n.push(o)}if(this.geometry3.isConnected){const o=this.geometry3.getConnectedValue(i);o&&n.push(o)}if(this.geometry4.isConnected){const o=this.geometry4.getConnectedValue(i);o&&n.push(o)}if(n.length===0)return null;let s=n[0].clone();const a=n.slice(1);return a.length&&s&&(s=s.merge(a,!0,!1,!0,!0)),s};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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],C2e.prototype,"evaluateContext",void 0);xe("BABYLON.MergeGeometryBlock",C2e);class A2e extends ur{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",_e.Geometry,!0),this.registerInput("geometry1",_e.Geometry,!0),this.registerInput("geometry2",_e.Geometry,!0),this.registerInput("geometry3",_e.Geometry,!0),this.registerInput("geometry4",_e.Geometry,!0),this.registerInput("geometry5",_e.Geometry,!0),this.registerInput("geometry6",_e.Geometry,!0),this.registerInput("geometry7",_e.Geometry,!0),this.registerInput("geometry8",_e.Geometry,!0),this.registerInput("geometry9",_e.Geometry,!0),this.registerOutput("output",_e.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,n){if(e.isConnected){const s=e.getConnectedValue(t);if(!s)return;s.metadata=s.metadata||{},s.metadata.collectionId=i,n.push(s)}}_buildBlock(e){const t=i=>{const n=[];return this._storeGeometry(this.geometry0,i,0,n),this._storeGeometry(this.geometry1,i,1,n),this._storeGeometry(this.geometry2,i,2,n),this._storeGeometry(this.geometry3,i,3,n),this._storeGeometry(this.geometry4,i,4,n),this._storeGeometry(this.geometry5,i,5,n),this._storeGeometry(this.geometry6,i,6,n),this._storeGeometry(this.geometry7,i,7,n),this._storeGeometry(this.geometry8,i,8,n),this._storeGeometry(this.geometry9,i,9,n),n.length?n[Math.round(Math.random()*(n.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}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],A2e.prototype,"evaluateContext",void 0);xe("BABYLON.GeometryCollectionBlock",A2e);class t$e extends ur{constructor(e){super(e),this.registerInput("input",_e.AutoDetect),this.registerOutput("output",_e.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=n=>i.getConnectedValue(n)}}xe("BABYLON.GeometryElbowBlock",t$e);class i$e extends ur{constructor(e){super(e),this.registerInput("geometry",_e.Geometry),this.registerOutput("output",_e.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=[]),vt.ComputeNormals(t.positions,t.indices,t.normals),t}}}xe("BABYLON.ComputeNormalsBlock",i$e);class r$e extends ur{constructor(e){super(e),this.registerInput("xyzw ",_e.Vector4,!0),this.registerInput("xyz ",_e.Vector3,!0),this.registerInput("xy ",_e.Vector2,!0),this.registerInput("zw ",_e.Vector2,!0),this.registerInput("x ",_e.Float,!0),this.registerInput("y ",_e.Float,!0),this.registerInput("z ",_e.Float,!0),this.registerInput("w ",_e.Float,!0),this.registerOutput("xyzw",_e.Vector4),this.registerOutput("xyz",_e.Vector3),this.registerOutput("xy",_e.Vector2),this.registerOutput("zw",_e.Vector2),this.registerOutput("x",_e.Float),this.registerOutput("y",_e.Float),this.registerOutput("z",_e.Float),this.registerOutput("w",_e.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,n=this.zIn,s=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,g=this.yOut,m=this.zOut,_=this.wOut,y=v=>{if(c.isConnected)return c.getConnectedValue(v);let x=0,b=0,C=0,A=0;if(t.isConnected&&(x=t.getConnectedValue(v)),i.isConnected&&(b=i.getConnectedValue(v)),n.isConnected&&(C=n.getConnectedValue(v)),s.isConnected&&(A=s.getConnectedValue(v)),a.isConnected){const E=a.getConnectedValue(v);E&&(x=E.x,b=E.y)}if(o.isConnected){const E=o.getConnectedValue(v);E&&(C=E.x,A=E.y)}if(l.isConnected){const E=l.getConnectedValue(v);E&&(x=E.x,b=E.y,C=E.z)}return new It(x,b,C,A)};u._storedFunction=v=>y(v),h._storedFunction=v=>{const x=y(v);return new O(x.x,x.y,x.z)},d._storedFunction=v=>{const x=y(v);return new Ne(x.x,x.y)},f._storedFunction=v=>{const x=y(v);return new Ne(x.z,x.w)},p._storedFunction=v=>y(v).x,g._storedFunction=v=>y(v).y,m._storedFunction=v=>y(v).z,_._storedFunction=v=>y(v).w}}xe("BABYLON.VectorConverterBlock",r$e);class n$e extends ur{constructor(e){super(e),this.registerInput("input",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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()}}xe("BABYLON.NormalizeVectorBlock",n$e);class S2e extends ur{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",_e.Geometry),this.registerInput("id",_e.Int,!0,0),this.registerOutput("output",_e.Geometry),this.id.acceptedConnectionPointTypes.push(_e.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 n=this.geometry.getConnectedValue(i);if(!n||!n.indices||!n.positions)return n;const s=new Y9;return s.materialIndex=this.id.getConnectedValue(i)|0,s.indexStart=0,s.indexCount=n.indices.length,s.verticesStart=0,s.verticesCount=n.positions.length/3,n.materialInfos=[s],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),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],S2e.prototype,"evaluateContext",void 0);xe("BABYLON.SetMaterialIDBlock",S2e);var xn;(function(r){r[r.Cos=0]="Cos",r[r.Sin=1]="Sin",r[r.Abs=2]="Abs",r[r.Exp=3]="Exp",r[r.Round=4]="Round",r[r.Floor=5]="Floor",r[r.Ceiling=6]="Ceiling",r[r.Sqrt=7]="Sqrt",r[r.Log=8]="Log",r[r.Tan=9]="Tan",r[r.ArcTan=10]="ArcTan",r[r.ArcCos=11]="ArcCos",r[r.ArcSin=12]="ArcSin",r[r.Sign=13]="Sign",r[r.Negate=14]="Negate",r[r.OneMinus=15]="OneMinus",r[r.Reciprocal=16]="Reciprocal",r[r.ToDegrees=17]="ToDegrees",r[r.ToRadians=18]="ToRadians",r[r.Fract=19]="Fract",r[r.Exp2=20]="Exp2"})(xn||(xn={}));class E2e extends ur{constructor(e){super(e),this.operation=xn.Cos,this.registerInput("input",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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 xn.Cos:{t=i=>Math.cos(i);break}case xn.Sin:{t=i=>Math.sin(i);break}case xn.Abs:{t=i=>Math.abs(i);break}case xn.Exp:{t=i=>Math.exp(i);break}case xn.Exp2:{t=i=>Math.pow(2,i);break}case xn.Round:{t=i=>Math.round(i);break}case xn.Floor:{t=i=>Math.floor(i);break}case xn.Ceiling:{t=i=>Math.ceil(i);break}case xn.Sqrt:{t=i=>Math.sqrt(i);break}case xn.Log:{t=i=>Math.log(i);break}case xn.Tan:{t=i=>Math.tan(i);break}case xn.ArcTan:{t=i=>Math.atan(i);break}case xn.ArcCos:{t=i=>Math.acos(i);break}case xn.ArcSin:{t=i=>Math.asin(i);break}case xn.Sign:{t=i=>Math.sign(i);break}case xn.Negate:{t=i=>-i;break}case xn.OneMinus:{t=i=>1-i;break}case xn.Reciprocal:{t=i=>1/i;break}case xn.ToRadians:{t=i=>i*Math.PI/180;break}case xn.ToDegrees:{t=i=>i*180/Math.PI;break}case xn.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 _e.Int:case _e.Float:{this.output._storedFunction=i=>{const n=this.input.getConnectedValue(i);return t(n)};break}case _e.Vector2:{this.output._storedFunction=i=>{const n=this.input.getConnectedValue(i);return new Ne(t(n.x),t(n.y))};break}case _e.Vector3:{this.output._storedFunction=i=>{const n=this.input.getConnectedValue(i);return new O(t(n.x),t(n.y),t(n.z))};break}case _e.Vector4:{this.output._storedFunction=i=>{const n=this.input.getConnectedValue(i);return new It(t(n.x),t(n.y),t(n.z),t(n.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.${xn[this.operation]}; `}}V([Fi("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:xn.Cos},{label:"Sin",value:xn.Sin},{label:"Abs",value:xn.Abs},{label:"Exp",value:xn.Exp},{label:"Exp2",value:xn.Exp2},{label:"Round",value:xn.Round},{label:"Floor",value:xn.Floor},{label:"Ceiling",value:xn.Ceiling},{label:"Sqrt",value:xn.Sqrt},{label:"Log",value:xn.Log},{label:"Tan",value:xn.Tan},{label:"ArcTan",value:xn.ArcTan},{label:"ArcCos",value:xn.ArcCos},{label:"ArcSin",value:xn.ArcSin},{label:"Sign",value:xn.Sign},{label:"Negate",value:xn.Negate},{label:"OneMinus",value:xn.OneMinus},{label:"Reciprocal",value:xn.Reciprocal},{label:"ToDegrees",value:xn.ToDegrees},{label:"ToRadians",value:xn.ToRadians},{label:"Fract",value:xn.Fract}]})],E2e.prototype,"operation",void 0);xe("BABYLON.GeometryTrigonometryBlock",E2e);class T2e extends ur{constructor(e){super(e),this._rotationMatrix=new pe,this._scalingMatrix=new pe,this._translationMatrix=new pe,this._scalingRotationMatrix=new pe,this._transformMatrix=new pe,this.evaluateContext=!0,this.registerInput("value",_e.AutoDetect),this.registerInput("matrix",_e.Matrix,!0),this.registerInput("translation",_e.Vector3,!0,O.Zero()),this.registerInput("rotation",_e.Vector3,!0,O.Zero()),this.registerInput("scaling",_e.Vector3,!0,O.One()),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.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 n=this.value.getConnectedValue(i);if(!n)return null;let s;if(this.matrix.isConnected)s=this.matrix.getConnectedValue(i);else{const a=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);pe.ScalingToRef(a.x,a.y,a.z,this._scalingMatrix),pe.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),pe.TranslationToRef(l.x,l.y,l.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),s=this._transformMatrix}switch(this.value.type){case _e.Geometry:{const a=n.clone();return a.transform(s),a}case _e.Vector2:return Ne.Transform(n,s);case _e.Vector3:return O.TransformCoordinates(n,s);case _e.Vector4:return It.TransformCoordinates(n,s)}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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],T2e.prototype,"evaluateContext",void 0);xe("BABYLON.GeometryTransformBlock",T2e);class s$e extends ur{constructor(e){super(e),this.registerInput("angle",_e.Float,!1,0),this.registerOutput("matrix",_e.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new jo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>pe.RotationX(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationXBlock",s$e);class a$e extends ur{constructor(e){super(e),this.registerInput("angle",_e.Float,!1,0),this.registerOutput("matrix",_e.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new jo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>pe.RotationY(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationYBlock",a$e);class o$e extends ur{constructor(e){super(e),this.registerInput("angle",_e.Float,!1,0),this.registerOutput("matrix",_e.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new jo("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>pe.RotationZ(this.angle.getConnectedValue(t))}}xe("BABYLON.RotationZBlock",o$e);class l$e extends ur{constructor(e){super(e),this.registerInput("scale",_e.Vector3,!1,O.One()),this.registerOutput("matrix",_e.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new jo("Scale");e.value=new O(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return pe.Scaling(i.x,i.y,i.z)}}}xe("BABYLON.ScalingBlock",l$e);class c$e extends ur{constructor(e){super(e),this.registerInput("source",_e.Vector3,!0,O.Up()),this.registerInput("target",_e.Vector3,!0,O.Left()),this.registerOutput("matrix",_e.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(),n=this.target.getConnectedValue(t).clone(),s=new pe;return i.normalize(),n.normalize(),pe.RotationAlignToRef(i,n,s,!0),s}}}xe("BABYLON.AlignBlock",c$e);class u$e extends ur{constructor(e){super(e),this.registerInput("translation",_e.Vector3,!1,O.Zero()),this.registerOutput("matrix",_e.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new jo("Translation");e.value=new O(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return pe.Translation(i.x,i.y,i.z)}}}xe("BABYLON.TranslationBlock",u$e);class Kee extends ur{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",_e.Geometry),this.registerInput("instance",_e.Geometry,!0),this.registerInput("density",_e.Float,!0,1,0,1),this.registerInput("matrix",_e.Matrix,!0),this.registerInput("rotation",_e.Vector3,!0,O.Zero()),this.registerInput("scaling",_e.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(_e.Float),this.registerOutput("output",_e.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 n=this._vertexData.positions.length/3;const s=[],a=new O,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,s)}else{const d=i.adaptInput(this.scaling,_e.Vector3,O.OneReadOnly),f=this.rotation.getConnectedValue(i)||O.ZeroReadOnly;i._instantiate(h,a,f,d,s)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),s.length)if(s.length===1)this._vertexData=s[0];else{const c=s.splice(0,1)[0];this._vertexData=c.merge(s,!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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Kee.prototype,"evaluateContext",void 0);V([Fi("Remove duplicated positions",0,"ADVANCED",{notifiers:{update:!0}})],Kee.prototype,"removeDuplicatedPositions",void 0);xe("BABYLON.InstantiateOnVerticesBlock",Kee);class M2e extends ur{constructor(e){super(e),this._currentPosition=new O,this._currentUV=new Ne,this._vertex0=new O,this._vertex1=new O,this._vertex2=new O,this._tempVector0=new O,this._tempVector1=new O,this._uv0=new Ne,this._uv1=new Ne,this._uv2=new Ne,this.evaluateContext=!0,this.registerInput("geometry",_e.Geometry),this.registerInput("instance",_e.Geometry,!0),this.registerInput("count",_e.Int,!0,256),this.registerInput("matrix",_e.Matrix,!0),this.registerInput("rotation",_e.Vector3,!0,O.Zero()),this.registerInput("scaling",_e.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(_e.Float),this.registerOutput("output",_e.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(),O.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 n=null;const s=this.count.getConnectedValue(i),a=this._vertexData.indices.length/3,o=s/a;let l=0;const c=[];let u=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=s);g++){let m=Math.random(),_=Math.random();if(m>_){const C=m;m=_,_=C}const y=m,v=_-m,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),n=this.instance.getConnectedValue(i),!n||!n.positions||n.positions.length===0){l-=o;continue}const b=n.clone();if(this.matrix.isConnected){const C=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(b,this._currentPosition,C,c)}else{const C=i.adaptInput(this.scaling,_e.Vector3,O.OneReadOnly),A=this.rotation.getConnectedValue(i)||O.ZeroReadOnly;i._instantiate(b,this._currentPosition,A,C,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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],M2e.prototype,"evaluateContext",void 0);xe("BABYLON.InstantiateOnFacesBlock",M2e);class Hee extends ur{constructor(e){super(e),this._currentPosition=new O,this._vertex0=new O,this._vertex1=new O,this._vertex2=new O,this.evaluateContext=!0,this.gridMode=!1,this.registerInput("geometry",_e.Geometry),this.registerInput("instance",_e.Geometry,!0),this.registerInput("count",_e.Int,!0,256),this.registerInput("matrix",_e.Matrix,!0),this.registerInput("rotation",_e.Vector3,!0,O.Zero()),this.registerInput("scaling",_e.Vector3,!0,O.One()),this.registerInput("gridSize",_e.Int,!0,10),this.scaling.acceptedConnectionPointTypes.push(_e.Float),this.registerOutput("output",_e.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,n){const s=(n-i)/t;return i+s/2+e*s}_getIndexinGrid(e,t,i,n){return e+t*n+i*n*n}_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 n=null;const s=this.count.getConnectedValue(i),a=[],o=JS(this._vertexData.positions,0,this._vertexData.positions.length/3),l=o.minimum,c=o.maximum,u=new O(.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&&m++}if(m%2===0){p--;continue}if(n=this.instance.getConnectedValue(i),!n||!n.positions||n.positions.length===0)continue;const _=n.clone();if(this.matrix.isConnected){const y=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,y,a)}else{const y=i.adaptInput(this.scaling,_e.Vector3,O.OneReadOnly),v=this.rotation.getConnectedValue(i)||O.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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],Hee.prototype,"evaluateContext",void 0);V([Fi("Grid mode",0,"MODES",{notifiers:{rebuild:!0}})],Hee.prototype,"gridMode",void 0);xe("BABYLON.InstantiateOnVolumeBlock",Hee);class jee extends ur{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",_e.Geometry,!0),this.registerInput("count",_e.Int,!0,1),this.registerOutput("output",_e.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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],jee.prototype,"evaluateContext",void 0);class h$e extends jee{constructor(e){super(e),this.registerInput("matrix",_e.Matrix,!0),this.registerInput("position",_e.Vector3,!0,O.Zero()),this.registerInput("rotation",_e.Vector3,!0,O.Zero()),this.registerInput("scaling",_e.Vector3,!0,O.One()),this.scaling.acceptedConnectionPointTypes.push(_e.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 n=this.count.getConnectedValue(i),s=[];for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const n=this.count.getConnectedValue(i),s=[],a=pe.Identity(),o=O.Zero(),l=O.Zero(),c=O.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const n=this.count.getConnectedValue(i),s=[],a=pe.Identity(),o=pe.Identity(),l=pe.Identity(),c=O.Zero(),u=O.Zero(),h=O.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}}xe("BABYLON.IntFloatConverterBlock",p$e);class m$e extends ur{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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 n=this.input.getConnectedValue(i);if(n==null)return this.log.push(["null",""]),n;switch(this.input.type){case _e.Vector2:this.log.push([Vje(n,4),n.toString()]);break;case _e.Vector3:this.log.push([Gje(n,4),n.toString()]);break;case _e.Vector4:this.log.push([Wje(n,4),n.toString()]);break;default:this.log.push([n.toString(),n.toString()]);break}return n};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}xe("BABYLON.DebugBlock",m$e);class g$e extends ur{constructor(e){super(e),this.registerInput("geometry",_e.Geometry),this.registerOutput("output",_e.Geometry),this.registerOutput("id",_e.Int),this.registerOutput("collectionId",_e.Int),this.registerOutput("verticesCount",_e.Int),this.registerOutput("facesCount",_e.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)}}xe("BABYLON.GeometryInfoBlock",g$e);var sg;(function(r){r[r.Spherical=0]="Spherical",r[r.Cylindrical=1]="Cylindrical",r[r.Cubic=2]="Cubic"})(sg||(sg={}));class R2e extends ur{constructor(e){super(e),this.mapping=sg.Spherical,this.registerInput("position",_e.Vector3),this.registerInput("normal",_e.Vector3),this.registerInput("center",_e.Vector3,!0,O.Zero()),this.registerOutput("uv",_e.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=O.Zero(),t=i=>{const n=this.position.getConnectedValue(i)||O.Zero(),s=this.normal.getConnectedValue(i)||O.Zero(),a=this.center.getConnectedValue(i),o=Ne.Zero();switch(this.mapping){case sg.Spherical:{n.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 sg.Cylindrical:{n.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 sg.Cubic:{const l=Math.abs(s.x),c=Math.abs(s.y),u=Math.abs(s.z),h=Math.max(Math.abs(n.x),Math.abs(n.y),Math.abs(n.z));let d=0,f=0;l>=c&&l>=u?(d=n.y/h-a.y,f=n.z/h-a.z):c>=l&&c>=u?(d=n.x/h-a.x,f=n.z/h-a.z):(d=n.x/h-a.x,f=n.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.${sg[this.mapping]}; `}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}V([Fi("Mapping",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:sg.Spherical},{label:"Cylindrical",value:sg.Cylindrical},{label:"Cubic",value:sg.Cubic}]})],R2e.prototype,"mapping",void 0);xe("BABYLON.MappingBlock",R2e);class _$e extends ur{constructor(e){super(e),this.registerInput("matrix0",_e.Matrix),this.registerInput("matrix1",_e.Matrix),this.registerOutput("output",_e.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)}}}xe("BABYLON.MatrixComposeBlock",_$e);class v$e extends ur{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",_e.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const n of this.endpoints)t.indexOf(n)===-1&&(i+=n._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)}}xe("BABYLON.TeleportInBlock",v$e);class y$e extends ur{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",_e.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}}xe("BABYLON.TeleportOutBlock",y$e);class I2e extends ur{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",_e.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const n=new Image,s=document.createElement("canvas"),a=s.getContext("2d");n.onload=()=>{s.width=n.width,s.height=n.height,a.drawImage(n,0,0);const l=a.getImageData(0,0,n.width,n.height).data,c=new Float32Array(l.length);for(let u=0;u{this._data=null,i()},n.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 n=e.getSize();aUe.GetTextureDataAsync(e,n.width,n.height).then(async s=>{const a=new Float32Array(s.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 n=this.coordinates.getConnectedValue(t);if(!n)return null;const s=this.clampCoordinates?Math.max(0,Math.min(n.x,1)):this._repeatClamp(n.x),a=this.clampCoordinates?Math.max(0,Math.min(n.y,1)):this._repeatClamp(n.y),o=Math.floor(s*(i.width-1)),l=Math.floor(a*(i.height-1)),c=o+i.width*l;return It.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}}V([Fi("Clamp Coordinates",0,"ADVANCED",{notifiers:{rebuild:!0}})],P2e.prototype,"clampCoordinates",void 0);xe("BABYLON.GeometryTextureFetchBlock",P2e);class x$e extends ur{constructor(e){super(e),this.registerInput("geometry",_e.Geometry),this.registerOutput("min",_e.Vector3),this.registerOutput("max",_e.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}}}xe("BABYLON.BoundingBlock",x$e);var ag;(function(r){r[r.Intersect=0]="Intersect",r[r.Subtract=1]="Subtract",r[r.Union=2]="Union"})(ag||(ag={}));class $ee extends ur{constructor(e){super(e),this.evaluateContext=!1,this.operation=ag.Intersect,this.registerInput("geometry0",_e.Geometry),this.registerInput("geometry1",_e.Geometry),this.registerOutput("output",_e.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 n=this.geometry0.getConnectedValue(i),s=this.geometry1.getConnectedValue(i);if(!n||!s)return null;const a=n.positions.length/3;!n.normals&&s.normals&&(n.normals=new Array(n.positions.length)),!s.normals&&n.normals&&(s.normals=new Array(s.positions.length)),!n.uvs&&s.uvs&&(n.uvs=new Array(a*2)),!s.uvs&&n.uvs&&(s.uvs=new Array(a*2)),!n.colors&&s.colors&&(n.colors=new Array(a*4)),!s.colors&&n.colors&&(s.colors=new Array(a*4));const o=Zm.FromVertexData(n),l=Zm.FromVertexData(s);let c;switch(this.operation){case ag.Intersect:c=o.intersect(l);break;case ag.Subtract:c=o.subtract(l);break;case ag.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.${ag[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)}}V([Fi("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],$ee.prototype,"evaluateContext",void 0);V([Fi("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:ag.Intersect},{label:"Subtract",value:ag.Subtract},{label:"Union",value:ag.Union}]})],$ee.prototype,"operation",void 0);xe("BABYLON.BooleanGeometryBlock",$ee);class b$e extends ur{constructor(e){super(e),this.registerInput("x",_e.AutoDetect),this.registerInput("y",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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),n=this.y.getConnectedValue(t);switch(this.x.type){case _e.Int:case _e.Float:return e(i,n);case _e.Vector2:return new Ne(e(i.x,n.x),e(i.y,n.y));case _e.Vector3:return new O(e(i.x,n.x),e(i.y,n.y),e(i.z,n.z));case _e.Vector4:return new It(e(i.x,n.x),e(i.y,n.y),e(i.z,n.z),e(i.w,n.w))}return 0}}}xe("BABYLON.GeometryArcTan2Block",b$e);class C$e extends ur{constructor(e){super(e),this.registerInput("left",_e.AutoDetect),this.registerInput("right",_e.AutoDetect),this.registerInput("gradient",_e.Float),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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,n)=>(1-t)*i+t*n;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),n=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case _e.Int:case _e.Float:return e(s,i,n);case _e.Vector2:return new Ne(e(s,i.x,n.x),e(s,i.y,n.y));case _e.Vector3:return new O(e(s,i.x,n.x),e(s,i.y,n.y),e(s,i.z,n.z));case _e.Vector4:return new It(e(s,i.x,n.x),e(s,i.y,n.y),e(s,i.z,n.z),e(s,i.w,n.w))}return 0},this}}xe("BABYLON.GeometryLerpBlock",C$e);class A$e extends ur{constructor(e){super(e),this.registerInput("left",_e.AutoDetect),this.registerInput("right",_e.AutoDetect),this.registerInput("gradient",_e.Float),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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,n)=>(1-t)*i+t*n;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),n=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case _e.Int:case _e.Float:return e(s,i,n);case _e.Vector2:{const a=new Ne(e(s,i.x,n.x),e(s,i.y,n.y));return a.normalize(),a}case _e.Vector3:{const a=new O(e(s,i.x,n.x),e(s,i.y,n.y),e(s,i.z,n.z));return a.normalize(),a}case _e.Vector4:{const a=new It(e(s,i.x,n.x),e(s,i.y,n.y),e(s,i.z,n.z),e(s,i.w,n.w));return a.normalize(),a}}return 0},this}}xe("BABYLON.GeometryNLerpBlock",A$e);class S$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("edge",_e.Float),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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),n=this.edge.getConnectedValue(t);switch(this.value.type){case _e.Int:case _e.Float:return e(i,n);case _e.Vector2:return new Ne(e(i.x,n),e(i.y,n));case _e.Vector3:return new O(e(i.x,n),e(i.y,n),e(i.z,n));case _e.Vector4:return new It(e(i.x,n),e(i.y,n),e(i.z,n),e(i.w,n))}return 0},this}}xe("BABYLON.GeometryStepBlock",S$e);class E$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("edge0",_e.Float),this.registerInput("edge1",_e.Float),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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,n)=>{const s=Math.max(0,Math.min((t-i)/(n-i),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),n=this.edge0.getConnectedValue(t),s=this.edge1.getConnectedValue(t);switch(this.value.type){case _e.Int:case _e.Float:return e(i,n,s);case _e.Vector2:return new Ne(e(i.x,n,s),e(i.y,n,s));case _e.Vector3:return new O(e(i.x,n,s),e(i.y,n,s),e(i.z,n,s));case _e.Vector4:return new It(e(i.x,n,s),e(i.y,n,s),e(i.z,n,s),e(i.w,n,s))}return 0},this}}xe("BABYLON.GeometrySmoothStepBlock",E$e);class T$e extends ur{constructor(e){super(e),this.registerInput("left",_e.AutoDetect),this.registerInput("right",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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),n=this.right.getConnectedValue(t);switch(this.left.type){case _e.Int:case _e.Float:return e(i,n);case _e.Vector2:return new Ne(e(i.x,n.x),e(i.y,n.y));case _e.Vector3:return new O(e(i.x,n.x),e(i.y,n.y),e(i.z,n.z));case _e.Vector4:return new It(e(i.x,n.x),e(i.y,n.y),e(i.z,n.z),e(i.w,n.w))}return 0},this}}xe("BABYLON.GeometryModBlock",T$e);class M$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("power",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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),n=this.power.getConnectedValue(t);switch(this.value.type){case _e.Int:case _e.Float:return e(i,n);case _e.Vector2:return new Ne(e(i.x,n),e(i.y,n));case _e.Vector3:return new O(e(i.x,n),e(i.y,n),e(i.z,n));case _e.Vector4:return new It(e(i.x,n),e(i.y,n),e(i.z,n),e(i.w,n))}return 0},this}}xe("BABYLON.GeometryPowBlock",M$e);class Xee extends ur{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Geometry),this._inputs[0].excludedConnectionPointTypes.push(_e.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 _e.Int:case _e.Float:return e(i);case _e.Vector2:return new Ne(e(i.x),e(i.y));case _e.Vector3:return new O(e(i.x),e(i.y),e(i.z));case _e.Vector4:return new It(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}}V([Fi("Minimum",1)],Xee.prototype,"minimum",void 0);V([Fi("Maximum",1)],Xee.prototype,"maximum",void 0);xe("BABYLON.GeometryClampBlock",Xee);class R$e extends ur{constructor(e){super(e),this.registerInput("left",_e.AutoDetect),this.registerInput("right",_e.AutoDetect),this.registerOutput("output",_e.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Int),this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.Vector2),this._inputs[1].excludedConnectionPointTypes.push(_e.Int),this._inputs[1].excludedConnectionPointTypes.push(_e.Float),this._inputs[1].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].excludedConnectionPointTypes.push(_e.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 _e.Vector3:return O.Cross(t,i);case _e.Vector4:return O.Cross(t.toVector3(),i.toVector3())}return 0},this}}xe("BABYLON.GeometryCrossBlock",R$e);var jr;(function(r){r[r.EaseInSine=0]="EaseInSine",r[r.EaseOutSine=1]="EaseOutSine",r[r.EaseInOutSine=2]="EaseInOutSine",r[r.EaseInQuad=3]="EaseInQuad",r[r.EaseOutQuad=4]="EaseOutQuad",r[r.EaseInOutQuad=5]="EaseInOutQuad",r[r.EaseInCubic=6]="EaseInCubic",r[r.EaseOutCubic=7]="EaseOutCubic",r[r.EaseInOutCubic=8]="EaseInOutCubic",r[r.EaseInQuart=9]="EaseInQuart",r[r.EaseOutQuart=10]="EaseOutQuart",r[r.EaseInOutQuart=11]="EaseInOutQuart",r[r.EaseInQuint=12]="EaseInQuint",r[r.EaseOutQuint=13]="EaseOutQuint",r[r.EaseInOutQuint=14]="EaseInOutQuint",r[r.EaseInExpo=15]="EaseInExpo",r[r.EaseOutExpo=16]="EaseOutExpo",r[r.EaseInOutExpo=17]="EaseInOutExpo",r[r.EaseInCirc=18]="EaseInCirc",r[r.EaseOutCirc=19]="EaseOutCirc",r[r.EaseInOutCirc=20]="EaseInOutCirc",r[r.EaseInBack=21]="EaseInBack",r[r.EaseOutBack=22]="EaseOutBack",r[r.EaseInOutBack=23]="EaseInOutBack",r[r.EaseInElastic=24]="EaseInElastic",r[r.EaseOutElastic=25]="EaseOutElastic",r[r.EaseInOutElastic=26]="EaseInOutElastic"})(jr||(jr={}));class w2e extends ur{constructor(e){super(e),this.type=jr.EaseInOutSine,this.registerInput("input",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[0].excludedConnectionPointTypes.push(_e.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 jr.EaseInSine:e=t=>1-Math.cos(t*3.1415/2);break;case jr.EaseOutSine:e=t=>Math.sin(t*3.1415/2);break;case jr.EaseInOutSine:e=t=>-(Math.cos(t*3.1415)-1)/2;break;case jr.EaseInQuad:e=t=>t*t;break;case jr.EaseOutQuad:e=t=>(1-t)*(1-t);break;case jr.EaseInOutQuad:{e=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break}case jr.EaseInCubic:e=t=>t*t*t;break;case jr.EaseOutCubic:{e=t=>1-Math.pow(1-t,3);break}case jr.EaseInOutCubic:{e=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;break}case jr.EaseInQuart:e=t=>t*t*t*t;break;case jr.EaseOutQuart:{e=t=>1-Math.pow(1-t,4);break}case jr.EaseInOutQuart:{e=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;break}case jr.EaseInQuint:e=t=>t*t*t*t*t;break;case jr.EaseOutQuint:{e=t=>1-Math.pow(1-t,5);break}case jr.EaseInOutQuint:{e=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;break}case jr.EaseInExpo:{e=t=>t===0?0:Math.pow(2,10*t-10);break}case jr.EaseOutExpo:{e=t=>t===1?1:1-Math.pow(2,-10*t);break}case jr.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 jr.EaseInCirc:{e=t=>1-Math.sqrt(1-Math.pow(t,2));break}case jr.EaseOutCirc:{e=t=>Math.sqrt(1-Math.pow(t-1,2));break}case jr.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 jr.EaseInBack:{e=t=>2.70158*t*t*t-1.70158*t*t;break}case jr.EaseOutBack:{e=t=>2.70158*Math.pow(t-1,3)+1.70158*Math.pow(t-1,2);break}case jr.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 jr.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 jr.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 jr.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 _e.Float:return e(i);case _e.Vector2:return new Ne(e(i.x),e(i.y));case _e.Vector3:return new O(e(i.x),e(i.y),e(i.z));case _e.Vector4:return new It(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.${jr[this.type]}; `}}V([Fi("Type",4,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:jr.EaseInSine},{label:"EaseOutSine",value:jr.EaseOutSine},{label:"EaseInOutSine",value:jr.EaseInOutSine},{label:"EaseInQuad",value:jr.EaseInQuad},{label:"EaseOutQuad",value:jr.EaseOutQuad},{label:"EaseInOutQuad",value:jr.EaseInOutQuad},{label:"EaseInCubic",value:jr.EaseInCubic},{label:"EaseOutCubic",value:jr.EaseOutCubic},{label:"EaseInOutCubic",value:jr.EaseInOutCubic},{label:"EaseInQuart",value:jr.EaseInQuart},{label:"EaseOutQuart",value:jr.EaseOutQuart},{label:"EaseInOutQuart",value:jr.EaseInOutQuart},{label:"EaseInQuint",value:jr.EaseInQuint},{label:"EaseOutQuint",value:jr.EaseOutQuint},{label:"EaseInOutQuint",value:jr.EaseInOutQuint},{label:"EaseInExpo",value:jr.EaseInExpo},{label:"EaseOutExpo",value:jr.EaseOutExpo},{label:"EaseInOutExpo",value:jr.EaseInOutExpo},{label:"EaseInCirc",value:jr.EaseInCirc},{label:"EaseOutCirc",value:jr.EaseOutCirc},{label:"EaseInOutCirc",value:jr.EaseInOutCirc},{label:"EaseInBack",value:jr.EaseInBack},{label:"EaseOutBack",value:jr.EaseOutBack},{label:"EaseInOutBack",value:jr.EaseInOutBack},{label:"EaseInElastic",value:jr.EaseInElastic},{label:"EaseOutElastic",value:jr.EaseOutElastic},{label:"EaseInOutElastic",value:jr.EaseInOutElastic}]})],w2e.prototype,"type",void 0);xe("BABYLON.GeometryCurveBlock",w2e);class I$e extends ur{constructor(e){super(e),this.registerInput("color",_e.Vector3),this.registerInput("level",_e.Float,!0,0),this.registerOutput("output",_e.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),n=Math.min(t.x,t.y,t.z),s=Math.max(t.x,t.y,t.z),a=.5*(n+s);return new O(t.x*(1-i)+a*i,t.y*(1-i)+a*i,t.z*(1-i)+a*i)},this}}xe("BABYLON.GeometryDesaturateBlock",I$e);class P$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("steps",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(_e.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 n=i;if(this.steps.type===_e.Float)switch(this.value.type){case _e.Vector2:n=new Ne(i,i);break;case _e.Vector3:n=new O(i,i,i);break;case _e.Vector4:n=new It(i,i,i,i);break}switch(this.value.type){case _e.Vector2:return new Ne(t.x/(1/n.x)*(1/n.x),t.y/(1/n.y)*(1/n.y));case _e.Vector3:return new O(t.x/(1/n.x)*(1/n.x),t.y/(1/n.y)*(1/n.y),t.z/(1/n.z)*(1/n.z));case _e.Vector4:return new It(t.x/(1/n.x)*(1/n.x),t.y/(1/n.y)*(1/n.y),t.z/(1/n.z)*(1/n.z),t.w/(1/n.w)*(1/n.w));default:return Math.floor(t/(1/i)*(1/i))}},this}}xe("BABYLON.GeometryPosterizeBlock",P$e);class w$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerInput("reference",_e.AutoDetect),this.registerInput("distance",_e.Float),this.registerInput("replacement",_e.AutoDetect),this.registerOutput("output",_e.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].excludedConnectionPointTypes.push(_e.Float),this._inputs[1].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[3].excludedConnectionPointTypes.push(_e.Float),this._inputs[3].excludedConnectionPointTypes.push(_e.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),n=this.distance.getConnectedValue(e),s=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}}xe("BABYLON.GeometryDistanceBlock",D$e);class O$e extends ur{constructor(e){super(e),this.registerInput("left",_e.AutoDetect),this.registerInput("right",_e.AutoDetect),this.registerOutput("output",_e.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(_e.Int),this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Matrix),this._inputs[1].excludedConnectionPointTypes.push(_e.Float),this._inputs[1].excludedConnectionPointTypes.push(_e.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}}xe("BABYLON.GeometryDotBlock",O$e);class L$e extends ur{constructor(e){super(e),this.registerInput("value",_e.AutoDetect),this.registerOutput("output",_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.Int),this._inputs[0].excludedConnectionPointTypes.push(_e.Float),this._inputs[0].excludedConnectionPointTypes.push(_e.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}}xe("BABYLON.GeometryLengthBlock",L$e);class N$e extends ur{constructor(e){super(e),this.registerInput("input",_e.Vector2),this.registerInput("angle",_e.Float),this.registerOutput("output",_e.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 Ne(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this}}xe("BABYLON.GeometryRotate2dBlock",N$e);class $v extends Re{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=pe.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._splatPositions=null;const n=new vt;n.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],n.indices=[0,1,2,0,2,3],n.applyToMesh(this),this.subMeshes=[],new yc(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 pw(this.name+"_material",this._scene),this.material=this._material);const n=this.getScene().getFrameId();if(n!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix),oe.Vector3[0].set(this._lastModelViewMatrix[8],this._lastModelViewMatrix[9],this._lastModelViewMatrix[10]),oe.Vector3[1].set(this._modelViewMatrix.m[8],this._modelViewMatrix.m[9],this._modelViewMatrix.m[10]),oe.Vector3[0].normalize(),oe.Vector3[1].normalize();const s=O.Dot(oe.Vector3[0],oe.Vector3[1]);Math.abs(s-1)>=.01&&(this._frameIdLastUpdate=n,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)),n=`end_header `,s=i.indexOf(n);if(s<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,s).split(` `).filter(m=>m.startsWith("property "));for(const m of u){const[,_,y]=m.split(" ");if(c.push({name:y,type:_,offset:o}),l[_])o+=l[_];else return ge.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,s+n.length),p=new ArrayBuffer(h*a),g=new Oe;for(let m=0;m{this._loadData($v.ConvertPLYToSplat(t))})}dispose(e){var t,i,n,s,a,o;(t=this._covariancesATexture)==null||t.dispose(),(i=this._covariancesBTexture)==null||i.dispose(),(n=this._centersTexture)==null||n.dispose(),(s=this._colorsTexture)==null||s.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,n,s;this._covariancesATexture=(t=e.covariancesATexture)==null?void 0:t.clone(),this._covariancesBTexture=(i=e.covariancesBTexture)==null?void 0:i.clone(),this._centersTexture=(n=e.centersTexture)==null?void 0:n.clone(),this._colorsTexture=(s=e.colorsTexture)==null?void 0:s.clone()}clone(e=""){const t=new $v(e,void 0,this.getScene());t._copySource(this),t.makeGeometryUnique(),t._vertexCount=this._vertexCount,t._copyTextures(this),t._modelViewMatrix=pe.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),n=3*4+3*4+4+4,s=t.length/n;this._vertexCount=s;const a=this._getTextureSize(s),o=a.x*a.y;this._splatPositions=new Float32Array(3*o);const l=new Float32Array(3*o),c=new Float32Array(3*o),u=oe.Matrix[0],h=oe.Matrix[1],d=oe.Quaternion[0],f=new O(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new O(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let v=0;vnew Vs(v,x,b,C,this._scene,!1,!1,2,1),_=v=>{const x=v.length/3,b=new Float32Array(x*4);for(let C=0;C{this._depthMix=s.data.depthMix;const a=new Uint32Array(s.data.depthMix.buffer);for(let o=0;oi&&(ge.Error("GaussianSplatting texture size: ("+i+", "+n+"), maxTextureSize: "+i),n=i),new Ne(i,n)}}$v._CreateWorker=function(r){let e=0,t,i,n,s;r.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,n=new Uint32Array(i.buffer),s=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 }`;me.ShadersStoreWGSL[F$e]=B$e;const k$e={name:F$e,shader:B$e},WRt=Object.freeze(Object.defineProperty({__proto__:null,colorPixelShaderWGSL:k$e},Symbol.toStringTag,{value:"Module"})),U$e="colorVertexShader",z$e=`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 }`;me.ShadersStoreWGSL[U$e]=z$e;const V$e={name:U$e,shader:z$e},KRt=Object.freeze(Object.defineProperty({__proto__:null,colorVertexShaderWGSL:V$e},Symbol.toStringTag,{value:"Module"})),G$e="meshUVSpaceRendererVertexShader",W$e=`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);}`;me.ShadersStore[G$e]=W$e;const K$e={name:G$e,shader:W$e},HRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererVertexShader:K$e},Symbol.toStringTag,{value:"Module"})),H$e="meshUVSpaceRendererPixelShader",j$e=`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);} `;me.ShadersStore[H$e]=j$e;const $$e={name:H$e,shader:j$e},jRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererPixelShader:$$e},Symbol.toStringTag,{value:"Module"})),X$e="meshUVSpaceRendererMaskerVertexShader",Y$e="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;}";me.ShadersStore[X$e]=Y$e;const Q$e={name:X$e,shader:Y$e},$Rt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerVertexShader:Q$e},Symbol.toStringTag,{value:"Module"})),Z$e="meshUVSpaceRendererMaskerPixelShader",q$e=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} `;me.ShadersStore[Z$e]=q$e;const J$e={name:Z$e,shader:q$e},XRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerPixelShader:J$e},Symbol.toStringTag,{value:"Module"})),eXe="meshUVSpaceRendererFinaliserPixelShader",tXe=`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;}}} `;me.ShadersStore[eXe]=tXe;const iXe={name:eXe,shader:tXe},YRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserPixelShader:iXe},Symbol.toStringTag,{value:"Module"})),rXe="meshUVSpaceRendererFinaliserVertexShader",nXe=`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;} `;me.ShadersStore[rXe]=nXe;const sXe={name:rXe,shader:nXe},QRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserVertexShader:sXe},Symbol.toStringTag,{value:"Module"})),aXe="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);}`;me.ShadersStoreWGSL[aXe]=oXe;const lXe={name:aXe,shader:oXe},ZRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererVertexShaderWGSL:lXe},Symbol.toStringTag,{value:"Module"})),cXe="meshUVSpaceRendererPixelShader",uXe=`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);} `;me.ShadersStoreWGSL[cXe]=uXe;const hXe={name:cXe,shader:uXe},qRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererPixelShaderWGSL:hXe},Symbol.toStringTag,{value:"Module"})),dXe="meshUVSpaceRendererMaskerVertexShader",fXe=`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;}`;me.ShadersStoreWGSL[dXe]=fXe;const pXe={name:dXe,shader:fXe},JRt=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerVertexShaderWGSL:pXe},Symbol.toStringTag,{value:"Module"})),mXe="meshUVSpaceRendererMaskerPixelShader",gXe=`varying vUV: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);} `;me.ShadersStoreWGSL[mXe]=gXe;const _Xe={name:mXe,shader:gXe},e8t=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererMaskerPixelShaderWGSL:_Xe},Symbol.toStringTag,{value:"Module"})),vXe="meshUVSpaceRendererFinaliserPixelShader",yXe=`#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;}}} `;me.ShadersStoreWGSL[vXe]=yXe;const xXe={name:vXe,shader:yXe},t8t=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserPixelShaderWGSL:xXe},Symbol.toStringTag,{value:"Module"})),bXe="meshUVSpaceRendererFinaliserVertexShader",CXe=`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;} `;me.ShadersStoreWGSL[bXe]=CXe;const AXe={name:bXe,shader:CXe},i8t=Object.freeze(Object.defineProperty({__proto__:null,meshUVSpaceRendererFinaliserVertexShaderWGSL:AXe},Symbol.toStringTag,{value:"Module"}));class r8t{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"?ge.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,!this.isSupported()){ge.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?ge.Warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&ge.Warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;let n,s,a;const o=[],l=[];let c=0;for(n=0;n{this.update(n.getEngine().getDeltaTime()*.001*e.timeFactor)})}addAgent(e,t,i){const n=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;n.radius=t.radius,n.height=t.height,n.maxAcceleration=t.maxAcceleration,n.maxSpeed=t.maxSpeed,n.collisionQueryRange=t.collisionQueryRange,n.pathOptimizationRange=t.pathOptimizationRange,n.separationWeight=t.separationWeight,n.updateFlags=7,n.obstacleAvoidanceType=0,n.queryFilterType=0,n.userData=0;const s=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),n);return this.transforms.push(i),this.agents.push(s),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new O(0,0,0)),s}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new O(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 O(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 O(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<=Ki)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=Ki)this.recastCrowd.update(e);else{let n=Math.floor(e/t);i&&n>i&&(n=i),n<1&&(n=1);const s=e/n;for(let a=0;au&&a.ynew uh(r,e,t);class uh{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=uh._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,uh.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ie.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 n=!1,s=i();const a=new oa;navigator.onLine&&(n=!0,s=s+(s.match(/\?/)==null?"?":"&")+Date.now()),a.open("GET",s),a.addEventListener("load",()=>{if(a.status===200||uh._ValidateXHRData(a,1))try{const o=JSON.parse(a.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&uh._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),a.addEventListener("error",()=>{if(n){n=!1;const o=i();a.open("GET",o),a.send()}else t()},!1);try{a.send()}catch{ge.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 n=this._idbFactory.open("babylonjs",1);n.onerror=()=>{i()},n.onblocked=()=>{ge.Error("IDB request blocked. Please reload the page."),i()},n.onsuccess=()=>{this._db=n.result,e()},n.onupgradeneeded=s=>{if(this._db=s.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){ge.Error("Error while creating object stores. Exception: "+a.message),i()}}}}loadImage(e,t){const i=uh._ReturnFullUrlLocation(e),n=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?n():this._loadImageFromDBAsync(i,t,n)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let n;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let o;n&&typeof URL=="function"?(o=URL.createObjectURL(n.data),t.onerror=()=>{ge.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const a=s.objectStore("textures").get(e);a.onsuccess=o=>{n=o.target.result},a.onerror=()=>{ge.Error("Error loading texture "+e+" from DB."),t.src=e}}else ge.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 n=()=>{let s;if(i&&typeof URL=="function")try{s=URL.createObjectURL(i)}catch{s=URL.createObjectURL(i)}s&&(t.src=s)};if(uh._IsUASupportingBlobStorage){const s=new oa;s.open("GET",e),s.responseType="blob",s.addEventListener("load",()=>{if(s.status===200&&this._db){i=s.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{}n()},a.oncomplete=()=>{n()};const o={textureUrl:e,data:i};try{const l=a.objectStore("textures").put(o);l.onsuccess=()=>{},l.onerror=()=>{n()}}catch(l){l.code===25&&(uh._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),s.addEventListener("error",()=>{ge.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),s.send()}else t.src=e}else ge.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 n;try{const s=this._db.transaction(["versions"]);s.oncomplete=()=>{n?this._manifestVersionFound!==n.data?(this._mustUpdateRessources=!0,i()):t(n.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};const a=s.objectStore("versions").get(e);a.onsuccess=o=>{n=o.target.result},a.onerror=()=>{ge.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(s){ge.Error("Error while accessing 'versions' object store (READ OP). Exception: "+s.message),t(-1)}}else ge.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 n={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(n);s.onsuccess=()=>{},s.onerror=()=>{ge.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){ge.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,n,s){const a=uh._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(a,t,i,s,n)};this._checkVersionFromDB(a,l=>{l!==-1?this._mustUpdateRessources?this._saveFileAsync(a,t,i,s,n):this._loadFileAsync(a,t,o,i):n&&n()})}_loadFileAsync(e,t,i,n){if(this._isSupported&&this._db){let s;e.indexOf(".babylon")!==-1?s="scenes":s="textures";let a;const o=this._db.transaction([s]);o.oncomplete=()=>{var c;if(a){if(n){const u=((c=a.data)==null?void 0:c.byteLength)||0;n({total:u,loaded:u,lengthComputable:!0})}t(a.data)}else i()},o.onabort=()=>{i()};const l=o.objectStore(s).get(e);l.onsuccess=c=>{a=c.target.result},l.onerror=()=>{ge.Error("Error loading file "+e+" from DB."),i()}}else ge.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,n,s){if(this._isSupported){let a;e.indexOf(".babylon")!==-1?a="scenes":a="textures";const o=new oa;let l;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),n&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&uh._ValidateXHRData(o,n?6:1))if(l=n?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=()=>{ge.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{ge.Error("error on XHR request."),s&&s()},!1),o.send()}else ge.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}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=uV(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}}uh._IsUASupportingBlobStorage=!0;uh.IDBStorageEnabled=!1;uh._ParseURL=r=>{const e=document.createElement("a");e.href=r;const t=r.substring(0,r.lastIndexOf("#")),i=r.substring(t.lastIndexOf("/")+1,r.length);return r.substring(0,r.indexOf(i,0))};uh._ReturnFullUrlLocation=r=>r.indexOf("http:/")===-1&&r.indexOf("https:/")===-1&&typeof window<"u"?uh._ParseURL(window.location.href)+r:r;class Xv{constructor(){this.direction1=new O(0,1,0),this.direction2=new O(0,1,0),this.minEmitBox=new O(-.5,-.5,-.5),this.maxEmitBox=new O(.5,.5,.5)}startDirectionFunction(e,t,i,n){const s=Qn(this.direction1.x,this.direction2.x),a=Qn(this.direction1.y,this.direction2.y),o=Qn(this.direction1.z,this.direction2.z);if(n){t.x=s,t.y=a,t.z=o;return}O.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,n){const s=Qn(this.minEmitBox.x,this.maxEmitBox.x),a=Qn(this.minEmitBox.y,this.maxEmitBox.y),o=Qn(this.minEmitBox.z,this.maxEmitBox.z);if(n){t.x=s,t.y=a,t.z=o;return}O.TransformCoordinatesFromFloatsToRef(s,a,o,e,t)}clone(){const e=new Xv;return bc.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){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2),O.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),O.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class fD{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,n){n?oe.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),oe.Vector3[0]).normalize();const s=Xt.RandomRange(0,this.directionRandomizer),a=Xt.RandomRange(0,this.directionRandomizer),o=Xt.RandomRange(0,this.directionRandomizer);t.x=oe.Vector3[0].x+s,t.y=oe.Vector3[0].y+a,t.z=oe.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,n){const s=Xt.RandomRange(0,Math.PI*2);let a;this.emitFromSpawnPointOnly?a=1e-4:(a=Xt.RandomRange(0,this.heightRange),a=1-a*a);let o=this._radius-Xt.RandomRange(0,this._radius*this.radiusRange);o=o*a;const l=o*Math.sin(s),c=o*Math.cos(s),u=a*this._height;if(n){t.x=l,t.y=u,t.z=c;return}O.TransformCoordinatesFromFloatsToRef(l,u,c,e,t)}clone(){const e=new fD(this._radius,this._angle,this.directionRandomizer);return bc.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 mV extends fD{constructor(e=1,t=Math.PI,i=new O(0,1,0),n=new O(0,1,0)){super(e,t),this.direction1=i,this.direction2=n}startDirectionFunction(e,t){const i=Xt.RandomRange(this.direction1.x,this.direction2.x),n=Xt.RandomRange(this.direction1.y,this.direction2.y),s=Xt.RandomRange(this.direction1.z,this.direction2.z);O.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new mV(this.radius,this.angle,this.direction1,this.direction2);return bc.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 pD{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=O.Zero()}startDirectionFunction(e,t,i,n,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),O.TransformNormalToRef(this._tempVector,s,this._tempVector);const a=Xt.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=Xt.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(),n){t.copyFrom(this._tempVector);return}O.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const s=Xt.RandomRange(-this.height/2,this.height/2),a=Xt.RandomRange(0,2*Math.PI),o=Xt.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(n){t.copyFromFloats(c,s,u);return}O.TransformCoordinatesFromFloatsToRef(c,s,u,e,t)}clone(){const e=new pD(this.radius,this.directionRandomizer);return bc.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 gV extends pD{constructor(e=1,t=1,i=1,n=new O(0,1,0),s=new O(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=s}startDirectionFunction(e,t,i,n){const s=Xt.RandomRange(this.direction1.x,this.direction2.x),a=Xt.RandomRange(this.direction1.y,this.direction2.y),o=Xt.RandomRange(this.direction1.z,this.direction2.z);if(n){t.copyFromFloats(s,a,o);return}O.TransformNormalFromFloatsToRef(s,a,o,e,t)}clone(){const e=new gV(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return bc.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),O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2)}}class _V{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),a=Xt.RandomRange(0,this.directionRandomizer),o=Xt.RandomRange(0,this.directionRandomizer),l=Xt.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=o,s.z+=l,s.normalize(),n){t.copyFrom(s);return}O.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-Xt.RandomRange(0,this.radius*this.radiusRange),a=Xt.RandomRange(0,1),o=Xt.RandomRange(0,2*Math.PI),l=Math.acos(2*a-1),c=s*Math.cos(o)*Math.sin(l),u=s*Math.cos(l),h=s*Math.sin(o)*Math.sin(l);if(n){t.copyFromFloats(c,Math.abs(u),h);return}O.TransformCoordinatesFromFloatsToRef(c,Math.abs(u),h,e,t)}clone(){const e=new _V(this.radius,this.directionRandomizer);return bc.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 vV{constructor(){this.direction1=new O(0,1,0),this.direction2=new O(0,1,0)}startDirectionFunction(e,t,i,n){const s=Xt.RandomRange(this.direction1.x,this.direction2.x),a=Xt.RandomRange(this.direction1.y,this.direction2.y),o=Xt.RandomRange(this.direction1.z,this.direction2.z);if(n){t.copyFromFloats(s,a,o);return}O.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,n){if(n){t.copyFromFloats(0,0,0);return}O.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new vV;return bc.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){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2)}}class mD{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),a=Xt.RandomRange(0,this.directionRandomizer),o=Xt.RandomRange(0,this.directionRandomizer),l=Xt.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=o,s.z+=l,s.normalize(),n){t.copyFrom(s);return}O.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-Xt.RandomRange(0,this.radius*this.radiusRange),a=Xt.RandomRange(0,1),o=Xt.RandomRange(0,2*Math.PI),l=Math.acos(2*a-1),c=s*Math.cos(o)*Math.sin(l),u=s*Math.cos(l),h=s*Math.sin(o)*Math.sin(l);if(n){t.copyFromFloats(c,u,h);return}O.TransformCoordinatesFromFloatsToRef(c,u,h,e,t)}clone(){const e=new mD(this.radius,this.directionRandomizer);return bc.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 yV extends mD{constructor(e=1,t=new O(0,1,0),i=new O(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=Xt.RandomRange(this.direction1.x,this.direction2.x),n=Xt.RandomRange(this.direction1.y,this.direction2.y),s=Xt.RandomRange(this.direction1.z,this.direction2.z);O.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new yV(this.radius,this.direction1,this.direction2);return bc.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 Yv{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,n){const s=oe.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const a=oe.Vector3[1];s.subtractToRef(i.position,a),a.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(n){t.copyFrom(s);return}O.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,n){const s=oe.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),n){t.copyFrom(s);return}O.TransformCoordinatesToRef(s,e,t)}clone(){const e=new Yv;return bc.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 Yee{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(ee.PositionKind),this._normals=e.getVerticesData(ee.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=O.Zero(),this._mesh=null,this.direction1=new O(0,1,0),this.direction2=new O(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals){O.TransformNormalToRef(this._storedNormal,e,t);return}const s=Xt.RandomRange(this.direction1.x,this.direction2.x),a=Xt.RandomRange(this.direction1.y,this.direction2.y),o=Xt.RandomRange(this.direction1.z,this.direction2.z);if(n){t.copyFromFloats(s,a,o);return}O.TransformNormalFromFloatsToRef(s,a,o,e,t)}startPositionFunction(e,t,i,n){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,a=Math.random(),o=Math.random()*(1-a),l=1-a-o,c=this._indices[s],u=this._indices[s+1],h=this._indices[s+2],d=oe.Vector3[0],f=oe.Vector3[1],p=oe.Vector3[2],g=oe.Vector3[3];O.FromArrayToRef(this._positions,c*3,d),O.FromArrayToRef(this._positions,u*3,f),O.FromArrayToRef(this._positions,h*3,p),g.x=a*d.x+o*f.x+l*p.x,g.y=a*d.y+o*f.y+l*p.y,g.z=a*d.z+o*f.z+l*p.z,n?t.copyFromFloats(g.x,g.y,g.z):O.TransformCoordinatesFromFloatsToRef(g.x,g.y,g.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(O.FromArrayToRef(this._normals,c*3,d),O.FromArrayToRef(this._normals,u*3,f),O.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 Yee(this.mesh);return bc.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){O.FromArrayToRef(e.direction1,0,this.direction1),O.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class EXe{_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 n8t="gpuUpdateParticlesPixelShader",s8t=`#version 300 es void main() {discard;} `;me.ShadersStore[n8t]=s8t;const a8t="gpuUpdateParticlesVertexShader",o8t=`#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 }}`;me.ShadersStore[a8t]=o8t;class TXe{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 Yv&&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 Sr("gpuUpdateParticles",this._updateEffectOptions,this._engine),new EXe(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 n=this._engine;n.bindTransformFeedbackBuffer(t.getBuffer()),n.setRasterizerState(!1),n.beginTransformFeedback(!0),n.drawArraysType(3,0,i),n.endTransformFeedback(),n.setRasterizerState(!0),n.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 }} `;me.ShadersStoreWGSL[l8t]=c8t;class MXe{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 cg("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:t,defines:e.split(` `)}),(i=this._simParamsComputeShader)==null||i.dispose(),this._simParamsComputeShader=new Ci(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 EXe(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new Q9(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 s=0;s=a.gradient&&e<=o.gradient){const l=(e-a.gradient)/(o.gradient-a.gradient);i(a,o,l);return}}const n=t.length-1;i(t[n],t[n],1)}}class gw{constructor(e){this.particleSystem=e,this.position=O.Zero(),this.direction=O.Zero(),this.color=new at(0,0,0,0),this.colorStep=new at(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new Ne(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new at(0,0,0,0),this._currentColor2=new at(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=gw._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 n;this._initialSpriteCellLoop?n=za(e*t%this.lifeTime/this.lifeTime):n=za(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+n*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=oe.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,oe.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(oe.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=gw._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 It(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()))}}gw._Count=0;class h5 extends El{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 pl(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 Ce),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,n=null,s=!1,a=.01){super(e),this._emitterInverseWorldMatrix=pe.Identity(),this._inheritedVelocityOffset=new O,this.onDisposeObservable=new Ce,this.onStoppedObservable=new Ce,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new at(0,0,0,0),this._colorDiff=new at(0,0,0,0),this._scaledDirection=O.Zero(),this._scaledGravity=O.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 gw(this),this._prepareParticle(l),l},this._shadersLoaded=!1,this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=s,!i||i.getClassName()==="Scene"?(this._scene=i||ei.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=pe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._initShaderSourceAsync(),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new pl(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new Xv;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-g;p=(f.lifeTime-g)*p/y,f.age=f.lifeTime}const m=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?xd.GetCurrentGradient(m,this._colorGradients,(y,v,x)=>{y!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),v.getColorToRef(f._currentColor2),f._currentColorGradient=y),at.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&&xd.GetCurrentGradient(m,this._angularSpeedGradients,(y,v,x)=>{y!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=v.getFactor(),f._currentAngularSpeedGradient=y),f.angularSpeed=ef(f._currentAngularSpeed1,f._currentAngularSpeed2,x)}),f.angle+=f.angularSpeed*p;let _=p;if(this._velocityGradients&&this._velocityGradients.length>0&&xd.GetCurrentGradient(m,this._velocityGradients,(y,v,x)=>{y!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=v.getFactor(),f._currentVelocityGradient=y),_*=ef(f._currentVelocity1,f._currentVelocity2,x)}),f.direction.scaleToRef(_,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&xd.GetCurrentGradient(m,this._limitVelocityGradients,(y,v,x)=>{y!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=v.getFactor(),f._currentLimitVelocityGradient=y);const b=ef(f._currentLimitVelocity1,f._currentLimitVelocity2,x);f.direction.length()>b&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&xd.GetCurrentGradient(m,this._dragGradients,(y,v,x)=>{y!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=v.getFactor(),f._currentDragGradient=y);const b=ef(f._currentDrag1,f._currentDrag2,x);this._scaledDirection.scaleInPlace(1-b)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),O.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),b=oe.Vector3[0],C=oe.Vector3[1];b.copyFromFloats((2*y-1)*this.noiseStrength.x,(2*v-1)*this.noiseStrength.y,(2*x-1)*this.noiseStrength.z),b.scaleToRef(p,C),f.direction.addInPlace(C)}if(this.gravity.scaleToRef(p,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&xd.GetCurrentGradient(m,this._sizeGradients,(y,v,x)=>{y!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=v.getFactor(),f._currentSizeGradient=y),f.size=ef(f._currentSize1,f._currentSize2,x)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&xd.GetCurrentGradient(m,this._colorRemapGradients,(y,v,x)=>{const b=ef(y.factor1,v.factor1,x),C=ef(y.factor2,v.factor2,x);f.remapData.x=b,f.remapData.y=C-b}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&xd.GetCurrentGradient(m,this._alphaRemapGradients,(y,v,x)=>{const b=ef(y.factor1,v.factor1,x),C=ef(y.factor2,v.factor2,x);f.remapData.z=b,f.remapData.w=C-b})),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,n){const s=new O2e(t,i,n);e.push(s),e.sort((a,o)=>a.gradiento.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const n of e){if(n.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=En.Color3[0];for(let i=0;i{Pe.LerpToRef(s.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=Vs.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 RXe(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 n=new D2e(e,t,i);return this._colorGradients.push(n),this._colorGradients.sort((s,a)=>s.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,n,s){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const a=e*i%i|0,o=t*n%n|0,l=(a+o*i)*4;return s[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 fl(e,this._vertexData,!0,t);let i=0;const n=this._vertexBuffer.createVertexBuffer(ee.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ee.PositionKind]=n,i+=3;const s=this._vertexBuffer.createVertexBuffer(ee.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ee.ColorKind]=s,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 fl(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 n=0;n{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 n=0;n0&&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,n){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===8||this.billboardMode===9)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let a=t._initialDirection;this.isLocal&&(O.TransformNormalToRef(a,this._emitterWorldMatrix,oe.Vector3[0]),a=oe.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[s++]=a.x,this._vertexData[s++]=a.y,this._vertexData[s++]=a.z}else{let a=t.direction;this.isLocal&&(O.TransformNormalToRef(a,this._emitterWorldMatrix,oe.Vector3[0]),a=oe.Vector3[0]),a.x===0&&a.z===0&&(a.x=.001),this._vertexData[s++]=a.x,this._vertexData[s++]=a.y,this._vertexData[s++]=a.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),n===0?n=this._epsilon:n===1&&(n=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=n)}_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=pe.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const s=za(this._actualFrame/this.targetStopDuration);xd.GetCurrentGradient(s,this._lifeTimeGradients,(a,o)=>{const l=a,c=o,u=l.getFactor(),h=c.getFactor(),d=(s-l.gradient)/(c.gradient-l.gradient);t.lifeTime=ef(u,h,d)})}else t.lifeTime=Qn(this.minLifeTime,this.maxLifeTime);const n=Qn(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(),O.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),n===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(n),!this._sizeGradients||this._sizeGradients.length===0?t.size=Qn(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(Qn(this.minScaleX,this.maxScaleX),Qn(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const s=this._actualFrame/this.targetStopDuration;xd.GetCurrentGradient(s,this._startSizeGradients,(a,o,l)=>{a!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=a);const c=ef(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(c)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=Qn(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=Qn(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 s=Qn(0,1);at.LerpToRef(this.color1,this.color2,s,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 It(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 O(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new O(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const n=[ee.PositionKind,ee.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const n=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Yo(n),e&&n.push("particlesInfos"),t&&n.push("logarithmicDepthConstant"),i&&(n.push("vFogInfos"),n.push("vFogColor")),n}fillDefines(e,t,i=!0){if(this._scene&&(x3(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===El.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(...h5._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==8&&this.billboardMode!==9,this._useRampGradients)),e.push(...h5._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(UBe(e,this._imageProcessingConfigurationDefines),zBe(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);const n=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[n];s||(s=this._drawWrappers[n]=[]);let a=s[e];a||(a=new pl(this._engine),a.drawContext&&(a.drawContext.useInstancing=this._useInstancing),s[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 n=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const s=this._actualFrame/this.targetStopDuration;xd.GetCurrentGradient(s,this._emitRateGradients,(a,o,l)=>{a!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=a),n=ef(this._currentEmitRate1,this._currentEmitRate2,l)})}t=n*this._scaledUpdateSpeed>>0,this._newPartsExcess+=n*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 n=0;for(let s=0;sPromise.resolve().then(()=>JXe),void 0),je(()=>Promise.resolve().then(()=>b8t),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>jXe),void 0),je(()=>Promise.resolve().then(()=>x8t),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!==El.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(El.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(El.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,n=this._engine;n.enableEffect(t);const s=this.defaultViewMatrix??this._scene.getViewMatrix();if(i.setTexture("diffuseSampler",this.particleTexture),i.setMatrix("view",s),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&&(wo(i,this,this._scene),this.applyFog&&ic(this._scene,void 0,i)),a.indexOf("#define BILLBOARDMODE_ALL")>=0&&(s.invertToRef(oe.Matrix[0]),i.setMatrix("invView",oe.Matrix[0])),this._vertexArrayObject!==void 0?(o=this._scene)!=null&&o.forceWireframe?n.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?n.bindBuffers(this._vertexBuffers,(u=this._scene)!=null&&u.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):n.bindBuffers(this._vertexBuffers,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&Xo(a,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case El.BLENDMODE_ADD:n.setAlphaMode(1);break;case El.BLENDMODE_ONEONE:n.setAlphaMode(6);break;case El.BLENDMODE_STANDARD:n.setAlphaMode(2);break;case El.BLENDMODE_MULTIPLY:n.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?(h=this._scene)!=null&&h.forceWireframe?n.drawElementsType(6,0,10,this._particles.length):n.drawArraysType(7,0,4,this._particles.length):(d=this._scene)!=null&&d.forceWireframe?n.drawElementsType(1,0,this._particles.length*10):n.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===El.BLENDMODE_MULTIPLYADD?t=this._render(El.BLENDMODE_MULTIPLY)+this._render(El.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 n=this._scene.particleSystems.indexOf(this);n>-1&&this._scene.particleSystems.splice(n,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}h5.ForceGLSL=!1;var zde;(function(r){r[r.ATTACHED=0]="ATTACHED",r[r.END=1]="END"})(zde||(zde={}));class Qv{constructor(e){if(this.particleSystem=e,this.type=1,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=Sa("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new O;else if(e instanceof O)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=Sa("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new Qv(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,n=!1){throw Ji("ParseParticle")}static Parse(e,t,i){const n=e.particleSystem,s=new Qv(Qv._ParseParticleSystem(n,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}function IXe(r,e){const t=new vV;return t.direction1=r,t.direction2=e,t}function PXe(r=1,e=1){return new _V(r,e)}function wXe(r=1,e=1){return new mD(r,e)}function DXe(r=1,e=new O(0,1,0),t=new O(0,1,0)){return new yV(r,e,t)}function OXe(r=1,e=1,t=1,i=0){return new pD(r,e,t,i)}function LXe(r=1,e=1,t=1,i=new O(0,1,0),n=new O(0,1,0)){return new gV(r,e,t,i,n)}function NXe(r=1,e=Math.PI/4){return new fD(r,e)}function FXe(r=1,e=Math.PI/4,t=new O(0,1,0),i=new O(0,1,0)){return new mV(r,e,t,i)}class $n extends h5{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 n=i.clone();e._inheritParticleInfoToSubEmitter(n),n.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(n.particleSystem),n.particleSystem.start()}})}}createPointEmitter(e,t){const i=IXe(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=PXe(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=wXe(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new O(0,1,0),i=new O(0,1,0)){const n=DXe(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=OXe(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new O(0,1,0),s=new O(0,1,0)){const a=LXe(e,t,i,n,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=NXe(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new O(0,1,0),n=new O(0,1,0)){const s=FXe(e,t,i,n);return this.particleEmitterType=s,s}createBoxEmitter(e,t,i,n){const s=new Xv;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof $n?this._subEmitters.push([new Qv(e)]):e instanceof Qv?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 n=i.clone();e._attachedSubEmitters.push(n),n.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(n=>{if(n._attachedSubEmitters)for(let s=n._attachedSubEmitters.length-1;s>=0;s-=1)n._attachedSubEmitters[s].dispose()})),t&&this.activeSubSystems)for(let n=this.activeSubSystems.length-1;n>=0;n-=1)this.activeSubSystems[n].dispose();if(this._subEmitters&&this._subEmitters.length){for(let n=0;n0?l.shaderOptions.defines.join(` `):"";o=c.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const h=new $n(a,s||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(Qv.Parse(p,t,i));h.subEmitters.push(f)}}return $n._Parse(e,h,t,i),e.textureMask&&(h.textureMask=at.FromArray(e.textureMask)),e.worldOffset&&(h.worldOffset=O.FromArray(e.worldOffset)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),!n&&!h.preventAutoStart&&h.start(),h}serialize(e=!1){const t={};if($n._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 n=[];for(const s of i)n.push(s.serialize(e));t.subEmitters.push(n)}}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 m=t.emitter;e.emitterId=m.id}else{const m=t.emitter;e.emitter=m.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,ot.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 n=t.getColorGradients();if(n){e.colorGradients=[];for(const m of n){const _={gradient:m.gradient,color1:m.color1.asArray()};m.color2?_.color2=m.color2.asArray():_.color2=m.color1.asArray(),e.colorGradients.push(_)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const m of s){const _={gradient:m.gradient,color:m.color.asArray()};e.rampGradients.push(_)}e.useRampGradients=t.useRampGradients}const a=t.getColorRemapGradients();if(a){e.colorRemapGradients=[];for(const m of a){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.colorRemapGradients.push(_)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const m of o){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.alphaRemapGradients.push(_)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const m of l){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.sizeGradients.push(_)}}const c=t.getAngularSpeedGradients();if(c){e.angularSpeedGradients=[];for(const m of c){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.angularSpeedGradients.push(_)}}const u=t.getVelocityGradients();if(u){e.velocityGradients=[];for(const m of u){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.velocityGradients.push(_)}}const h=t.getDragGradients();if(h){e.dragGradients=[];for(const m of h){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.dragGradients.push(_)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const m of d){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.emitRateGradients.push(_)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const m of f){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.startSizeGradients.push(_)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const m of p){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.lifeTimeGradients.push(_)}}const g=t.getLimitVelocityGradients();if(g){e.limitVelocityGradients=[];for(const m of g){const _={gradient:m.gradient,factor1:m.factor1};m.factor2!==void 0?_.factor2=m.factor2:_.factor2=m.factor1,e.limitVelocityGradients.push(_)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const n={...this._customWrappers};let s=null;const a=this._engine;if(a.createEffectForParticles&&this.customShader!=null){s=this.customShader;const c=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join(` `):"",u=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,c);n[0]?n[0].effect=u:this.setCustomEffect(u,0)}const o=this.serialize(i),l=$n.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=s,l._customWrappers=n,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,this.preventAutoStart||l.start(),l}}$n.BILLBOARDMODE_Y=2;$n.BILLBOARDMODE_ALL=7;$n.BILLBOARDMODE_STRETCHED=8;$n.BILLBOARDMODE_STRETCHED_LOCAL=9;Qv._ParseParticleSystem=$n.Parse;const u8t="clipPlaneFragmentDeclaration2",h8t=`#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 `;me.IncludesShadersStore[u8t]=h8t;const d8t="gpuRenderParticlesPixelShader",f8t=`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 } `;me.ShadersStore[d8t]=f8t;const p8t="clipPlaneVertexDeclaration2",m8t=`#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 `;me.IncludesShadersStore[p8t]=m8t;const g8t="gpuRenderParticlesVertexShader",_8t=`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 }`;me.ShadersStore[g8t]=_8t;class vf extends El{static get IsSupported(){if(!ei.LastCreatedEngine)return!1;const e=ei.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=IXe(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=PXe(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=wXe(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new O(0,1,0),i=new O(0,1,0)){const n=DXe(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=OXe(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new O(0,1,0),s=new O(0,1,0)){const a=LXe(e,t,i,n,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){const i=NXe(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new O(0,1,0),n=new O(0,1,0)){const s=FXe(e,t,i,n);return this.particleEmitterType=s,s}createBoxEmitter(e,t,i,n){const s=new Xv;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==$n.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper($n.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper($n.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 pl(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new Ce),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 D2e(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 n=new O2e(t,i);e.push(n),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((s,a)=>s.gradienta.gradient?1:0);const n=this;n[t]&&(n[t].dispose(),n[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,n=null,s=!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 Ce,this.onStoppedObservable=new Ce,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||ei.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=pe.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!Sa("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Sa("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!Sa("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(Sa("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new pl(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers={0:new pl(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=s,this.particleEmitterType=new Xv;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 fl(t,l,!1,this._attributesStrideSize),this._buffer1=new fl(t,c,!1,this._attributesStrideSize),this._spriteBuffer=new fl(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 n=this._drawWrappers[e];n||(n=new pl(this._engine),n.drawContext&&(n.drawContext.useInstancing=!0),this._drawWrappers[e]=n);const s=i.join(` `);if(n.defines!==s){const a=[],o=[],l=[];this.fillUniformsAttributesAndSamplerNames(o,a,l),n.setEffect(this._engine.createEffect("gpuRenderParticles",a,o,l,s),s)}return n}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,n=!1){const s=[ee.PositionKind,"age","life","size","angle"];return e||s.push(ee.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),n&&s.push("direction"),s.push("offset",ee.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const n=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Yo(n),e&&n.push("sheetInfos"),t&&n.push("logarithmicDepthConstant"),i&&(n.push("vFogInfos"),n.push("vFogColor")),n}fillDefines(e,t=0,i=!0){if(this._scene&&(x3(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==Ut.FOGMODE_NONE&&e.push("#define FOG")),t===$n.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 $n.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case $n.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case $n.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(...vf._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===$n.BILLBOARDMODE_STRETCHED)),e.push(...vf._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Gr.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Gr.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 n=new Float32Array(this._rawTextureWidth);for(let s=0;s{n[s]=Xt.Lerp(o.factor1,l.factor1,c)})}this[t]=Vs.CreateRTexture(n,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=En.Color4[0];for(let i=0;i{at.LerpToRef(s.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=Vs.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),n=i.effect;this._engine.enableEffect(i);const s=((o=this._scene)==null?void 0:o.getViewMatrix())||pe.IdentityReadOnly;if(n.setMatrix("view",s),n.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),n.setTexture("diffuseSampler",this.particleTexture),n.setVector2("translationPivot",this.translationPivot),n.setVector3("worldOffset",this.worldOffset),this.isLocal&&n.setMatrix("emitterWM",t),this._colorGradientsTexture?n.setTexture("colorGradientSampler",this._colorGradientsTexture):n.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const h=this.particleTexture.getBaseSize();n.setFloat3("sheetInfos",this.spriteCellWidth/h.width,this.spriteCellHeight/h.height,h.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const h=this._scene.activeCamera;n.setVector3("eyePosition",h.globalPosition)}const a=n.defines;if(this._scene&&(wo(n,this,this._scene),this.applyFog&&ic(this._scene,void 0,n)),a.indexOf("#define BILLBOARDMODE_ALL")>=0){const h=s.clone();h.invert(),n.setMatrix("invView",h)}switch(this.useLogarithmicDepth&&this._scene&&Xo(a,n,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(n),e){case $n.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case $n.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case $n.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case $n.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,n,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(n),(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=oe.Matrix[0],pe.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=oe.Matrix[0],pe.TranslationToRef(a.x,a.y,a.z,i)}const n=this._engine;this.updateInAnimate||this._update(i);let s=0;return!e&&!t&&(n.setState(!1),this.forceDepthWrite&&n.setDepthWrite(!0),this.blendMode===$n.BLENDMODE_MULTIPLYADD?s=this._render($n.BLENDMODE_MULTIPLY,i)+this._render($n.BLENDMODE_ADD,i):s=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}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?s.shaderOptions.defines.join(` `):"";n[0]=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,c,void 0,void 0,void 0,this)}const o=this.serialize(i),l=vf.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=s,l._customWrappers=n,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,l}serialize(e=!1){const t={};return $n._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,n=!1,s){const a=e.name;let o,l;t instanceof Qe?o=t:(l=t,o=l.getEngine());const c=new vf(a,{capacity:s||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),$n._Parse(e,c,t,i),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),!n&&!c.preventAutoStart&&c.start(),c}}class o3{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 n=bu("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;const s=new ct("emitterSphereMaterial",i);s.emissiveColor=e.color,n.material=s;for(const a of this.systems)a.emitter=n;this._emitterNode=n}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,n){const s=new o3,a=this.BaseAssetsUrl+"/textures/";t=t||ei.LastCreatedScene;for(const o of e.systems)s.systems.push(i?vf.Parse(o,t,a,!0,n):$n.Parse(o,t,a,!0,n));if(e.emitter){const o=e.emitter.options;switch(e.emitter.kind){case"Sphere":s.setEmitterAsSphere({diameter:o.diameter,segments:o.segments,color:Pe.FromArray(o.color)},e.emitter.renderingGroupId,t);break}}return s}}o3.BaseAssetsUrl="https://assets.babylonjs.com/particles";class cE{static CreateDefault(e,t=500,i,n=!1){let s;return n?s=new vf("default system",{capacity:t},i):s=new $n("default system",t,i),s.emitter=e,s.particleTexture=new be("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new at(1,1,1,1),s.color2=new at(1,1,1,1),s.colorDead=new at(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,n){t||(t=ei.LastCreatedScene);const s={};return t.addPendingData(s),new Promise((a,o)=>{if(i&&!vf.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");Ie.LoadFile(`${cE.BaseAssetsUrl}/systems/${e}.json`,l=>{t.removePendingData(s);const c=JSON.parse(l.toString());return a(o3.Parse(c,t,i,n))},void 0,void 0,void 0,()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){const t=new o3;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,n=!1,s="",a){return new Promise((o,l)=>{const c=new oa;c.addEventListener("readystatechange",()=>{if(c.readyState==4)if(c.status==200){const u=JSON.parse(c.responseText);let h;n?h=vf.Parse(u,i,s,!1,a):h=$n.Parse(u,i,s,!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,n="",s){if(e==="_BLANK"){const a=this.CreateDefault(null);return a.start(),Promise.resolve(a)}return new Promise((a,o)=>{const l=new oa;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=vf.Parse(u,t,n,!1,s):h=$n.Parse(u,t,n,!1,s),h.snippetId=e,a(h)}else o("Unable to load the snippet "+e)}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}}cE.BaseAssetsUrl=o3.BaseAssetsUrl;cE.SnippetUrl="https://snippet.babylonjs.com";cE.CreateFromSnippetAsync=cE.ParseFromSnippetAsync;vo.AddParser(bt.NAME_PARTICLESYSTEM,(r,e,t,i)=>{const n=vo.GetIndividualParser(bt.NAME_PARTICLESYSTEM);if(n&&r.particleSystems!==void 0&&r.particleSystems!==null)for(let s=0,a=r.particleSystems.length;sr.activeParticleCount?vf.Parse(r,e,t):$n.Parse(r,e,t));Qe.prototype.createEffectForParticles=function(r,e=[],t=[],i="",n,s,a,o,l=0){let c=[],u=[];const h=[];return o?o.fillUniformsAttributesAndSamplerNames(u,c,h):(c=$n._GetAttributeNamesOrOptions(),u=$n._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:r},c,u.concat(e),h.concat(t),i,n,s,a,void 0,l,async()=>{l===0?await je(()=>Promise.resolve().then(()=>jXe),void 0):await je(()=>Promise.resolve().then(()=>JXe),void 0)})};Re.prototype.getEmittedParticleSystems=function(){const r=[];for(let e=0;es.sqDistance-n.sqDistance,this._materialSortFunction=(n,s)=>n.materialIndex-s.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||ei.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 Tf(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new kXe}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(this.nbParticles===0&&!this.mesh){const t=lD("",{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 Re(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&vt.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 vt;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,ee.PositionKind),e.set(this._normals32,ee.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,ee.UVKind),this._colors32.length>0&&e.set(this._colors32,ee.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let t=0;for(let i=0;if?f:n,i=Math.round(f/n),s=0):i=i>f?f:i;const p=[],g=[],m=[],_=[],y=[],v=O.Zero(),x=i;for(;df-i&&(i=f-d),p.length=0,g.length=0,m.length=0,_.length=0,y.length=0;let b=0;for(let j=d*3;j<(d+i)*3;j++){m.push(b);const B=o[j],G=B*3;if(p.push(a[G],a[G+1],a[G+2]),g.push(u[G],u[G+1],u[G+2]),l){const Y=B*2;_.push(l[Y],l[Y+1])}if(c){const Y=B*4;y.push(c[Y],c[Y+1],c[Y+2],c[Y+3])}b++}let C=this.nbParticles;const A=this._posToShape(p),E=this._uvsToShapeUV(_),P=m.slice(),w=y.slice(),M=g.slice();v.copyFromFloats(0,0,0);let R;for(R=0;R65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const z=b.materialIndex!==null?b.materialIndex:0;this.depthSortedParticles.push(new BXe(f,t,s.length,z))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const n=this.particles,s=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const K=this.mesh.getBoundingInfo();K&&(v.copyFrom(K.minimum),x.copyFrom(K.maximum))}M=this.particles[e]._pos;const W=M/3|0;I=W*4,k=W*2;for(let K=e;K<=t;K++){const U=this.particles[K];this.updateParticle(U);const j=U._model._shape,B=U._model._shapeUV,G=U._rotationMatrix,Y=U.position,Z=U.rotation,te=U.scaling,le=U._globalPosition;if(p){const ce=this.depthSortedParticles[K];ce.idx=U.idx,ce.ind=U._ind,ce.indicesLength=U._model._indicesLength,ce.sqDistance=O.DistanceSquared(U.position,b)}if(!U.alive||U._stillInvisible&&!U.isVisible&&!this._recomputeInvisibles){z=j.length,M+=z*3,I+=z*4,k+=z*2;continue}if(U.isVisible){U._stillInvisible=!1;const ce=g[12];if(U.pivot.multiplyToRef(te,ce),this.billboard&&(Z.x=0,Z.y=0),(this._computeParticleRotation||this.billboard)&&U.getRotationMatrix(n),U.parentId!==null){const F=this.getParticleById(U.parentId);if(F){const X=F._rotationMatrix,J=F._globalPosition,ae=Y.x*X[1]+Y.y*X[4]+Y.z*X[7],ne=Y.x*X[0]+Y.y*X[3]+Y.z*X[6],he=Y.x*X[2]+Y.y*X[5]+Y.z*X[8];if(le.x=J.x+ne,le.y=J.y+ae,le.z=J.z+he,this._computeParticleRotation||this.billboard){const fe=n.m;G[0]=fe[0]*X[0]+fe[1]*X[3]+fe[2]*X[6],G[1]=fe[0]*X[1]+fe[1]*X[4]+fe[2]*X[7],G[2]=fe[0]*X[2]+fe[1]*X[5]+fe[2]*X[8],G[3]=fe[4]*X[0]+fe[5]*X[3]+fe[6]*X[6],G[4]=fe[4]*X[1]+fe[5]*X[4]+fe[6]*X[7],G[5]=fe[4]*X[2]+fe[5]*X[5]+fe[6]*X[8],G[6]=fe[8]*X[0]+fe[9]*X[3]+fe[10]*X[6],G[7]=fe[8]*X[1]+fe[9]*X[4]+fe[10]*X[7],G[8]=fe[8]*X[2]+fe[9]*X[5]+fe[10]*X[8]}}else U.parentId=null}else if(le.x=Y.x,le.y=Y.y,le.z=Y.z,this._computeParticleRotation||this.billboard){const F=n.m;G[0]=F[0],G[1]=F[1],G[2]=F[2],G[3]=F[4],G[4]=F[5],G[5]=F[6],G[6]=F[8],G[7]=F[9],G[8]=F[10]}const N=g[11];for(U.translateFromPivot?N.setAll(0):N.copyFrom(ce),z=0;z0)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 vt;t.set(this._positions32,ee.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,ee.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,ee.ColorKind));const n=new Re(this.name,this._scene);t.applyToMesh(n,this._updatable),this.mesh=n,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let s=e;return s||(s=new ct("point cloud material",this._scene),s.emissiveColor=new Pe(i,i,i),s.disableLighting=!0,s.pointsCloud=!0,s.pointSize=this._size),n.material=s,new Promise(a=>a(n))}_addParticle(e,t,i,n){const s=new UXe(e,t,i,n,this);return this.particles.push(s),s}_randomUnitVector(e){e.position=new O(Math.random(),Math.random(),Math.random()),e.color=new at(1,1,1,1)}_getColorIndicesForCoord(e,t,i,n){const s=e._groupImageData,a=i*(n*4)+t*4,o=[a,a+1,a+2,a+3],l=o[0],c=o[1],u=o[2],h=o[3],d=s[l],f=s[c],p=s[u],g=s[h];return new at(d/255,f/255,p/255,g)}_setPointsColorOrUV(e,t,i,n,s,a,o,l){l=l??0,i&&e.updateFacetData();const u=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(ee.PositionKind);const d=e.getIndices(),f=e.getVerticesData(ee.UVKind+(l?l+1:"")),p=e.getVerticesData(ee.ColorKind),g=O.Zero();e.computeWorldMatrix();const m=e.getWorldMatrix();if(!m.isIdentity()){h=h.slice(0);for(let ni=0;ni1&&(rt=1),Ei<0&&(Ei=0),Ei>1&&(Ei=1),Pe.HSVtoRGBToRef(gi,rt,Ei,At),zt.set(At.r,At.g,At.b,1)):zt=Je.set(Math.random(),Math.random(),Math.random(),1),Et.color=new at(zt.x,zt.y,zt.z,zt.w),this._colors.push(zt.x,zt.y,zt.z,zt.w))}}_colorFromTexture(e,t,i){if(e.material===null){ge.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const s=e.material.getActiveTextures();if(s.length===0){ge.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=>{Cn.WhenAllReady(s,()=>{let l=t._textureNb;l<0&&(l=0),l>s.length-1&&(l=s.length-1);const c=()=>{t._groupImgWidth=s[l].getSize().width,t._groupImgHeight=s[l].getSize().height,this._setPointsColorOrUV(a,t,i,!0,!0,void 0,void 0,s[l].coordinatesIndex),a.dispose(),o()};t._groupImageData=null;const u=s[l].readPixels();u?u.then(h=>{t._groupImageData=h,c()}):c()})}))}_calculateDensity(e,t,i){let n,s,a,o,l,c,u,h,d,f,p,g;const m=O.Zero(),_=O.Zero(),y=O.Zero(),v=O.Zero(),x=O.Zero(),b=O.Zero();let C;const A=[];let E=0;const P=i.length/3;for(let R=0;R0;R--){const I=A[R];if(I===0)w[R]=0;else{const k=(I-A[R-1])/I*M,z=Math.floor(k),W=k-z,K=+(Math.random()3)&&(a=0);const o=e.getVerticesData(ee.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new rQ(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),a===2?c._textureNb=n||0:n=n||new at(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,n,s);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,n,s){let a=i||0;(isNaN(a)||a<0||a>3)&&(a=0);const o=e.getVerticesData(ee.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const c=new rQ(this._groupCounter,null);switch(c._groupDensity=this._calculateDensity(t,o,l),a===2?c._textureNb=n||0:n=n||new at(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,n,s);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 n=oe.Matrix[0],s=this.mesh,a=this._colors32,o=this._positions32,l=this._uvs32,c=oe.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);pe.IdentityToRef(n);let g=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 b=(x=this.mesh)==null?void 0:x.getBoundingInfo();b&&(f.copyFrom(b.minimum),p.copyFrom(b.maximum))}g=0;let m=0,_=0,y=0;for(let b=e;b<=t;b++){const C=this.particles[b];g=C.idx,m=3*g,_=4*g,y=2*g,this.updateParticle(C);const A=C._rotationMatrix,E=C.position,P=C._globalPosition;if(this._computeParticleRotation&&C.getRotationMatrix(n),C.parentId!==null){const G=this.particles[C.parentId],Y=G._rotationMatrix,Z=G._globalPosition,te=E.x*Y[1]+E.y*Y[4]+E.z*Y[7],le=E.x*Y[0]+E.y*Y[3]+E.z*Y[6],ce=E.x*Y[2]+E.y*Y[5]+E.z*Y[8];if(P.x=Z.x+le,P.y=Z.y+te,P.z=Z.z+ce,this._computeParticleRotation){const ue=n.m;A[0]=ue[0]*Y[0]+ue[1]*Y[3]+ue[2]*Y[6],A[1]=ue[0]*Y[1]+ue[1]*Y[4]+ue[2]*Y[7],A[2]=ue[0]*Y[2]+ue[1]*Y[5]+ue[2]*Y[8],A[3]=ue[4]*Y[0]+ue[5]*Y[3]+ue[6]*Y[6],A[4]=ue[4]*Y[1]+ue[5]*Y[4]+ue[6]*Y[7],A[5]=ue[4]*Y[2]+ue[5]*Y[5]+ue[6]*Y[8],A[6]=ue[8]*Y[0]+ue[9]*Y[3]+ue[10]*Y[6],A[7]=ue[8]*Y[1]+ue[9]*Y[4]+ue[10]*Y[7],A[8]=ue[8]*Y[2]+ue[9]*Y[5]+ue[10]*Y[8]}}else if(P.x=0,P.y=0,P.z=0,this._computeParticleRotation){const G=n.m;A[0]=G[0],A[1]=G[1],A[2]=G[2],A[3]=G[4],A[4]=G[5],A[5]=G[6],A[6]=G[8],A[7]=G[9],A[8]=G[10]}const M=c[11];C.translateFromPivot?M.setAll(0):M.copyFrom(C.pivot);const R=c[0];R.copyFrom(C.position);const I=R.x-C.pivot.x,D=R.y-C.pivot.y,k=R.z-C.pivot.z;let z=I*A[0]+D*A[3]+k*A[6],W=I*A[1]+D*A[4]+k*A[7],K=I*A[2]+D*A[5]+k*A[8];z+=M.x,W+=M.y,K+=M.z;const U=o[m]=P.x+u.x*z+h.x*W+d.x*K,j=o[m+1]=P.y+u.y*z+h.y*W+d.y*K,B=o[m+2]=P.z+u.z*z+h.z*W+d.z*K;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(U,j,B),p.maximizeInPlaceFromFloats(U,j,B)),this._computeParticleColor&&C.color){const G=C.color,Y=this._colors32;Y[_]=G.r,Y[_+1]=G.g,Y[_+2]=G.b,Y[_+3]=G.a}if(this._computeParticleTexture&&C.uv){const G=C.uv,Y=this._uvs32;Y[y]=G.x,Y[y+1]=G.y}}return s&&(i&&(this._computeParticleColor&&s.updateVerticesData(ee.ColorKind,a,!1,!1),this._computeParticleTexture&&s.updateVerticesData(ee.UVKind,l,!1,!1),s.updateVerticesData(ee.PositionKind,o,!1,!1)),this._computeBoundingBox&&(s.hasBoundingInfo?s.getBoundingInfo().reConstruct(f,p,s._worldMatrix):s.buildBoundingInfo(f,p,s._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 O(-t,-t,-t),new O(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 zXe="particlesPixelShader",VXe=`#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 }`;me.ShadersStore[zXe]=VXe;const GXe={name:zXe,shader:VXe},x8t=Object.freeze(Object.defineProperty({__proto__:null,particlesPixelShader:GXe},Symbol.toStringTag,{value:"Module"})),WXe="particlesVertexShader",KXe=`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 }`;me.ShadersStore[WXe]=KXe;const HXe={name:WXe,shader:KXe},jXe=Object.freeze(Object.defineProperty({__proto__:null,particlesVertexShader:HXe},Symbol.toStringTag,{value:"Module"})),$Xe="particlesPixelShader",XXe=`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 }`;me.ShadersStoreWGSL[$Xe]=XXe;const YXe={name:$Xe,shader:XXe},b8t=Object.freeze(Object.defineProperty({__proto__:null,particlesPixelShaderWGSL:YXe},Symbol.toStringTag,{value:"Module"})),QXe="particlesVertexShader",ZXe=`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 }`;me.ShadersStoreWGSL[QXe]=ZXe;const qXe={name:QXe,shader:ZXe},JXe=Object.freeze(Object.defineProperty({__proto__:null,particlesVertexShaderWGSL:qXe},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(vr.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(r){this._physicsImpostor!==r&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=r,r&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});vr.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};vr.prototype.applyImpulse=function(r,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(r,e),this):this};vr.prototype.setPhysicsLinkWith=function(r,e,t,i){return!this.physicsImpostor||!r.physicsImpostor?this:(this.physicsImpostor.createJoint(r.physicsImpostor,cs.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class Qee{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw Ji("")}constructor(e,t=Qee.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new O(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,n){this._physicsPlugin.raycast(e,t,i,n)}raycast(e,t,i){const n=new cV;return this._physicsPlugin.raycast(e,t,n,i),n}}var Kde;(function(r){r[r.FREE=0]="FREE",r[r.LIMITED=1]="LIMITED",r[r.LOCKED=2]="LOCKED"})(Kde||(Kde={}));var Hde;(function(r){r[r.LINEAR_X=0]="LINEAR_X",r[r.LINEAR_Y=1]="LINEAR_Y",r[r.LINEAR_Z=2]="LINEAR_Z",r[r.ANGULAR_X=3]="ANGULAR_X",r[r.ANGULAR_Y=4]="ANGULAR_Y",r[r.ANGULAR_Z=5]="ANGULAR_Z",r[r.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(Hde||(Hde={}));var jde;(function(r){r[r.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",r[r.DISTANCE=2]="DISTANCE",r[r.HINGE=3]="HINGE",r[r.SLIDER=4]="SLIDER",r[r.LOCK=5]="LOCK",r[r.PRISMATIC=6]="PRISMATIC",r[r.SIX_DOF=7]="SIX_DOF"})(jde||(jde={}));var $de;(function(r){r[r.SPHERE=0]="SPHERE",r[r.CAPSULE=1]="CAPSULE",r[r.CYLINDER=2]="CYLINDER",r[r.BOX=3]="BOX",r[r.CONVEX_HULL=4]="CONVEX_HULL",r[r.CONTAINER=5]="CONTAINER",r[r.MESH=6]="MESH",r[r.HEIGHTFIELD=7]="HEIGHTFIELD"})($de||($de={}));var Xde;(function(r){r[r.NONE=0]="NONE",r[r.VELOCITY=1]="VELOCITY",r[r.POSITION=2]="POSITION"})(Xde||(Xde={}));var Yde;(function(r){r.COLLISION_STARTED="COLLISION_STARTED",r.COLLISION_CONTINUED="COLLISION_CONTINUED",r.COLLISION_FINISHED="COLLISION_FINISHED",r.TRIGGER_ENTERED="TRIGGER_ENTERED",r.TRIGGER_EXITED="TRIGGER_EXITED"})(Yde||(Yde={}));var Qde;(function(r){r[r.STATIC=0]="STATIC",r[r.ANIMATED=1]="ANIMATED",r[r.DYNAMIC=2]="DYNAMIC"})(Qde||(Qde={}));var f_;(function(r){r[r.DISABLED=0]="DISABLED",r[r.TELEPORT=1]="TELEPORT",r[r.ACTION=2]="ACTION"})(f_||(f_={}));var Zde;(function(r){r[r.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",r[r.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",r[r.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"})(Zde||(Zde={}));class Zee{get disablePreStep(){return this._prestepType==f_.DISABLED}set disablePreStep(e){this._prestepType=e?f_.DISABLED:f_.TELEPORT}constructor(e,t,i,n){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disableSync=!1,this._isDisposed=!1,this._shape=null,this._prestepType=f_.DISABLED,!n)return;const s=n.getPhysicsEngine();if(!s)throw new Error("No Physics Engine available.");if(this._physicsEngine=s,s.getPluginVersion()!=2)throw new Error("Plugin version is incorrect. Expected version 2.");const a=s.getPhysicsPlugin();if(!a)throw new Error("No Physics Plugin available.");this._physicsPlugin=a,e.rotationQuaternion||(e.rotationQuaternion=Oe.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,s.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}getClassName(){return"PhysicsBody"}clone(e){const t=new Zee(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 O;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 O;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 O;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){var i;if(((i=this._pluginDataInstances)==null?void 0:i.length)>0){const n=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[n*16+12],s[n*16+13],s[n*16+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,n){this._physicsPlugin.addConstraint(this,e,t,i,n)}syncWithBone(e,t,i,n,s,a){const o=this.transformNode;if(o.rotationQuaternion)if(s){const u=oe.Quaternion[0];e.getRotationQuaternionToRef(1,t,u),u.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const l=oe.Vector3[0],c=oe.Vector3[1];a||(a=oe.Vector3[2],a.x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,c),e.getAbsolutePositionToRef(t,l),n==null&&i&&(n=i.length()),n!=null&&(l.x+=c.x*n,l.y+=c.y*n,l.z+=c.z*n),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 Id(new O(-.5,-.5,-.5),new O(.5,.5,.5))}_hasVertices(e){return(e==null?void 0:e.getTotalVertices())>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=oe.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=oe.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const n=new O;n.copyFrom(e.center),n.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=n}switch(this.type){case 0:!this._options.radius&&Xt.WithinEpsilon(t.x,t.y,1e-4)&&Xt.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(ge.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 n=t.x/2;this._options.radius=this._options.radius??n,this._options.pointA=this._options.pointA??new O(0,i.y+n,0),this._options.pointB=this._options.pointB??new O(0,i.y+t.y-n,0)}break;case 2:{const n=t.x/2;this._options.radius=this._options.radius??n,this._options.pointA=this._options.pointA??new O(0,i.y,0),this._options.pointB=this._options.pointB??new O(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 O(t.x,t.y,t.z),this._options.rotation=this._options.rotation??Oe.Identity();break}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class N8t{}class F8t{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 B8t{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=oe.Matrix[0];if(pe.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Re?this._addMesh(e,i):e instanceof W0&&this._addMesh(e.sourceMesh,i),t){const n=oe.Matrix[1];e.computeWorldMatrix().invertToRef(n);const s=oe.Matrix[2];n.multiplyToRef(i,s),e.getChildMeshes(!1).filter(o=>!o.physicsBody).forEach(o=>{const l=o.computeWorldMatrix(),c=oe.Matrix[3];l.multiplyToRef(s,c),o instanceof Re?this._addMesh(o,c):o instanceof W0&&this._addMesh(o.sourceMesh,c)})}}_addMesh(e,t){const i=e.getVerticesData(ee.PositionKind)||[],n=i.length/3,s=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 n=((a=i._thinInstanceDataStorage)==null?void 0:a.instancesCount)??0,s=i._thinInstanceDataStorage.matrixData;s&&(this._createOrUpdateBodyInstances(e,t,s,0,n,!1),e._pluginDataInstances.forEach((o,l)=>{this._bodies.set(o.hpBodyId[0],{body:e,index:l})}))}_createOrUpdateBodyInstances(e,t,i,n,s,a){const o=oe.Quaternion[0],l=pe.Identity();for(let c=n;cs){this._createOrUpdateBodyInstances(e,a,n,s,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=s;u{this._hknp.HP_Body_SetEventMask(n.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:O.FromArray(e[0]),mass:e[1],inertia:O.FromArray(e[2]),inertiaOrientation:Oe.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,n=>{this._internalSetMotionType(n,t)},i)}getMotionType(e,t){const i=this._getPluginReference(e,t),n=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(n){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: "+n)}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),n=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(n)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,n=>{n.userMassProps=t,this._internalUpdateMassProperties(n)},i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),n=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(n)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,n=>{this._hknp.HP_Body_SetLinearDamping(n.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,n=>{this._hknp.HP_Body_SetAngularDamping(n.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,n=>{this._hknp.HP_Body_SetLinearVelocity(n.hpBodyId,this._bVecToV3(t))},i)}getLinearVelocityToRef(e,t,i){const n=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetLinearVelocity(n.hpBodyId)[1];this._v3ToBvecRef(s,t)}_applyToBodyOrInstances(e,t,i){var n;if(((n=e._pluginDataInstances)==null?void 0:n.length)>0&&i===void 0)for(let s=0;s{this._hknp.HP_Body_ApplyImpulse(s.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))},n)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,n=>{this._hknp.HP_Body_ApplyAngularImpulse(n.hpBodyId,this._bVecToV3(t))},i)}applyForce(e,t,i,n){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,n)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,n=>{this._hknp.HP_Body_SetAngularVelocity(n.hpBodyId,this._bVecToV3(t))},i)}getAngularVelocityToRef(e,t,i){const n=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetAngularVelocity(n.hpBodyId)[1];this._v3ToBvecRef(s,t)}setPhysicsBodyTransformation(e,t){if(e.getPrestepType()==f_.TELEPORT){const i=e.transformNode;if(e.numInstances>0){const s=i._thinInstanceDataStorage.matrixData;if(!s)return;const a=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),s,0,a,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}else e.getPrestepType()==f_.ACTION?this.setTargetTransform(e,t.absolutePosition,t.absoluteRotationQuaternion):e.getPrestepType()==f_.DISABLED?ge.Warn("Prestep type is set to DISABLED. Unable to set physics body transformation."):ge.Warn("Invalid prestep type set to physics body.")}setTargetTransform(e,t,i,n){this._applyToBodyOrInstances(e,s=>{this._hknp.HP_Body_SetTargetQTransform(s.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])},n)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,n=>{this._hknp.HP_Body_SetGravityFactor(n.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(ee.PositionKind);const n=t.computeWorldMatrix(!0),s=[];let a;for(a=0;a0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],n=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(n[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const s=this._hknp.HP_DebugGeometry_GetInfo(n[1])[1],a=new Float32Array(this._hknp.HEAPU8.buffer,s[0],s[1]*3),o=new Uint32Array(this._hknp.HEAPU8.buffer,s[2],s[3]*3),l=a.slice(0),c=o.slice(0);return this._hknp.HP_DebugGeometry_Release(n[1]),{positions:l,indices:c}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,n,s){const a=e.type,o=e.options;if(!a||!o){ge.Warn("No constraint type or options. Constraint is invalid.");return}if(t._pluginDataInstances.length>0&&n===void 0||i._pluginDataInstances.length>0&&s===void 0){ge.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,n).hpBodyId,u=this._getPluginReference(i,s).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(O.Zero()),d=o.axisA??new O(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(O.Zero()),g=o.axisB??new O(1,0,0),m=this._tmpVec3[0];if(o.perpAxisB?m.copyFrom(o.perpAxisB):g.getNormalToRef(m),this._hknp.HP_Constraint_SetAnchorInChild(l,p,this._bVecToV3(g),this._bVecToV3(m)),e._initOptions||(e._initOptions={axisA:d.clone(),axisB:g.clone(),perpAxisA:f.clone(),perpAxisB:m.clone(),pivotA:new O(h[0],h[1],h[2]),pivotB:new O(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 n=this._constraintToBodyIdPair.get(i[0]);if(n){const s=this._bodies.get(n[0]),a=this._bodies.get(n[1]);s&&a&&t.push({parentBody:s.body,parentBodyIndex:s.index,childBody:a.body,childBodyIndex:a.index})}}return t}addConstraint(e,t,i,n,s){this.initConstraint(i,e,t,n,s)}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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(n,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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(n,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const n=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(n)}return null}setAxisMinLimit(e,t,i){for(const n of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(n,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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(n,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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(n,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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(n,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 n of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(n,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 n=this._shapes.get(e[1][0]);t.shape=n;const s=e[3],a=e[4],o=e[5];t.setHitData({x:a[0],y:a[1],z:a[2]},{x:s[0],y:s[1],z:s[2]},o)}raycast(e,t,i,n){const s=(n==null?void 0:n.membership)??-1,a=(n==null?void 0:n.collideWith)??-1;i.reset(e,t);const o=!1,l=[BigInt(0)],c=[this._bVecToV3(e),this._bVecToV3(t),[s,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,n=((l=e==null?void 0:e.collisionFilter)==null?void 0:l.collideWith)??-1;t.reset();const s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[this._bVecToV3(e.position),e.maxDistance,[i,n],e.shouldHitTriggers,s];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 n=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[n,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,s];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 n=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],a=[n,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,s];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 Ce,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new Ce,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(n=>{this._hknp.HP_Body_SetEventMask(n.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 n=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];n=t?n|this._hknp.EventType.COLLISION_FINISHED.value:n&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach(s=>{this._hknp.HP_Body_SetEventMask(s.hpBodyId,n)}):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,n)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new _Re;for(;e;){_Re.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),n=this._bodies.get(t.bodyIdB);if(i&&n){const s={collider:i.body,colliderIndex:i.index,collidedAgainst:n.body,collidedAgainstIndex:n.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(s)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new gRe,i=Number(this.world);for(;e;){gRe.readToRef(this._hknp.HEAPU8.buffer,e,t);const n=this._bodies.get(t.contactOnA.bodyId),s=this._bodies.get(t.contactOnB.bodyId);if(n&&s){const a={collider:n.body,colliderIndex:n.index,collidedAgainst:s.body,collidedAgainstIndex:s.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=O.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=O.Dot(this._tmpVec3[0],t.contactOnB.normal);if(o&&o.notifyObservers(a),l){const u={collider:s.body,colliderIndex:s.index,collidedAgainst:n.body,collidedAgainstIndex:n.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=O.Dot(this._tmpVec3[0],t.contactOnB.normal);if(o&&o.notifyObservers(a),l){const u={collider:s.body,colliderIndex:s.index,collidedAgainst:n.body,collidedAgainstIndex:n.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"}}Ut.prototype.getPhysicsEngine=function(){return this._physicsEngine};Ut.prototype.enablePhysics=function(r=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(bt.NAME_PHYSICSENGINE);t||(t=new U8t(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new G_e(r,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new Qee(r,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return ge.Error(i.message),!1}};Ut.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};Ut.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};Ut.prototype.deleteCompoundImpostor=function(r){const e=r.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};Ut.prototype._advancePhysicsEngineStep=function(r){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=r;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(r/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class U8t{constructor(e){this.name=bt.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new Ce,this.scene.onAfterPhysicsObservable=new Ce,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(Yt.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(r){this._physicsBody!==r&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=r,r&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});Yt.prototype.getPhysicsBody=function(){return this.physicsBody};Yt.prototype.applyImpulse=function(r,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(r,e),this};Yt.prototype.applyAngularImpulse=function(r){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(r),this};class kS{static GetContactPointToRef(e,t,i,n,s){const a=e.getScene().getPhysicsEngine(),o=a==null?void 0:a.getPluginVersion();if(o===1){const c=new wr(t,i).intersectsMesh(e);if(c.hit&&c.pickedPoint)return n.copyFrom(c.pickedPoint),!0}else if(o===2)return e.physicsBody.getObjectCenterWorldToRef(n,s),!0;return!1}static HasAppliedForces(e,t){var i,n;return e.getMotionType(t)===0||(((i=e.getMassProperties(t))==null?void 0:i.mass)??0)===0||((n=e.transformNode)==null?void 0:n.getTotalVertices())===0}static IsInsideCylinder(e,t,i,n){const s=oe.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=n}}class z8t{constructor(e){if(this._hitData={force:new O,contactPoint:new O,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),!this._physicsEngine){ge.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.");return}}applyRadialExplosionImpulse(e,t,i,n){if(!this._physicsEngine)return ge.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 s=!1;if(typeof t=="number"){const l=t;t=new d5,t.radius=l,t.strength=i??t.strength,t.falloff=n??t.falloff}else s=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new vRe(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),s&&l.push({impostor:u,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(a,e,o,s,(l,c)=>{l.applyImpulse(c.force,c.contactPoint,c.instanceIndex)});return a.dispose(!1),a}applyRadialExplosionForce(e,t,i,n){if(!this._physicsEngine)return ge.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 s=!1;if(typeof t=="number"){const l=t;t=new d5,t.radius=l,t.strength=i??t.strength,t.falloff=n??t.falloff}else s=!!(t.affectedImpostorsCallback||t.affectedBodiesCallback);const a=new vRe(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),s&&l.push({impostor:u,hitData:this._copyPhysicsHitData(o)}))}),a.triggerAffectedImpostorsCallback(l)}else this._applicationForBodies(a,e,o,s,(l,c)=>{l.applyForce(c.force,c.contactPoint,c.instanceIndex)});return a.dispose(!1),a}_applicationForBodies(e,t,i,n,s){const a=Array(),o=this._physicsEngine.getBodies();for(const l of o)l.iterateOverAllInstances((c,u)=>{e.getBodyHitData(c,t,i,u)&&(s(c,i),n&&a.push({body:c,hitData:this._copyPhysicsHitData(i)}))});e.triggerAffectedBodiesCallback(a)}gravitationalField(e,t,i,n){if(!this._physicsEngine)return ge.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 d5,t.radius=a,t.strength=i??t.strength,t.falloff=n??t.falloff}const s=new V8t(this,this._scene,e,t);return s.dispose(!1),s}updraft(e,t,i,n,s){if(!this._physicsEngine)return ge.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 k2e,t.radius=o,t.strength=i??t.strength,t.height=n??t.height,t.updraftMode=s??t.updraftMode}const a=new qee(this._scene,e,t);return a.dispose(!1),a}vortex(e,t,i,n){if(!this._physicsEngine)return ge.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 U2e,t.radius=a,t.strength=i??t.strength,t.height=n??t.height}const s=new _w(this._scene,e,t);return s.dispose(!1),s}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class vRe{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new d5,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,n){const s=oe.Vector3[0];s.copyFrom(t).subtractInPlace(i);const a=oe.Vector3[1];if(!kS.GetContactPointToRef(e,i,s,a,n.instanceIndex))return!1;const l=O.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 s.scaleInPlace(c),n.force.copyFrom(s),n.contactPoint.copyFrom(a),n.distanceFromOrigin=l,!0}getBodyHitData(e,t,i,n){if(kS.HasAppliedForces(e,n))return!1;const s=e.transformNode,a=e.getObjectCenterWorld(n);return i.instanceIndex=n,this._getHitData(s,a,t,i)}getImpostorHitData(e,t,i){if(e.mass===0||e.object.getClassName()!=="Mesh"&&e.object.getClassName()!=="InstancedMesh")return!1;const n=e.object;if(!this._intersectsWithSphere(n,t,this._options.radius))return!1;const s=e.getObjectCenter();return this._getHitData(n,s,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=bu("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 V8t{constructor(e,t,i,n){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=n,this._dataFetched=!1,this._options={...new d5,...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 qee{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=O.Zero(),this._originDirection=O.Zero(),this._cylinderPosition=O.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new k2e,...this._options},this._origin.addToRef(new O(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new O(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 n=O.Distance(this._origin,e),s=this._options.strength*-1,a=i.multiplyByFloats(s,s,s);t.force.copyFrom(a),t.contactPoint.copyFrom(e),t.distanceFromOrigin=n}_getBodyHitData(e,t,i){if(kS.HasAppliedForces(e))return!1;const n=e.getObjectCenterWorld(i);return kS.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(n,t),!0):!1}_getImpostorHitData(e,t){if(e.mass===0)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(n,t),!0}_tick(){const e=qee._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,n)=>{this._getBodyHitData(i,e,n)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=zu("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}}qee._HitData={force:new O,contactPoint:new O,distanceFromOrigin:0};class _w{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=O.Zero(),this._cylinderPosition=O.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new U2e,...this._options},this._origin.addToRef(new O(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new O(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 n=_w._OriginOnPlane;n.set(this._origin.x,t.y,this._origin.z);const s=oe.Vector3[0];t.subtractToRef(n,s);const a=oe.Vector3[1];if(!kS.GetContactPointToRef(e,n,s,a,i.instanceIndex))return!1;const c=O.Distance(a,n)/this._options.radius,u=oe.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 g=O.Cross(n,t).normalize();h=(g.x+u.x)*this._options.centrifugalForceMultiplier,d=this._originTop.y*this._options.updraftForceMultiplier,f=(g.z+u.z)*this._options.centrifugalForceMultiplier}const p=oe.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(kS.HasAppliedForces(e,i))return!1;const n=e.transformNode,s=e.getObjectCenterWorld(i);return kS.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)?(t.instanceIndex=i,this._getHitData(n,s,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 n=e.getObjectCenter();return this._getHitData(i,n,t),!0}_tick(){const e=_w._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,n)=>{this._getBodyHitData(i,e,n)&&i.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=zu("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)}}_w._OriginOnPlane=O.Zero();_w._HitData={force:new O,contactPoint:new O,distanceFromOrigin:0};class d5{constructor(){this.radius=5,this.strength=10,this.falloff=0,this.sphere={segments:32,diameter:1}}}class k2e{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=0}}class U2e{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}var Jde;(function(r){r[r.Constant=0]="Constant",r[r.Linear=1]="Linear"})(Jde||(Jde={}));var efe;(function(r){r[r.Center=0]="Center",r[r.Perpendicular=1]="Perpendicular"})(efe||(efe={}));class G8t extends V_e{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class W8t extends V_e{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}class xV extends ii{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,n,s,a){super(e,"blackAndWhite",["degree"],null,t,i,n,s,a),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(je(()=>Promise.resolve().then(()=>LPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>OPt),void 0)),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new xV(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}V([Q()],xV.prototype,"degree",void 0);xe("BABYLON.BlackAndWhitePostProcess",xV);class sn{constructor(e,t,i,n){this._name=t,this._singleInstance=n||!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=s.attachPostProcess(o);this._indicesForCamera[a].push(l)}),this._cameras[a]||(this._cameras[a]=s)}}_detachCameras(e){const t=Ie.MakeArray(e||this._cameras);if(t)for(let i=0;i{n.detachPostProcess(o)}),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ie.MakeArray(e||this._cameras);if(t)for(let i=0;i{n.detachPostProcess(a)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}class Jee extends ii{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,n,s,a,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,n,s,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,e5)),c.setFloat("exposure",this._exposure)})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(je(()=>Promise.resolve().then(()=>RPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>MPt),void 0)),super._gatherImports(e,t)}}V([Q()],Jee.prototype,"threshold",void 0);xe("BABYLON.ExtractHighlightsPostProcess",Jee);class ete extends ii{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,n,s,a,o,l,c,u=0,h=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,a,o,l,c,null,u,void 0,null,!0),this.weight=1,this.weight=n,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(je(()=>Promise.resolve().then(()=>TPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>EPt),void 0)),super._gatherImports(e,t)}}V([Q()],ete.prototype,"weight",void 0);xe("BABYLON.BloomMergePostProcess",ete);class tfe extends sn{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,n,s=0,a=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new Jee("highlights",1,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._blurX=new Dl("horizontal blur",new Ne(1,0),10,t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Dl("vertical blur",new Ne(0,1),10,t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=n,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new ete("bloomMerge",this._downscale,this._blurY,i,t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,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([je(()=>Promise.resolve().then(()=>xPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>rIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new Gg(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,n)}}V([Q()],Gg.prototype,"aberrationAmount",void 0);V([Q()],Gg.prototype,"radialIntensity",void 0);V([Q()],Gg.prototype,"direction",void 0);V([Q()],Gg.prototype,"centerPosition",void 0);V([Q()],Gg.prototype,"screenWidth",void 0);V([Q()],Gg.prototype,"screenHeight",void 0);xe("BABYLON.ChromaticAberrationPostProcess",Gg);class fT extends ii{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,n,s,a,o,l=0,c=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,n,s,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){ge.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(je(()=>Promise.resolve().then(()=>SPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>APt),void 0)),super._gatherImports(e,t)}set depthTexture(e){this._depthTexture=e}}V([Q()],fT.prototype,"lensSize",void 0);V([Q()],fT.prototype,"fStop",void 0);V([Q()],fT.prototype,"focusDistance",void 0);V([Q()],fT.prototype,"focalLength",void 0);xe("BABYLON.CircleOfConfusionPostProcess",fT);class bV extends ii{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,n,s,a,o){super(e,"colorCorrection",null,["colorTable"],i,n,s,a,o);const l=(n==null?void 0:n.getScene())||null;this._colorTableTexture=new be(t,l,!0,!1,be.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=be.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=be.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=c=>{c.setTexture("colorTable",this._colorTableTexture)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>zPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>UPt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new bV(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}V([Q()],bV.prototype,"colorTableUrl",void 0);xe("BABYLON.ColorCorrectionPostProcess",bV);class Wg extends ii{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,n,s,a,o,l=0){super(e,"convolution",["kernel","screenSize"],null,i,n,s,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([je(()=>Promise.resolve().then(()=>kPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>BPt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new Wg(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,n)}}Wg.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];Wg.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];Wg.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];Wg.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];Wg.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];Wg.GaussianKernel=[0,1,0,1,1,1,0,1,0];V([Q()],Wg.prototype,"kernel",void 0);xe("BABYLON.ConvolutionPostProcess",Wg);class oU extends Dl{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,n,s,a,o,l=null,c=be.BILINEAR_SAMPLINGMODE,u,h,d=0,f=!1,p=5){super(e,i,n,s,a,c=2,u,h,d,`#define DOF 1 `,f,p),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(g=>{l!=null&&g.setTextureFromPostProcess("textureSampler",l),g.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}V([Q()],oU.prototype,"direction",void 0);xe("BABYLON.DepthOfFieldBlurPostProcess",oU);class iYe extends ii{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,n,s,a,o,l,c,u=0,h=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,o,l,c,null,u,void 0,null,!0),this._blurSteps=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),n.forEach((f,p)=>{d.setTextureFromPostProcessOutput("blurStep"+(n.length-p-1),f)})}),h||this.updateEffect()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(je(()=>Promise.resolve().then(()=>CPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>bPt),void 0)),super._gatherImports(e,t)}updateEffect(e=null,t=null,i=null,n,s,a){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+` `),super.updateEffect(e,t,i,n,s,a)}}var ife;(function(r){r[r.Low=0]="Low",r[r.Medium=1]="Medium",r[r.High=2]="High"})(ife||(ife={}));class rfe extends sn{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,n=0,s=!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,be.BILINEAR_SAMPLINGMODE,a,!1,n,s),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(()=>XPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>$Pt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new tte(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}xe("BABYLON.DisplayPassPostProcess",tte);class CV extends ii{getClassName(){return"FilterPostProcess"}constructor(e,t,i,n,s,a,o){super(e,"filter",["kernelMatrix"],null,i,n,s,a,o),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>KPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>WPt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new CV(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}V([DJ()],CV.prototype,"kernelMatrix",void 0);xe("BABYLON.FilterPostProcess",CV);class pT extends ii{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,n,s,a,o=0){super(e,"fxaa",["texelSize"],null,t,i,n||be.BILINEAR_SAMPLINGMODE,s,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([je(()=>Promise.resolve().then(()=>wPt),void 0),je(()=>Promise.resolve().then(()=>DPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>IPt),void 0),je(()=>Promise.resolve().then(()=>PPt),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,n){return ot.Parse(()=>new pT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}xe("BABYLON.FxaaPostProcess",pT);class mT extends ii{getClassName(){return"GrainPostProcess"}constructor(e,t,i,n,s,a,o=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,n,s,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([je(()=>Promise.resolve().then(()=>yPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>vPt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new mT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}V([Q()],mT.prototype,"intensity",void 0);V([Q()],mT.prototype,"animated",void 0);xe("BABYLON.GrainPostProcess",mT);class K8t extends ii{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,n,s,a,o=0){super(e,"highlights",null,null,t,i,n,s,a,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>jPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>HPt),void 0)])),super._gatherImports(e,t)}}class ite extends ii{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 n=this.getEngine(),s=this.getCamera();if(s)i=s.getScene();else if(n&&n.scenes){const a=n.scenes;i=a[a.length-1]}else i=ei.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new Gr}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,n,s,a,o=0,l){super(e,"imageProcessing",[],[],t,i,n,s,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(je(()=>Promise.resolve().then(()=>mPt),void 0))):t.push(je(()=>Promise.resolve().then(()=>gPt),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 n in this._defines){const s=this._defines[n];switch(typeof s){case"number":case"string":e+=`#define ${n} ${s}; `;break;default:s&&(e+=`#define ${n}; `);break}}const t=["textureSampler"],i=["scale"];Gr&&(Gr.PrepareSamplers(t,this._defines),Gr.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)}}V([Q()],ite.prototype,"_fromLinearSpace",void 0);const H8t="mrtFragmentDeclaration",j8t=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif `;me.IncludesShadersStore[H8t]=j8t;const rYe="geometryPixelShader",nYe=`#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 #if defined(PREPASS_NORMAL) || defined(PREPASS_WORLD_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 } `;me.ShadersStore[rYe]=nYe;const sYe={name:rYe,shader:nYe},$8t=Object.freeze(Object.defineProperty({__proto__:null,geometryPixelShader:sYe},Symbol.toStringTag,{value:"Module"})),X8t="geometryVertexDeclaration",Y8t="uniform mat4 viewProjection;uniform mat4 view;";me.IncludesShadersStore[X8t]=Y8t;const Q8t="geometryUboDeclaration",Z8t=`#include `;me.IncludesShadersStore[Q8t]=Z8t;const aYe="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 } `;me.ShadersStore[aYe]=oYe;const lYe={name:aYe,shader:oYe},q8t=Object.freeze(Object.defineProperty({__proto__:null,geometryVertexShader:lYe},Symbol.toStringTag,{value:"Module"})),cYe=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Yo(cYe);class dn{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===dn.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===dn.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===dn.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===dn.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===dn.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 dn.POSITION_TEXTURE_TYPE:return this._positionIndex;case dn.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case dn.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case dn.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case dn.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,n){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 at(0,0,0,0),this._clearDepthColor=new at(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=n||{},this._initShaderSourceAsync(),dn._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!dn.ForceGLSL?(this._shaderLanguage=1,await Promise.all([je(()=>Promise.resolve().then(()=>zwt),void 0),je(()=>Promise.resolve().then(()=>Uwt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>q8t),void 0),je(()=>Promise.resolve().then(()=>$8t),void 0)]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const n=[],s=[ee.PositionKind,ee.NormalKind],a=e.getMesh();if(i){let f=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(n.push("#define ALPHATEST"),n.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),f=!0),i.bumpTexture&<.BumpTextureEnabled&&(n.push("#define BUMP"),n.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let p=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!=null&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),p=!0),i.roughness!=null&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),p=!0),p&&(i.baseTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),f=!0),i.baseColor&&n.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),f=!0,i.specularGlossinessTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&n.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&n.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),f=!0,p=!0),i.metallic!=null&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),p=!0),i.roughness!=null&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),p=!0),p?(i.albedoTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),f=!0),i.albedoColor&&n.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0):i.reflectivityColor&&n.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&n.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture&&(n.push("#define REFLECTIVITYTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0),i.specularColor&&n.push("#define REFLECTIVITYCOLOR"))}f&&(n.push("#define NEED_UV"),a.isVerticesDataPresent(ee.UVKind)&&(s.push(ee.UVKind),n.push("#define UV1")),a.isVerticesDataPresent(ee.UV2Kind)&&(s.push(ee.UV2Kind),n.push("#define UV2")))}this._linkedWithPrePass&&(n.push("#define PREPASS"),this._depthIndex!==-1&&(n.push("#define DEPTH_INDEX "+this._depthIndex),n.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(n.push("#define NORMAL_INDEX "+this._normalIndex),n.push("#define PREPASS_NORMAL"))),this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&n.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(n.push("#define REFLECTIVITY"),n.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&n.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&n.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(s.push(ee.MatricesIndicesKind),s.push(ee.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(ee.MatricesIndicesExtraKind),s.push(ee.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),n.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),n.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(n.push("#define NUM_BONE_INFLUENCERS 0"),n.push("#define BONETEXTURE false"),n.push("#define BonesPerMesh 0"));const o=a.morphTargetManager;let l=0;o&&(l=o.numMaxInfluencers||o.numInfluencers,l>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+l),o.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),tb(s,a,l))),t&&(n.push("#define INSTANCES"),k_(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this._linkedWithPrePass?n.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):n.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),x3(i,this._scene,n);const c=this._scene.getEngine(),u=e._getDrawWrapper(void 0,!0),h=u.defines,d=n.join(` `);return h!==d&&u.setEffect(c.createEffect("geometry",{attributes:s,uniformsNames:cYe,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[dn.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[dn.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[dn.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[dn.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[dn.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,n]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[];for(const m of n)m?(o.push(m.textureType),l.push(m.textureFormat)):(o.push(s),l.push(5));if(this._normalsAreUnsigned=o[dn.NORMAL_TEXTURE_TYPE]===11||o[dn.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new r_("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=be.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=be.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const c=[!0],u=[!1],h=[!0];for(let m=1;m{m.bindAttachments(this.useSpecificClearForDepthTexture?f:d),m.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(m.bindAttachments(p),m.clear(this._clearDepthColor,!0,!0,!0)),m.bindAttachments(d)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const m=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(m)}});const g=m=>{const _=m.getRenderingMesh(),y=m.getEffectiveMesh(),v=this._scene,x=v.getEngine(),b=m.getMaterial();if(!b)return;if(y._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[y.uniqueId]&&(this._previousTransformationMatrices[y.uniqueId]={world:pe.Identity(),viewProjection:v.getTransformMatrix()},_.skeleton)){const P=_.skeleton.getTransformMatrices(_);this._previousBonesTransformationMatrices[_.uniqueId]=this._copyBonesTransformationMatrices(P,new Float32Array(P.length))}const C=_._getInstancesRenderList(m._id,!!m.getReplacementMesh());if(C.mustReturn)return;const A=x.getCaps().instancedArrays&&(C.visibleInstances[m._id]!==null||_.hasThinInstances),E=y.getWorldMatrix();if(this.isReady(m,A)){const P=m._getDrawWrapper();if(!P)return;const w=P.effect;x.enableEffect(P),A||_._bind(m,w,b.fillMode),this._useUbo?(tD(w,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(w.setMatrix("viewProjection",v.getTransformMatrix()),w.setMatrix("view",v.getViewMatrix()));let M;const R=_._instanceDataStorage;if(!R.isFrozen&&(b.backFaceCulling||b.sideOrientation!==null)){const I=y._getWorldMatrixDeterminant();M=b._getEffectiveOrientation(_),I<0&&(M=M===tt.ClockWiseSideOrientation?tt.CounterClockWiseSideOrientation:tt.ClockWiseSideOrientation)}else M=R.sideOrientation;if(b._preBind(P,M),b.needAlphaTesting()){const I=b.getAlphaTestTexture();I&&(w.setTexture("diffuseSampler",I),w.setMatrix("diffuseMatrix",I.getTextureMatrix()))}if(b.bumpTexture&&v.getEngine().getCaps().standardDerivatives&<.BumpTextureEnabled&&(w.setFloat3("vBumpInfos",b.bumpTexture.coordinatesIndex,1/b.bumpTexture.level,b.parallaxScaleBias),w.setMatrix("bumpMatrix",b.bumpTexture.getTextureMatrix()),w.setTexture("bumpSampler",b.bumpTexture),w.setFloat2("vTangentSpaceParams",b.invertNormalMapX?-1:1,b.invertNormalMapY?-1:1)),this._enableReflectivity&&(b.getClassName()==="PBRMetallicRoughnessMaterial"?(b.metallicRoughnessTexture!==null&&(w.setTexture("reflectivitySampler",b.metallicRoughnessTexture),w.setMatrix("reflectivityMatrix",b.metallicRoughnessTexture.getTextureMatrix())),b.metallic!==null&&w.setFloat("metallic",b.metallic),b.roughness!==null&&w.setFloat("glossiness",1-b.roughness),b.baseTexture!==null&&(w.setTexture("albedoSampler",b.baseTexture),w.setMatrix("albedoMatrix",b.baseTexture.getTextureMatrix())),b.baseColor!==null&&w.setColor3("albedoColor",b.baseColor)):b.getClassName()==="PBRSpecularGlossinessMaterial"?(b.specularGlossinessTexture!==null?(w.setTexture("reflectivitySampler",b.specularGlossinessTexture),w.setMatrix("reflectivityMatrix",b.specularGlossinessTexture.getTextureMatrix())):b.specularColor!==null&&w.setColor3("reflectivityColor",b.specularColor),b.glossiness!==null&&w.setFloat("glossiness",b.glossiness)):b.getClassName()==="PBRMaterial"?(b.metallicTexture!==null&&(w.setTexture("reflectivitySampler",b.metallicTexture),w.setMatrix("reflectivityMatrix",b.metallicTexture.getTextureMatrix())),b.metallic!==null&&w.setFloat("metallic",b.metallic),b.roughness!==null&&w.setFloat("glossiness",1-b.roughness),b.roughness!==null||b.metallic!==null||b.metallicTexture!==null?(b.albedoTexture!==null&&(w.setTexture("albedoSampler",b.albedoTexture),w.setMatrix("albedoMatrix",b.albedoTexture.getTextureMatrix())),b.albedoColor!==null&&w.setColor3("albedoColor",b.albedoColor)):(b.reflectivityTexture!==null?(w.setTexture("reflectivitySampler",b.reflectivityTexture),w.setMatrix("reflectivityMatrix",b.reflectivityTexture.getTextureMatrix())):b.reflectivityColor!==null&&w.setColor3("reflectivityColor",b.reflectivityColor),b.microSurface!==null&&w.setFloat("glossiness",b.microSurface))):b.getClassName()==="StandardMaterial"&&(b.specularTexture!==null&&(w.setTexture("reflectivitySampler",b.specularTexture),w.setMatrix("reflectivityMatrix",b.specularTexture.getTextureMatrix())),b.specularColor!==null&&w.setColor3("reflectivityColor",b.specularColor))),wo(w,b,this._scene),_.useBones&&_.computeBonesUsingShaders&&_.skeleton){const I=_.skeleton;if(I.isUsingTextureForMatrices&&w.getUniformIndex("boneTextureWidth")>-1){const D=I.getTransformMatrixTexture(_);w.setTexture("boneSampler",D),w.setFloat("boneTextureWidth",4*(I.bones.length+1))}else w.setMatrices("mBones",_.skeleton.getTransformMatrices(_));this._enableVelocity&&w.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[_.uniqueId])}Np(_,w),_.morphTargetManager&&_.morphTargetManager.isUsingTextureForTargets&&_.morphTargetManager._bind(w),this._enableVelocity&&(w.setMatrix("previousWorld",this._previousTransformationMatrices[y.uniqueId].world),w.setMatrix("previousViewProjection",this._previousTransformationMatrices[y.uniqueId].viewProjection)),A&&_.hasThinInstances&&w.setMatrix("world",E),_._processRendering(y,m,w,b.fillMode,C,A,(I,D)=>{I||w.setMatrix("world",D)})}this._enableVelocity&&(this._previousTransformationMatrices[y.uniqueId].world=E.clone(),this._previousTransformationMatrices[y.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),_.skeleton&&this._copyBonesTransformationMatrices(_.skeleton.getTransformMatrices(_),this._previousBonesTransformationMatrices[y.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(m,_,y)=>{if((y||_===0)&&m.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 Ji("GeometryBufferRendererSceneComponent")};class J8t{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Ut.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(r){r&&r.isSupported&&(this._geometryBufferRenderer=r)},enumerable:!0,configurable:!0});Ut.prototype.enableGeometryBufferRenderer=function(r=1,e=15,t){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new dn(this,r,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};Ut.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class uYe{constructor(e){this.name=bt.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(bt.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}dn._SceneComponentInitialization=r=>{let e=r._getComponent(bt.NAME_GEOMETRYBUFFERRENDERER);e||(e=new uYe(r),r._addComponent(e))};class ob extends ii{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,n,s,a,o,l=0,c=!1,u=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,n,s,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 J8t)),this._applyMode()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([je(()=>Promise.resolve().then(()=>GPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>VPt),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 ge.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=pe.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 Ne(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(dn.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=oe.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 Ne(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(dn.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,n){return ot.Parse(()=>new ob(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,n)}}V([Q()],ob.prototype,"motionStrength",void 0);V([Q()],ob.prototype,"motionBlurSamples",null);V([Q()],ob.prototype,"isObjectBased",null);xe("BABYLON.MotionBlurPostProcess",ob);const eIt="refractionPixelShader",tIt="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);}";me.ShadersStore[eIt]=tIt;class lb extends ii{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,n,s,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=n,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(h=>{this._refTexture=this._refTexture||new be(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,n){return ot.Parse(()=>new lb(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,n)}}V([Q()],lb.prototype,"color",void 0);V([Q()],lb.prototype,"depth",void 0);V([Q()],lb.prototype,"colorLevel",void 0);V([Q()],lb.prototype,"refractionTextureUrl",void 0);xe("BABYLON.RefractionPostProcess",lb);const hYe="sharpenPixelShader",dYe=`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.);}`;me.ShadersStore[hYe]=dYe;const fYe={name:hYe,shader:dYe},iIt=Object.freeze(Object.defineProperty({__proto__:null,sharpenPixelShader:fYe},Symbol.toStringTag,{value:"Module"}));class gT extends ii{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,n,s,a,o=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,n,s,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([je(()=>Promise.resolve().then(()=>_Pt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>iIt),void 0)])),super._gatherImports(e,t)}static _Parse(e,t,i,n){return ot.Parse(()=>new gT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,n)}}V([Q()],gT.prototype,"colorAmount",void 0);V([Q()],gT.prototype,"edgeAmount",void 0);xe("BABYLON.SharpenPostProcess",gT);class V_{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(Ie.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ie.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ie.MakeArray(e||this._cameras);if(!i)return;const n=[];let s;for(s=0;s0){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 n of i)n.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}V([Q()],V_.prototype,"_name",void 0);class pYe{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 n=this._renderPipelines[e];n&&n._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._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(Ut.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let r=this._getComponent(bt.NAME_POSTPROCESSRENDERPIPELINEMANAGER);r||(r=new mYe(this),this._addComponent(r)),this._postProcessRenderPipelineManager=new pYe}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class mYe{constructor(e){this.name=bt.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(bt.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 Cc extends V_{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 tfe(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 rfe(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 tfe(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new Gg("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,be.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new sn(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new mT("Grain",1,null,be.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new sn(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?Ie.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 ite("imageProcessing",1,null,be.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new sn(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,be.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new sn(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&&ge.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 Cc(e._name,e._name._hdr,t),e,t,i)}}V([Q()],Cc.prototype,"sharpenEnabled",null);V([Q()],Cc.prototype,"bloomKernel",null);V([Q()],Cc.prototype,"_bloomWeight",void 0);V([Q()],Cc.prototype,"_bloomThreshold",void 0);V([Q()],Cc.prototype,"_hdr",void 0);V([Q()],Cc.prototype,"bloomWeight",null);V([Q()],Cc.prototype,"bloomThreshold",null);V([Q()],Cc.prototype,"bloomScale",null);V([Q()],Cc.prototype,"bloomEnabled",null);V([Q()],Cc.prototype,"depthOfFieldEnabled",null);V([Q()],Cc.prototype,"depthOfFieldBlurLevel",null);V([Q()],Cc.prototype,"fxaaEnabled",null);V([Q()],Cc.prototype,"samples",null);V([Q()],Cc.prototype,"imageProcessingEnabled",null);V([Q()],Cc.prototype,"glowLayerEnabled",null);V([Q()],Cc.prototype,"chromaticAberrationEnabled",null);V([Q()],Cc.prototype,"grainEnabled",null);xe("BABYLON.DefaultRenderingPipeline",Cc);const gYe="chromaticAberrationPixelShader",_Ye=`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);}`;me.ShadersStore[gYe]=_Ye;const vYe={name:gYe,shader:_Ye},rIt=Object.freeze(Object.defineProperty({__proto__:null,chromaticAberrationPixelShader:vYe},Symbol.toStringTag,{value:"Module"})),nIt="lensHighlightsPixelShader",sIt=`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;}`;me.ShadersStore[nIt]=sIt;const aIt="depthOfFieldPixelShader",oIt=`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;}} `;me.ShadersStore[aIt]=oIt;class lIt extends V_{constructor(e,t,i,n=1,s){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(n),this._createHighlightsPostProcess(n),this._createDepthOfFieldPostProcess(n/4),this.addEffect(new sn(i.getEngine(),this.LensChromaticAberrationEffect,()=>this._chromaticAberrationPostProcess,!0)),this.addEffect(new sn(i.getEngine(),this.HighlightsEnhancingEffect,()=>this._highlightsPostProcess,!0)),this.addEffect(new sn(i.getEngine(),this.LensDepthOfFieldEffect,()=>this._depthOfFieldPostProcess,!0)),this._highlightsGain===-1&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),s&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}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 ii("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,be.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 ii("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,be.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 ii("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,be.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 n=0;nthis._originalColorPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}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,n=1-e*.85,s=Math.sqrt(1-n*n);return new O(Math.cos(i)*s,Math.sin(i)*s,n)}_generateHemisphere(){const e=this.samples,t=[];let i,n=0;for(;n{s?a.push(je(()=>Promise.resolve().then(()=>SIt),void 0)):a.push(je(()=>Promise.resolve().then(()=>AIt),void 0))}),this._ssaoPostProcess.autoClear=!1,this._ssaoPostProcess.onApply=s=>{if(this._scene.activeCamera){if(s.setArray3("sampleSphere",this._sampleSphere),s.setFloat("randTextureTiles",32),s.setFloat("samplesFactor",1/this.samples),s.setFloat("totalStrength",this.totalStrength),s.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),s.setFloat("radius",this.radius),s.setFloat("maxZ",this.maxZ),s.setFloat("minZAspect",this.minZAspect),s.setFloat("base",this.base),s.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===di.PERSPECTIVE_CAMERA)s.setMatrix3x3("depthProjection",Nl.PERSPECTIVE_DEPTH_PROJECTION),s.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),s.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;s.setMatrix3x3("depthProjection",Nl.ORTHO_DEPTH_PROJECTION),s.setFloat("xViewport",(c-l)*.5),s.setFloat("yViewport",(h-u)*.5)}s.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(s.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),s.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(s.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),s.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),s.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new cIt)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new ii("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(i,n)=>{i?n.push(je(()=>Promise.resolve().then(()=>EIt),void 0)):n.push(je(()=>Promise.resolve().then(()=>dIt),void 0))}),this._ssaoCombinePostProcess.onApply=i=>{const n=this._scene.activeCamera.viewport;i.setVector4("viewport",oe.Vector4[0].copyFromFloats(n.x,n.y,n.width,n.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=Ne.Zero();for(let s=0;snew Nl(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}Nl.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];Nl.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];V([Q()],Nl.prototype,"totalStrength",void 0);V([Q()],Nl.prototype,"maxZ",void 0);V([Q()],Nl.prototype,"minZAspect",void 0);V([Q("epsilon")],Nl.prototype,"_epsilon",void 0);V([Q("samples")],Nl.prototype,"_samples",void 0);V([Q("textureSamples")],Nl.prototype,"_textureSamples",void 0);V([Q()],Nl.prototype,"_forceGeometryBuffer",void 0);V([Q()],Nl.prototype,"_ratio",void 0);V([Q()],Nl.prototype,"_textureType",void 0);V([Q()],Nl.prototype,"radius",void 0);V([Q()],Nl.prototype,"base",void 0);V([Q("bypassBlur")],Nl.prototype,"_bypassBlur",void 0);V([Q("expensiveBlur")],Nl.prototype,"_expensiveBlur",void 0);V([Q()],Nl.prototype,"bilateralSamples",void 0);V([Q()],Nl.prototype,"bilateralSoften",void 0);V([Q()],Nl.prototype,"bilateralTolerance",void 0);xe("BABYLON.SSAO2RenderingPipeline",Nl);const uIt="ssaoPixelShader",hIt=`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 sn(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new sn(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}_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],n=1/16;this._ssaoPostProcess=new ii("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define SAMPLES 16 #define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=s=>{this._firstUpdate&&(s.setArray3("sampleSphere",i),s.setFloat("samplesFactor",n),s.setFloat("randTextureTiles",4)),s.setFloat("totalStrength",this.totalStrength),s.setFloat("radius",this.radius),s.setFloat("area",this.area),s.setFloat("fallOff",this.fallOff),s.setFloat("base",this.base),s.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),s.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new ii("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,be.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",oe.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let n=0;n0.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(dn.POSITION_TEXTURE_TYPE),y=d.getTextureIndex(dn.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 g=p.getViewMatrix(!0),m=p.getProjectionMatrix(!0);h.setMatrix("projection",m),h.setMatrix("view",g),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,n){return ot.Parse(()=>new Fp(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,n)}}V([Q()],Fp.prototype,"threshold",void 0);V([Q()],Fp.prototype,"strength",void 0);V([Q()],Fp.prototype,"reflectionSpecularFalloffExponent",void 0);V([Q()],Fp.prototype,"step",void 0);V([Q()],Fp.prototype,"roughnessFactor",void 0);V([Q()],Fp.prototype,"enableSmoothReflections",null);V([Q()],Fp.prototype,"reflectionSamples",null);V([Q()],Fp.prototype,"smoothSteps",null);xe("BABYLON.ScreenSpaceReflectionPostProcess",Fp);const gIt="standardPixelShader",_It=`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 `;me.ShadersStore[gIt]=_It;class Ln extends V_{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()){ge.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,n=null,s){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=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=n,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 Fp("HDRPass",t,e,null,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new sn(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new ii("HDRPass","standard",[],[],e,null,be.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 sn(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 ii("HDRDepthOfFieldSource","standard",[],[],e,null,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new sn(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new ii("HDRVLSFinal","standard",[],[],e,null,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new sn(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new ii("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new sn(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new ii("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new sn(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,be.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new sn(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&ge.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 ii("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=n=>{let s=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[s]=(l+.5)*(1/a),i[s+1]=(c+.5)*(1/o),s+=2;n.setArray2("dsOffsets",i)},this.addEffect(new sn(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new ii("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=n=>{const s=1/this.brightPassPostProcess.width,a=1/this.brightPassPostProcess.height;i[0]=-.5*s,i[1]=.5*a,i[2]=.5*s,i[3]=.5*a,i[4]=-.5*s,i[5]=-.5*a,i[6]=.5*s,i[7]=-.5*a,n.setArray2("dsOffsets",i),n.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new sn(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,n="blurWidth"){const s=e.getEngine(),a=new Dl("HDRBlurH_"+i,new Ne(1,0),this[n],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Dl("HDRBlurV_"+i,new Ne(0,1),this[n],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add(()=>{const l=a.width/s.getRenderWidth();a.kernel=this[n]*l}),o.onActivateObservable.add(()=>{const l=o.height/s.getRenderHeight();o.kernel=this.horizontalBlur?64*l:this[n]*l}),this.addEffect(new sn(e.getEngine(),"HDRBlurH"+i,()=>a,!0)),this.addEffect(new sn(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new ii("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,be.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 sn(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const n=i.getGBuffer();this.volumetricLightPostProcess=new ii("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS #define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const s=Ne.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",n.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),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),a.setVector2("depthValues",s)}},this.addEffect(new sn(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new ii("HDRVLSMerge","standard",[],["originalSampler"],t,null,be.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 sn(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Ln.LuminanceSteps);this.luminancePostProcess=new ii("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const n=[];this.luminancePostProcess.onApply=a=>{const o=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;n[0]=-.5*o,n[1]=.5*l,n[2]=.5*o,n[3]=.5*l,n[4]=-.5*o,n[5]=-.5*l,n[6]=.5*o,n[7]=-.5*l,a.setArray2("lumOffsets",n)},this.addEffect(new sn(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let a=Ln.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 ii("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(l)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((a,o)=>{const l=new Array(18);a.onApply=c=>{if(!s)return;let u=0;for(let h=-1;h<2;h++)for(let d=-1;d<2;d++)l[u]=h/s.width,l[u+1]=d/s.height,u+=2;c.setArray2("dsOffsets",l),c.setFloat("halfDestPixelSize",.5/s.width),o===this.luminanceDownSamplePostProcesses.length-1?s=this.luminancePostProcess:s=a},o===this.luminanceDownSamplePostProcesses.length-1&&(a.onAfterRender=()=>{const c=e.getEngine().readPixels(0,0,1,1),u=new It(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 sn(e.getEngine(),"HDRLuminanceDownSample"+o,()=>a,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new ii("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` `),0);let n=1,s=0,a=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),n<0)n=this._hdrCurrentLuminance;else{const l=(a-s)/1e3;this._hdrCurrentLuminancen-this.hdrIncreaseRate*l?n-=this.hdrIncreaseRate*l:n=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/n:(n=Xt.Clamp(n,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",n)),a=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new sn(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new ii("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new sn(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new ii("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new sn(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new Ne(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 n=pe.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=pe.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=O.Dot(o.toVector3(),new O(1,0,0))+O.Dot(l.toVector3(),new O(0,0,1));c*=4;const u=pe.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=s.multiply(u).multiply(n);a.setMatrix("lensStarMatrix",h),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new ii("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,be.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 sn(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new ob("HDRMotionBlur",e,t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new ii("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,be.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR #define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,n=pe.Identity();const s=pe.Identity();let a=pe.Identity();const o=Ne.Zero();this.motionBlurPostProcess.onApply=l=>{a=e.getProjectionMatrix().multiply(e.getViewMatrix()),a.invertToRef(s),l.setMatrix("inverseViewProjection",s),l.setMatrix("prevViewProjection",n),n=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 sn(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 Ln(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(n.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&ot.Parse(()=>n.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),n}}Ln.LuminanceSteps=6;V([Q()],Ln.prototype,"brightThreshold",void 0);V([Q()],Ln.prototype,"blurWidth",void 0);V([Q()],Ln.prototype,"horizontalBlur",void 0);V([Q()],Ln.prototype,"exposure",null);V([ki("lensTexture")],Ln.prototype,"lensTexture",void 0);V([Q()],Ln.prototype,"volumetricLightCoefficient",void 0);V([Q()],Ln.prototype,"volumetricLightPower",void 0);V([Q()],Ln.prototype,"volumetricLightBlurScale",void 0);V([Q()],Ln.prototype,"hdrMinimumLuminance",void 0);V([Q()],Ln.prototype,"hdrDecreaseRate",void 0);V([Q()],Ln.prototype,"hdrIncreaseRate",void 0);V([Q()],Ln.prototype,"hdrAutoExposure",null);V([ki("lensColorTexture")],Ln.prototype,"lensColorTexture",void 0);V([Q()],Ln.prototype,"lensFlareStrength",void 0);V([Q()],Ln.prototype,"lensFlareGhostDispersal",void 0);V([Q()],Ln.prototype,"lensFlareHaloWidth",void 0);V([Q()],Ln.prototype,"lensFlareDistortionStrength",void 0);V([Q()],Ln.prototype,"lensFlareBlurWidth",void 0);V([ki("lensStarTexture")],Ln.prototype,"lensStarTexture",void 0);V([ki("lensFlareDirtTexture")],Ln.prototype,"lensFlareDirtTexture",void 0);V([Q()],Ln.prototype,"depthOfFieldDistance",void 0);V([Q()],Ln.prototype,"depthOfFieldBlurWidth",void 0);V([Q()],Ln.prototype,"motionStrength",null);V([Q()],Ln.prototype,"objectBasedMotionBlur",null);V([Q()],Ln.prototype,"_ratio",void 0);V([Q()],Ln.prototype,"BloomEnabled",null);V([Q()],Ln.prototype,"DepthOfFieldEnabled",null);V([Q()],Ln.prototype,"LensFlareEnabled",null);V([Q()],Ln.prototype,"HDREnabled",null);V([Q()],Ln.prototype,"VLSEnabled",null);V([Q()],Ln.prototype,"MotionBlurEnabled",null);V([Q()],Ln.prototype,"fxaaEnabled",null);V([Q()],Ln.prototype,"screenSpaceReflectionsEnabled",null);V([Q()],Ln.prototype,"volumetricLightStepsCount",null);V([Q()],Ln.prototype,"motionBlurSamples",null);V([Q()],Ln.prototype,"samples",null);xe("BABYLON.StandardRenderingPipeline",Ln);class vIt{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const yIt=pe.Compose(new O(.5,.5,.5),Oe.Identity(),new O(.5,.5,.5)),xIt=pe.Compose(new O(.5,.5,1),Oe.Identity(),new O(.5,.5,0));class Ns extends V_{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,n=!1,s=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=s,this._forceGeometryBuffer=n,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 n,s;const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&((n=this._scene.activeCamera)==null?void 0:n._getFirstPostProcess())===this._ssrPostProcess){const a=t.getRenderTarget();a&&a.textures&&(i=a.textures[t.getIndex(4)].getSize())}else(s=this._ssrPostProcess)!=null&&s.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){var i,n,s,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)??((n=this._prePassRenderer)==null?void 0:n.generateNormalsInWorldSpace))&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(s=this._geometryBufferRenderer)!=null&&s.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 I_(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 sn(e,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new sn(e,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new sn(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)),n=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==n)&&this._depthRenderer.getDepthMap().resize({width:i,height:n})}_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,n;for(let s=0;s{e?t.push(je(()=>Promise.resolve().then(()=>DIt),void 0)):t.push(je(()=>Promise.resolve().then(()=>RIt),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(dn.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 n=this._scene.activeCamera;if(!n)return;const s=n.getViewMatrix(),a=n.getProjectionMatrix();a.invertToRef(oe.Matrix[0]),s.invertToRef(oe.Matrix[1]),e.setMatrix("projection",a),e.setMatrix("view",s),e.setMatrix("invView",oe.Matrix[1]),e.setMatrix("invProjectionMatrix",oe.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",n.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();pe.ScalingToRef(o.width,o.height,1,oe.Matrix[2]),a.multiplyToRef(this._scene.getEngine().isWebGPU?xIt:yIt,oe.Matrix[3]),oe.Matrix[3].multiplyToRef(oe.Matrix[2],oe.Matrix[4]),e.setMatrix("projectionPixel",oe.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 vIt)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new ii("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,(s,a)=>{s?a.push(je(()=>Promise.resolve().then(()=>xRe),void 0)):a.push(je(()=>Promise.resolve().then(()=>yRe),void 0))}),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(s=>{var o;const a=((o=this._blurPostProcessX)==null?void 0:o.inputTexture.width)??this._scene.getEngine().getRenderWidth();s.setFloat2("texelOffsetScale",this._blurDispersionStrength/a,0)}),this._blurPostProcessY=new ii("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,(s,a)=>{s?a.push(je(()=>Promise.resolve().then(()=>xRe),void 0)):a.push(je(()=>Promise.resolve().then(()=>yRe),void 0))}),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(s=>{var o;const a=((o=this._blurPostProcessY)==null?void 0:o.inputTexture.height)??this._scene.getEngine().getRenderHeight();s.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/a)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let n="";this._debug&&(n+=`#define SSRAYTRACE_DEBUG `),this._inputTextureColorIsInGammaSpace&&(n+=`#define SSR_INPUT_IS_GAMMA_SPACE `),this._generateOutputInGammaSpace&&(n+=`#define SSR_OUTPUT_IS_GAMMA_SPACE `),this.useFresnel&&(n+=`#define SSR_BLEND_WITH_FRESNEL `,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(n+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new ii("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,n,this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,(s,a)=>{s?a.push(je(()=>Promise.resolve().then(()=>OIt),void 0)):a.push(je(()=>Promise.resolve().then(()=>IIt),void 0))}),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(s=>{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&&s.setTexture("mainSampler",c.textures[o.getIndex(4)])}else s.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(a){const c=a.getTextureIndex(dn.REFLECTIVITY_TEXTURE_TYPE);s.setTexture("reflectivitySampler",a.getGBuffer().textures[c]),this.useFresnel&&(s.setTexture("normalSampler",a.getGBuffer().textures[1]),s.setTexture("depthSampler",a.getGBuffer().textures[0]))}else if(o){const c=o.getIndex(3);if(s.setTexture("reflectivitySampler",o.getRenderTarget().textures[c]),this.useFresnel){const u=o.getIndex(5),h=o.getIndex(6);s.setTexture("normalSampler",o.getRenderTarget().textures[h]),s.setTexture("depthSampler",o.getRenderTarget().textures[u])}}if(s.setFloat("strength",this.strength),s.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),s.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const c=this._scene.activeCamera;if(c){const u=c.getProjectionMatrix();u.invertToRef(oe.Matrix[0]),s.setMatrix("projection",u),s.setMatrix("invProjectionMatrix",oe.Matrix[0])}}}})}serialize(){const e=ot.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return ot.Parse(()=>new Ns(e._name,t,e._ratio),e,t,i)}}V([Q()],Ns.prototype,"samples",null);V([Q()],Ns.prototype,"maxDistance",void 0);V([Q()],Ns.prototype,"step",void 0);V([Q()],Ns.prototype,"thickness",void 0);V([Q()],Ns.prototype,"strength",void 0);V([Q()],Ns.prototype,"reflectionSpecularFalloffExponent",void 0);V([Q()],Ns.prototype,"maxSteps",void 0);V([Q()],Ns.prototype,"roughnessFactor",void 0);V([Q()],Ns.prototype,"selfCollisionNumSkip",void 0);V([Q()],Ns.prototype,"_reflectivityThreshold",void 0);V([Q("_ssrDownsample")],Ns.prototype,"_ssrDownsample",void 0);V([Q()],Ns.prototype,"ssrDownsample",null);V([Q("blurDispersionStrength")],Ns.prototype,"_blurDispersionStrength",void 0);V([Q("blurDownsample")],Ns.prototype,"_blurDownsample",void 0);V([Q("enableSmoothReflections")],Ns.prototype,"_enableSmoothReflections",void 0);V([Q("environmentTexture")],Ns.prototype,"_environmentTexture",void 0);V([Q("environmentTextureIsProbe")],Ns.prototype,"_environmentTextureIsProbe",void 0);V([Q("attenuateScreenBorders")],Ns.prototype,"_attenuateScreenBorders",void 0);V([Q("attenuateIntersectionDistance")],Ns.prototype,"_attenuateIntersectionDistance",void 0);V([Q("attenuateIntersectionIterations")],Ns.prototype,"_attenuateIntersectionIterations",void 0);V([Q("attenuateFacingCamera")],Ns.prototype,"_attenuateFacingCamera",void 0);V([Q("attenuateBackfaceReflection")],Ns.prototype,"_attenuateBackfaceReflection",void 0);V([Q("clipToFrustum")],Ns.prototype,"_clipToFrustum",void 0);V([Q("useFresnel")],Ns.prototype,"_useFresnel",void 0);V([Q("enableAutomaticThicknessComputation")],Ns.prototype,"_enableAutomaticThicknessComputation",void 0);V([Q("backfaceDepthTextureDownsample")],Ns.prototype,"_backfaceDepthTextureDownsample",void 0);V([Q("backfaceForceDepthWriteTransparentMeshes")],Ns.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);V([Q("isEnabled")],Ns.prototype,"_isEnabled",void 0);V([Q("inputTextureColorIsInGammaSpace")],Ns.prototype,"_inputTextureColorIsInGammaSpace",void 0);V([Q("generateOutputInGammaSpace")],Ns.prototype,"_generateOutputInGammaSpace",void 0);V([Q("debug")],Ns.prototype,"_debug",void 0);xe("BABYLON.SSRRenderingPipeline",Ns);const bIt="taaPixelShader",CIt=`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);} `;me.ShadersStore[bIt]=CIt;class S3 extends V_{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,n=0){const s=t.getEngine();super(s,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=n,this._hs=new zje(this.samples),this.isSupported&&(this._createPingPongTextures(s.getRenderWidth(),s.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 n,s;const i=this._scene.getEngine();(n=this._ping)==null||n.dispose(),(s=this._pong)==null||s.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 sn(e,this.TAARenderEffect,()=>this._taaPostProcess,!0)),this._createPassPostProcess(),this.addEffect(new sn(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 n=this._scene.getEngine();this._createPingPongTextures(n.getRenderWidth(),n.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===di.PERSPECTIVE_CAMERA){const n=e.getProjectionMatrix();n.setRowFromFloats(2,this._hs.x,this._hs.y,n.m[10],n.m[11])}else{const n=e.getProjectionMatrix(!0);n.setRowFromFloats(3,this._hs.x+n.m[12],this._hs.y+n.m[13],n.m[14],n.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 J0("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=ot.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return ot.Parse(()=>new S3(e._name,t,e._ratio),e,t,i)}}V([Q("samples")],S3.prototype,"_samples",void 0);V([Q("msaaSamples")],S3.prototype,"_msaaSamples",void 0);V([Q()],S3.prototype,"factor",void 0);V([Q()],S3.prototype,"disableOnCameraMove",void 0);V([Q("isEnabled")],S3.prototype,"_isEnabled",void 0);xe("BABYLON.TAARenderingPipeline",S3);const CYe="ssao2PixelShader",AYe=`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 } `;me.ShadersStoreWGSL[RYe]=IYe;const PYe={name:RYe,shader:IYe},EIt=Object.freeze(Object.defineProperty({__proto__:null,ssaoCombinePixelShaderWGSL:PYe},Symbol.toStringTag,{value:"Module"})),TIt="screenSpaceRayTrace",MIt=`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;} `;me.IncludesShadersStore[TIt]=MIt;const wYe="screenSpaceReflection2PixelShader",DYe=`#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 } `;me.ShadersStore[wYe]=DYe;const OYe={name:wYe,shader:DYe},RIt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2PixelShader:OYe},Symbol.toStringTag,{value:"Module"})),LYe="screenSpaceReflection2BlurPixelShader",NYe=`#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);} `;me.ShadersStore[LYe]=NYe;const FYe={name:LYe,shader:NYe},yRe=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurPixelShader:FYe},Symbol.toStringTag,{value:"Module"})),BYe="screenSpaceReflection2BlurCombinerPixelShader",kYe=`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 } `;me.ShadersStore[BYe]=kYe;const UYe={name:BYe,shader:kYe},IIt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurCombinerPixelShader:UYe},Symbol.toStringTag,{value:"Module"})),PIt="screenSpaceRayTrace",wIt=`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;} `;me.IncludesShadersStoreWGSL[PIt]=wIt;const zYe="screenSpaceReflection2PixelShader",VYe=`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 } `;me.ShadersStoreWGSL[zYe]=VYe;const GYe={name:zYe,shader:VYe},DIt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2PixelShaderWGSL:GYe},Symbol.toStringTag,{value:"Module"})),WYe="screenSpaceReflection2BlurPixelShader",KYe=`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);} `;me.ShadersStoreWGSL[WYe]=KYe;const HYe={name:WYe,shader:KYe},xRe=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurPixelShaderWGSL:HYe},Symbol.toStringTag,{value:"Module"})),jYe="screenSpaceReflection2BlurCombinerPixelShader",$Ye=`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 } `;me.ShadersStoreWGSL[jYe]=$Ye;const XYe={name:jYe,shader:$Ye},OIt=Object.freeze(Object.defineProperty({__proto__:null,screenSpaceReflection2BlurCombinerPixelShaderWGSL:XYe},Symbol.toStringTag,{value:"Module"}));var nfe;(function(r){r[r.Hable=0]="Hable",r[r.Reinhard=1]="Reinhard",r[r.HejiDawson=2]="HejiDawson",r[r.Photographic=3]="Photographic"})(nfe||(nfe={}));class LIt extends ii{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,n,s=2,a,o=0,l){super(e,"tonemap",["_ExposureAdjustment"],null,1,n,s,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([je(()=>Promise.resolve().then(()=>QPt),void 0)]))):t.push(Promise.all([je(()=>Promise.resolve().then(()=>YPt),void 0)])),super._gatherImports(e,t)}}const NIt="volumetricLightScatteringPixelShader",FIt=`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 } `;me.ShadersStore[BIt]=kIt;const UIt="volumetricLightScatteringPassPixelShader",zIt=`#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);} `;me.ShadersStore[UIt]=zIt;class wf extends ii{get useDiffuseColor(){return ge.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){ge.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,n,s=100,a=be.BILINEAR_SAMPLINGMODE,o,l,c){super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,a,o,l,"#define NUM_SAMPLES "+s),this._screenCoordinates=Ne.Zero(),this.customMeshPosition=O.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 Yc(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=n??wf.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 g;const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const n=(g=i._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:g[this._scene.getEngine().currentRenderPassId];if(n)return n.isReadyForSubMesh(i,e,t);const s=[],a=[ee.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&s.push("#define ALPHATEST"),i.isVerticesDataPresent(ee.UVKind)&&(a.push(ee.UVKind),s.push("#define UV1")),i.isVerticesDataPresent(ee.UV2Kind)&&(a.push(ee.UV2Kind),s.push("#define UV2")));const l=new ha;if(i.useBones&&i.computeBonesUsingShaders&&i.skeleton){a.push(ee.MatricesIndicesKind),a.push(ee.MatricesWeightsKind),i.numBoneInfluencers>4&&(a.push(ee.MatricesIndicesExtraKind),a.push(ee.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),i.numBoneInfluencers>0&&l.addCPUSkinningFallback(0,i);const m=i.skeleton;m.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(m.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const c=i.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),tb(a,i,u))),t&&(s.push("#define INSTANCES"),k_(a),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const h=i.bakedVertexAnimationManager;h&&h.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&a.push("bakedVertexAnimationSettingsInstanced"));const d=e._getDrawWrapper(void 0,!0),f=d.defines,p=s.join(` `);if(f!==p){const m=["world","mBones","boneTextureWidth","viewProjection","diffuseMatrix","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],_=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];d.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",{attributes:a,uniformsNames:m,uniformBuffersNames:[],samplers:_,defines:p,fallbacks:l,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u}},i.getScene().getEngine()),p)}return d.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 vn("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=be.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=be.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const n=this.getCamera();n?n.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=l=>{var m;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 g=f.getCaps().instancedArrays&&(p.visibleInstances[l._id]!==null||c.hasThinInstances);if(this._isReady(l,g)){const _=(m=u._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:m[f.currentRenderPassId];let y=l._getDrawWrapper();if(c===this.mesh&&!y&&(y=h._getDrawWrapper()),!y)return;const v=y.effect;if(f.enableEffect(y),g||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.needAlphaTesting()){const b=h.getAlphaTestTexture();b&&(v.setTexture("diffuseSampler",b),v.setMatrix("diffuseMatrix",b.getTextureMatrix()))}rc(c,v),Np(c,v),c.morphTargetManager&&c.morphTargetManager.isUsingTextureForTargets&&c.morphTargetManager._bind(v);const x=l.getMesh().bakedVertexAnimationManager;x&&x.isEnabled&&x.bind(v,g)}g&&c.hasThinInstances&&v.setMatrix("world",u.getWorldMatrix()),c._processRendering(u,l,v,tt.TriangleFillMode,p,g,(x,b)=>{x||v.setMatrix("world",b)})}};let a;const o=new at(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;fg._alphaIndex>m._alphaIndex?1:g._alphaIndexm._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)}):ge.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=ei.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,n){return ot.Parse(()=>new _D(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,n)}}V([Q()],_D.prototype,"ridge",void 0);V([Q()],_D.prototype,"valley",void 0);xe("BABYLON.ScreenSpaceCurvaturePostProcess",_D);const YYe="postprocessVertexShader",QYe=`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 } `;me.ShadersStoreWGSL[YYe]=QYe;const ZYe={name:YYe,shader:QYe},WIt=Object.freeze(Object.defineProperty({__proto__:null,postprocessVertexShaderWGSL:ZYe},Symbol.toStringTag,{value:"Module"})),KIt="kernelBlurVaryingDeclaration",HIt="varying vec2 sampleCoord{X};";me.IncludesShadersStore[KIt]=HIt;const jIt="kernelBlurFragment",$It=`#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 `;me.IncludesShadersStore[jIt]=$It;const XIt="kernelBlurFragment2",YIt=`#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 `;me.IncludesShadersStore[XIt]=YIt;const qYe="kernelBlurPixelShader",JYe=`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 }`;me.ShadersStore[qYe]=JYe;const eQe={name:qYe,shader:JYe},QIt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShader:eQe},Symbol.toStringTag,{value:"Module"})),ZIt="kernelBlurVertex",qIt="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";me.IncludesShadersStore[ZIt]=qIt;const tQe="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 }`;me.ShadersStore[tQe]=iQe;const rQe={name:tQe,shader:iQe},JIt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShader:rQe},Symbol.toStringTag,{value:"Module"})),ePt="kernelBlurVaryingDeclaration",tPt="varying sampleCoord{X}: vec2f;";me.IncludesShadersStoreWGSL[ePt]=tPt;const iPt="kernelBlurFragment",rPt=`#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 `;me.IncludesShadersStoreWGSL[iPt]=rPt;const nPt="kernelBlurFragment2",sPt=`#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 `;me.IncludesShadersStoreWGSL[nPt]=sPt;const nQe="kernelBlurPixelShader",sQe=`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 }`;me.ShadersStoreWGSL[nQe]=sQe;const aQe={name:nQe,shader:sQe},aPt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurPixelShaderWGSL:aQe},Symbol.toStringTag,{value:"Module"})),oPt="kernelBlurVertex",lPt="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";me.IncludesShadersStoreWGSL[oPt]=lPt;const oQe="kernelBlurVertexShader",lQe=`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 }`;me.ShadersStoreWGSL[oQe]=lQe;const cQe={name:oQe,shader:lQe},cPt=Object.freeze(Object.defineProperty({__proto__:null,kernelBlurVertexShaderWGSL:cQe},Symbol.toStringTag,{value:"Module"})),uQe="passCubePixelShader",hQe=`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 }`;me.ShadersStore[uQe]=hQe;const dQe={name:uQe,shader:hQe},uPt=Object.freeze(Object.defineProperty({__proto__:null,passCubePixelShader:dQe},Symbol.toStringTag,{value:"Module"})),fQe="passPixelShader",pQe=`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);}`;me.ShadersStoreWGSL[fQe]=pQe;const mQe={name:fQe,shader:pQe},hPt=Object.freeze(Object.defineProperty({__proto__:null,passPixelShaderWGSL:mQe},Symbol.toStringTag,{value:"Module"})),gQe="passCubePixelShader",_Qe=`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 }`;me.ShadersStoreWGSL[gQe]=_Qe;const vQe={name:gQe,shader:_Qe},dPt=Object.freeze(Object.defineProperty({__proto__:null,passCubePixelShaderWGSL:vQe},Symbol.toStringTag,{value:"Module"})),yQe="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);}}`;me.ShadersStore[yQe]=xQe;const bQe={name:yQe,shader:xQe},fPt=Object.freeze(Object.defineProperty({__proto__:null,vrDistortionCorrectionPixelShader:bQe},Symbol.toStringTag,{value:"Module"})),CQe="vrDistortionCorrectionPixelShader",AQe=`#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);}}`;me.ShadersStoreWGSL[CQe]=AQe;const SQe={name:CQe,shader:AQe},pPt=Object.freeze(Object.defineProperty({__proto__:null,vrDistortionCorrectionPixelShaderWGSL:SQe},Symbol.toStringTag,{value:"Module"})),EQe="imageProcessingPixelShader",TQe=`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;}`;me.ShadersStoreWGSL[EQe]=TQe;const MQe={name:EQe,shader:TQe},mPt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShaderWGSL:MQe},Symbol.toStringTag,{value:"Module"})),RQe="imageProcessingPixelShader",IQe=`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;}`;me.ShadersStore[RQe]=IQe;const PQe={name:RQe,shader:IQe},gPt=Object.freeze(Object.defineProperty({__proto__:null,imageProcessingPixelShader:PQe},Symbol.toStringTag,{value:"Module"})),wQe="sharpenPixelShader",DQe=`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.));}`;me.ShadersStoreWGSL[wQe]=DQe;const OQe={name:wQe,shader:DQe},_Pt=Object.freeze(Object.defineProperty({__proto__:null,sharpenPixelShaderWGSL:OQe},Symbol.toStringTag,{value:"Module"})),LQe="grainPixelShader",NQe=`#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);}`;me.ShadersStore[LQe]=NQe;const FQe={name:LQe,shader:NQe},vPt=Object.freeze(Object.defineProperty({__proto__:null,grainPixelShader:FQe},Symbol.toStringTag,{value:"Module"})),BQe="grainPixelShader",kQe=`#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);}`;me.ShadersStoreWGSL[BQe]=kQe;const UQe={name:BQe,shader:kQe},yPt=Object.freeze(Object.defineProperty({__proto__:null,grainPixelShaderWGSL:UQe},Symbol.toStringTag,{value:"Module"})),zQe="chromaticAberrationPixelShader",VQe=`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);}`;me.ShadersStoreWGSL[zQe]=VQe;const GQe={name:zQe,shader:VQe},xPt=Object.freeze(Object.defineProperty({__proto__:null,chromaticAberrationPixelShaderWGSL:GQe},Symbol.toStringTag,{value:"Module"})),WQe="depthOfFieldMergePixelShader",KQe=`#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 } `;me.ShadersStore[WQe]=KQe;const HQe={name:WQe,shader:KQe},bPt=Object.freeze(Object.defineProperty({__proto__:null,depthOfFieldMergePixelShader:HQe},Symbol.toStringTag,{value:"Module"})),jQe="depthOfFieldMergePixelShader",$Qe=`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 } `;me.ShadersStoreWGSL[jQe]=$Qe;const XQe={name:jQe,shader:$Qe},CPt=Object.freeze(Object.defineProperty({__proto__:null,depthOfFieldMergePixelShaderWGSL:XQe},Symbol.toStringTag,{value:"Module"})),YQe="circleOfConfusionPixelShader",QQe=`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);} `;me.ShadersStore[YQe]=QQe;const ZQe={name:YQe,shader:QQe},APt=Object.freeze(Object.defineProperty({__proto__:null,circleOfConfusionPixelShader:ZQe},Symbol.toStringTag,{value:"Module"})),qQe="circleOfConfusionPixelShader",JQe=`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);} `;me.ShadersStoreWGSL[qQe]=JQe;const eZe={name:qQe,shader:JQe},SPt=Object.freeze(Object.defineProperty({__proto__:null,circleOfConfusionPixelShaderWGSL:eZe},Symbol.toStringTag,{value:"Module"})),tZe="bloomMergePixelShader",iZe=`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); } `;me.ShadersStore[tZe]=iZe;const rZe={name:tZe,shader:iZe},EPt=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShader:rZe},Symbol.toStringTag,{value:"Module"})),nZe="bloomMergePixelShader",sZe=`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);} `;me.ShadersStoreWGSL[nZe]=sZe;const aZe={name:nZe,shader:sZe},TPt=Object.freeze(Object.defineProperty({__proto__:null,bloomMergePixelShaderWGSL:aZe},Symbol.toStringTag,{value:"Module"})),oZe="extractHighlightsPixelShader",lZe=`#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;}`;me.ShadersStore[oZe]=lZe;const cZe={name:oZe,shader:lZe},MPt=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShader:cZe},Symbol.toStringTag,{value:"Module"})),uZe="extractHighlightsPixelShader",hZe=`#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);}`;me.ShadersStoreWGSL[uZe]=hZe;const dZe={name:uZe,shader:hZe},RPt=Object.freeze(Object.defineProperty({__proto__:null,extractHighlightsPixelShaderWGSL:dZe},Symbol.toStringTag,{value:"Module"})),fZe="fxaaPixelShader",pZe=`#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 }`;me.ShadersStoreWGSL[CZe]=AZe;const SZe={name:CZe,shader:AZe},DPt=Object.freeze(Object.defineProperty({__proto__:null,fxaaVertexShaderWGSL:SZe},Symbol.toStringTag,{value:"Module"})),EZe="blackAndWhitePixelShader",TZe=`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);}`;me.ShadersStore[EZe]=TZe;const MZe={name:EZe,shader:TZe},OPt=Object.freeze(Object.defineProperty({__proto__:null,blackAndWhitePixelShader:MZe},Symbol.toStringTag,{value:"Module"})),RZe="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);}`;me.ShadersStoreWGSL[RZe]=IZe;const PZe={name:RZe,shader:IZe},LPt=Object.freeze(Object.defineProperty({__proto__:null,blackAndWhitePixelShaderWGSL:PZe},Symbol.toStringTag,{value:"Module"})),wZe="anaglyphPixelShader",DZe=`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);}`;me.ShadersStore[wZe]=DZe;const OZe={name:wZe,shader:DZe},NPt=Object.freeze(Object.defineProperty({__proto__:null,anaglyphPixelShader:OZe},Symbol.toStringTag,{value:"Module"})),LZe="anaglyphPixelShader",NZe=`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);}`;me.ShadersStoreWGSL[LZe]=NZe;const FZe={name:LZe,shader:NZe},FPt=Object.freeze(Object.defineProperty({__proto__:null,anaglyphPixelShaderWGSL:FZe},Symbol.toStringTag,{value:"Module"})),BZe="convolutionPixelShader",kZe=`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);}`;me.ShadersStore[BZe]=kZe;const UZe={name:BZe,shader:kZe},BPt=Object.freeze(Object.defineProperty({__proto__:null,convolutionPixelShader:UZe},Symbol.toStringTag,{value:"Module"})),zZe="convolutionPixelShader",VZe=`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);}`;me.ShadersStoreWGSL[zZe]=VZe;const GZe={name:zZe,shader:VZe},kPt=Object.freeze(Object.defineProperty({__proto__:null,convolutionPixelShaderWGSL:GZe},Symbol.toStringTag,{value:"Module"})),WZe="colorCorrectionPixelShader",KZe=`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);}`;me.ShadersStore[WZe]=KZe;const HZe={name:WZe,shader:KZe},UPt=Object.freeze(Object.defineProperty({__proto__:null,colorCorrectionPixelShader:HZe},Symbol.toStringTag,{value:"Module"})),jZe="colorCorrectionPixelShader",$Ze=`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);}`;me.ShadersStoreWGSL[jZe]=$Ze;const XZe={name:jZe,shader:$Ze},zPt=Object.freeze(Object.defineProperty({__proto__:null,colorCorrectionPixelShaderWGSL:XZe},Symbol.toStringTag,{value:"Module"})),YZe="motionBlurPixelShader",QZe=`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 } `;me.ShadersStore[YZe]=QZe;const ZZe={name:YZe,shader:QZe},VPt=Object.freeze(Object.defineProperty({__proto__:null,motionBlurPixelShader:ZZe},Symbol.toStringTag,{value:"Module"})),qZe="motionBlurPixelShader",JZe=`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 } `;me.ShadersStoreWGSL[qZe]=JZe;const eqe={name:qZe,shader:JZe},GPt=Object.freeze(Object.defineProperty({__proto__:null,motionBlurPixelShaderWGSL:eqe},Symbol.toStringTag,{value:"Module"})),tqe="filterPixelShader",iqe=`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);}`;me.ShadersStore[tqe]=iqe;const rqe={name:tqe,shader:iqe},WPt=Object.freeze(Object.defineProperty({__proto__:null,filterPixelShader:rqe},Symbol.toStringTag,{value:"Module"})),nqe="filterPixelShader",sqe=`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);}`;me.ShadersStoreWGSL[nqe]=sqe;const aqe={name:nqe,shader:sqe},KPt=Object.freeze(Object.defineProperty({__proto__:null,filterPixelShaderWGSL:aqe},Symbol.toStringTag,{value:"Module"})),oqe="highlightsPixelShader",lqe=`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); }`;me.ShadersStore[oqe]=lqe;const cqe={name:oqe,shader:lqe},HPt=Object.freeze(Object.defineProperty({__proto__:null,highlightsPixelShader:cqe},Symbol.toStringTag,{value:"Module"})),uqe="highlightsPixelShader",hqe=`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); }`;me.ShadersStoreWGSL[uqe]=hqe;const dqe={name:uqe,shader:hqe},jPt=Object.freeze(Object.defineProperty({__proto__:null,highlightsPixelShaderWGSL:dqe},Symbol.toStringTag,{value:"Module"})),fqe="displayPassPixelShader",pqe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(passSampler,vUV);}`;me.ShadersStore[fqe]=pqe;const mqe={name:fqe,shader:pqe},$Pt=Object.freeze(Object.defineProperty({__proto__:null,displayPassPixelShader:mqe},Symbol.toStringTag,{value:"Module"})),gqe="displayPassPixelShader",_qe=`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);}`;me.ShadersStoreWGSL[gqe]=_qe;const vqe={name:gqe,shader:_qe},XPt=Object.freeze(Object.defineProperty({__proto__:null,displayPassPixelShaderWGSL:vqe},Symbol.toStringTag,{value:"Module"})),yqe="tonemapPixelShader",xqe=`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);}`;me.ShadersStore[yqe]=xqe;const bqe={name:yqe,shader:xqe},YPt=Object.freeze(Object.defineProperty({__proto__:null,tonemapPixelShader:bqe},Symbol.toStringTag,{value:"Module"})),Cqe="tonemapPixelShader",Aqe=`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);}`;me.ShadersStoreWGSL[Cqe]=Aqe;const Sqe={name:Cqe,shader:Aqe},QPt=Object.freeze(Object.defineProperty({__proto__:null,tonemapPixelShaderWGSL:Sqe},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(Ut.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(r){this._forceShowBoundingBoxes=r,r&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Ut.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new Eqe(this)),this._boundingBoxRenderer};Object.defineProperty(vr.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(r){this._showBoundingBox=r,r&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class Eqe{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=bt.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Pe(1,1,1),this.backColor=new Pe(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new Ce,this.onAfterBoxRenderingObservable=new Ce,this.onResourcesReadyObservable=new Ce,this.enabled=!0,this._shaderLanguage=0,this.renderList=new Go(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 Ci(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Ci(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(bt.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(bt.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(bt.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(bt.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 ua("colorShader",this.scene,"boundingBoxRenderer",{attributes:[ee.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([je(()=>Promise.resolve().then(()=>SRe),void 0),je(()=>Promise.resolve().then(()=>ARe),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>CRe),void 0),je(()=>Promise.resolve().then(()=>bRe),void 0)])}},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new ua("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[ee.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([je(()=>Promise.resolve().then(()=>SRe),void 0),je(()=>Promise.resolve().then(()=>ARe),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>CRe),void 0),je(()=>Promise.resolve().then(()=>bRe),void 0)])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=lee({size:1});this._vertexBuffers[ee.PositionKind]=new ee(e,t.positions,ee.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[ee.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 n=0;n{let e=r._getComponent(bt.NAME_DEPTHRENDERER);e||(e=new Tqe(r),r._addComponent(e))};const ZPt="oitFinalPixelShader",qPt=`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 );}`;me.ShadersStore[ZPt]=qPt;const JPt="oitBackBlendPixelShader",e5t=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { discard;}}`;me.ShadersStore[JPt]=e5t;class t5t{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class p_{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 Go(10),this._excludedSubMeshes=new Go(10),this._excludedMeshes=[],this._colorCache=[new at(p_._DEPTH_CLEAR_VALUE,p_._DEPTH_CLEAR_VALUE,0,0),new at(-p_._MIN_DEPTH,p_._MAX_DEPTH,0,0),new at(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){ge.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i{t===1?await Promise.all([je(()=>Promise.resolve().then(()=>eDt),void 0),je(()=>Promise.resolve().then(()=>Jwt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>qwt),void 0),je(()=>Promise.resolve().then(()=>$wt),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,n=!0,s){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 Go(32),this._shaderLanguage=0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=s??null,this._epsilon=t;const a=this._source.getScene().getEngine();a.isWebGPU&&(this._drawWrapper=new pl(a),this._shaderLanguage=1),this._prepareRessources(),n&&((s==null?void 0:s.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=AV._GetShader(this._source.getScene(),this._shaderLanguage))}_rebuild(){let e=this._buffers[ee.PositionKind];e&&e._rebuild(),e=this._buffers[ee.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[ee.PositionKind];e&&(e.dispose(),this._buffers[ee.PositionKind]=null),e=this._buffers[ee.NormalKind],e&&(e.dispose(),this._buffers[ee.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,n,s){return e===i&&t===n||e===n&&t===i?0:e===n&&t===s||e===s&&t===n?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,n,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(n,1e-10)||e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(n,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(n,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,n,s){let a;t===void 0?a=!0:a=O.Dot(i[e],i[t]){w>=0&&P.push(w);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 E=0;E<3;++E)E===a?e[E].sort((P,w)=>P[1]w[1]?1:0):e[E].sort((P,w)=>P[1]>w[1]?-1:P[1]=a+1;--E)s(e[E%3],l,E!==a+2?n[i[t+(E+1)%3]]:-1);const u=l.length,h=0,d=0;i.push(n[i[t+a]],o[0],l[0]),i.push(n[i[t+(a+1)%3]],l[u-1],o[c-1]);const f=c<=u,p=f?c:u,g=f?u:c,m=f?c-1:u-1,_=f?0:1;let y=c+u-2,v=f?h:d,x=f?d:h;const b=f?o:l,C=f?l:o;let A=0;for(;y-- >0;){_?i.push(b[v],C[x]):i.push(C[x],b[v]),A+=p;let E;A>=g&&vv){const A=y;y=v,v=A}const b=y+"_"+v,C=o[b];C?C.done||(O.Dot(m,C.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,n=i||this._source.hasThinInstances;let s=0;if(n)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(s=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[s]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),n.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(n)}_resetLayout(){for(let e=0;el!=null),this._scene.autoClear=!0;const n=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!n&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),a=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||n,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),a?o=a:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),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;en!=null),t)){for(let n=0;n=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw Ji("PrePassRendererSceneComponent")};hc.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"},{purpose:8,type:0,format:5,name:"prePass_WorldNormal"},{purpose:9,type:2,format:5,name:"prePass_LocalPosition"},{purpose:10,type:1,format:6,name:"prePass_NdcDepth"},{purpose:11,type:2,format:5,name:"prePass_VelocityLinear"}];const n5t="voxelGridPixelShader",s5t=`precision highp float;layout(location=0) out highp float glFragData[MAX_DRAW_BUFFERS];varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;if (normPos.zfarPlane) {discard;} glFragData[0]=normPos.z=nearPlane+stepSize && normPos.z=nearPlane+2.0*stepSize && normPos.z=nearPlane+3.0*stepSize && normPos.z4 glFragData[4]=normPos.z>=nearPlane+4.0*stepSize && normPos.z=nearPlane+5.0*stepSize && normPos.z=nearPlane+6.0*stepSize && normPos.z=nearPlane+7.0*stepSize && normPos.zsize.z-1 ? true : false;sampleIndex=clamp(sampleIndex,0,size.z-1);ivec2 samplePosInt=ivec2(samplePos.xy*vec2(size.xy));vec3 voxel=texelFetch(voxelTexture, ivec3(samplePosInt.x,samplePosInt.y,sampleIndex), int(mipNumber)) .rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {if (outBounds) {voxel=vec3(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;} voxel.r+=mip_separator;} glFragColor.rgb=mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel;glFragColor.a=1.0;}}`;me.ShadersStore[u5t]=h5t;const d5t="voxelSlabDebugVertexShader",f5t="attribute vec3 position;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 cameraViewMatrix;uniform mat4 projection;uniform mat4 viewMatrix;void main(void) {vec4 worldPosition=(world*vec4(position,1.));gl_Position=projection*cameraViewMatrix*worldPosition;vNormalizedPosition=(viewMatrix*invWorldScale*worldPosition).rgb;vNormalizedPosition.xyz=vNormalizedPosition.xyz*vec3(0.5)+vec3(0.5);}";me.ShadersStore[d5t]=f5t;const p5t="voxelSlabDebugPixelShader",m5t=`precision highp float;varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;float chunkSize=stepSize*float(MAX_DRAW_BUFFERS);float numChunks=1.0/chunkSize;float positionInChunk=fract(normPos.z/chunkSize);float slab=floor(positionInChunk*float(MAX_DRAW_BUFFERS)) / float(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 || normPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {gl_FragColor=vec4(0.0,0.0,0.0,0.0);} else {gl_FragColor=vec4(slab,0.0,0.0,0.75);}}`;me.ShadersStore[p5t]=m5t;const g5t="combineVoxelGridsPixelShader",_5t="precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelXaxisSampler;uniform sampler3D voxelYaxisSampler;uniform sampler3D voxelZaxisSampler;uniform float layer;void main(void) {vec3 coordZ=vec3(vUV.x,vUV.y,layer);float voxelZ=texture(voxelZaxisSampler,coordZ).r;vec3 coordX=vec3(1.0-layer,vUV.y,vUV.x);float voxelX=texture(voxelXaxisSampler,coordX).r;vec3 coordY=vec3(layer,vUV.x,vUV.y);float voxelY=texture(voxelYaxisSampler,coordY).r;float voxel=(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0) ? 1.0 : 0.0;glFragColor=vec4(vec3(voxel),1.0);}";me.ShadersStore[g5t]=_5t;const v5t="generateVoxelMipPixelShader",y5t=`precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D srcMip;uniform int layerNum;void main(void) {ivec3 Coords=ivec3(2)*ivec3(gl_FragCoord.x,gl_FragCoord.y,layerNum);uint tex = uint(texelFetch(srcMip,Coords+ivec3(0,0,0),0).x>0.0f ? 1u : 0u) << 0u | uint(texelFetch(srcMip,Coords+ivec3(1,0,0),0).x>0.0f ? 1u : 0u) << 1u | uint(texelFetch(srcMip,Coords+ivec3(0,1,0),0).x>0.0f ? 1u : 0u) << 2u | uint(texelFetch(srcMip,Coords+ivec3(1,1,0),0).x>0.0f ? 1u : 0u) << 3u | uint(texelFetch(srcMip,Coords+ivec3(0,0,1),0).x>0.0f ? 1u : 0u) << 4u | uint(texelFetch(srcMip,Coords+ivec3(1,0,1),0).x>0.0f ? 1u : 0u) << 5u | uint(texelFetch(srcMip,Coords+ivec3(0,1,1),0).x>0.0f ? 1u : 0u) << 6u | uint(texelFetch(srcMip,Coords+ivec3(1,1,1),0).x>0.0f ? 1u : 0u) << 7u;glFragColor.rgb=vec3(float(tex)/255.0f,0.0f,0.0f);glFragColor.a=1.0;}`;me.ShadersStore[v5t]=y5t;const x5t="copyTexture3DLayerToTexturePixelShader",b5t=`precision highp sampler3D;uniform sampler3D textureSampler;uniform int layerNum;varying vec2 vUV;void main(void) {vec3 coord=vec3(0.0,0.0,float(layerNum));coord.xy=vec2(vUV.x,vUV.y)*vec2(textureSize(textureSampler,0).xy);vec3 color=texelFetch(textureSampler,ivec3(coord),0).rgb;gl_FragColor=vec4(color,1);} `;me.ShadersStore[x5t]=b5t;class C5t{getVoxelGrid(){return this._triPlanarVoxelization?this._voxelGridRT:this._voxelGridZaxis}getDebugPassPP(){return this._voxelDebugPass||this._createDebugPass(),this._voxelDebugPass}get triPlanarVoxelization(){return this._triPlanarVoxelization}set triPlanarVoxelization(e){this._triPlanarVoxelization!==e&&(this._triPlanarVoxelization=e,this._disposeVoxelTextures(),this._createTextures(),this._renderPipeline.updateVoxelization())}setWorldScaleMatrix(e){this._invWorldScaleMatrix=e}isVoxelizationInProgress(){return this._voxelizationInProgress}get voxelResolutionExp(){return this._voxelResolutionExp}set voxelResolutionExp(e){this._voxelResolutionExp===e&&this._voxelGridZaxis||(this._voxelResolutionExp=Math.round(Math.min(Math.max(e,3),9)),this._voxelResolution=Math.pow(2,this._voxelResolutionExp),this._disposeVoxelTextures(),this._createTextures())}set voxelDebugAxis(e){this._voxelDebugAxis=e}get voxelDebugAxis(){return this._voxelDebugAxis}setDebugDisplayParams(e,t,i,n){this._debugSizeParams.set(e,t,i,n)}setDebugMipNumber(e){this._debugMipNumber=e}get debugPassName(){return this._debugPassName}get voxelDebugEnabled(){return this._voxelDebugEnabled}set voxelDebugEnabled(e){this._voxelDebugEnabled!==e&&(this._voxelDebugEnabled=e,e?(this._voxelSlabDebugRT=new vn("voxelSlabDebug",{ratio:1},this._scene,{generateDepthBuffer:!0,generateMipMaps:!1,type:0,format:6,samplingMode:1}),this._voxelSlabDebugRT.noPrePassRenderer=!0):this._voxelSlabDebugRT&&this._removeVoxelRTs([this._voxelSlabDebugRT]))}_createDebugPass(){if(!this._voxelDebugPass){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:6,textureType:0,samplingMode:1,uniforms:["sizeParams","mipNumber"],samplers:["voxelTexture","voxelSlabTexture"],engine:this._engine,reusable:!1};this._voxelDebugPass=new ii(this.debugPassName,this._isVoxelGrid3D?"voxelGrid3dDebug":"voxelGrid2dArrayDebug",e),this._voxelDebugPass.onApplyObservable.add(t=>{this._voxelDebugAxis===0?t.setTexture("voxelTexture",this._voxelGridXaxis):this._voxelDebugAxis===1?t.setTexture("voxelTexture",this._voxelGridYaxis):this._voxelDebugAxis===2?t.setTexture("voxelTexture",this._voxelGridZaxis):t.setTexture("voxelTexture",this.getVoxelGrid()),t.setTexture("voxelSlabTexture",this._voxelSlabDebugRT),t.setVector4("sizeParams",this._debugSizeParams),t.setFloat("mipNumber",this._debugMipNumber)})}}constructor(e,t,i=6,n=!0){this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[],this._isVoxelGrid3D=!0,this._renderTargets=[],this._triPlanarVoxelization=!0,this._voxelizationInProgress=!1,this._voxelResolution=64,this._voxelResolutionExp=6,this.onReadyObservable=new Ce,this._mipArray=[],this._voxelDebugEnabled=!1,this._voxelDebugAxis=-1,this._debugSizeParams=new It(0,0,0,0),this._debugMipNumber=0,this._debugPassName="Voxelization Debug Pass",this._scene=e,this._engine=e.getEngine(),this._triPlanarVoxelization=n,this._renderPipeline=t,this._engine.getCaps().drawBuffersExtension||ge.Error("Can't do voxel rendering without the draw buffers extension."),this._engine instanceof gr?this._maxDrawBuffers=8:this._maxDrawBuffers=this._engine._gl.getParameter(this._engine._gl.MAX_DRAW_BUFFERS),this._copyMipEffectRenderer=new aD(this._engine),this._copyMipEffectWrapper=new _g({engine:this._engine,fragmentShader:"copyTexture3DLayerToTexture",useShaderStore:!0,uniformNames:["layerNum"],samplerNames:["textureSampler"]}),this.voxelResolutionExp=i}_generateMipMaps(){const e=Math.ceil(Math.log2(this._voxelResolution));for(let t=1;t>s,o={width:a,height:a,depth:a};this._mipArray[s-1]=new Bu("voxelMip"+s,o,"generateVoxelMip",this._scene,t);const l=this._mipArray[s-1];l._noMipmap=!0,l.refreshRate=0,l.autoClear=!1,l.wrapU=be.CLAMP_ADDRESSMODE,l.wrapV=be.CLAMP_ADDRESSMODE,l.setTexture("srcMip",s>1?this._mipArray[s-2]:this.getVoxelGrid()),l.setInt("layerNum",0)}}_createVoxelMRTs(e,t,i){t.wrapU=be.CLAMP_ADDRESSMODE,t.wrapV=be.CLAMP_ADDRESSMODE,t.noPrePassRenderer=!0;const n=[],s=new Array(this._maxDrawBuffers).fill(this._isVoxelGrid3D?32879:35866);for(let a=0;aa*this._maxDrawBuffers+h);let l=new Array(this._maxDrawBuffers).fill("");l=l.map((u,h)=>"voxel_grid_"+e+(a*this._maxDrawBuffers+h));const c=new r_("mrt_"+e+a,{width:this._voxelResolution,height:this._voxelResolution,depth:this._isVoxelGrid3D?this._voxelResolution:void 0},this._maxDrawBuffers,this._scene,{types:new Array(this._maxDrawBuffers).fill(0),samplingModes:new Array(this._maxDrawBuffers).fill(3),generateMipMaps:!1,targetTypes:s,formats:new Array(this._maxDrawBuffers).fill(6),faceIndex:new Array(this._maxDrawBuffers).fill(0),layerIndex:o,layerCounts:new Array(this._maxDrawBuffers).fill(this._voxelResolution),generateDepthBuffer:!1,generateStencilBuffer:!1},l);c.clearColor=new at(0,0,0,1),c.noPrePassRenderer=!0;for(let u=0;u{s.dispose()}),this._mipArray=[],this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[]}_createVoxelMaterial(){const e=new ua("voxelization",this._scene,"voxelGrid",{uniforms:["world","viewMatrix","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers]});return e.cullBackFaces=!1,e.backFaceCulling=!1,e.depthFunction=Vt.ALWAYS,e}isReady(){return!(!this.getVoxelGrid().isReady()||this._voxelizationInProgress)}_stopVoxelization(){this._removeVoxelRTs(this._voxelMrtsXaxis),this._removeVoxelRTs(this._voxelMrtsYaxis),this._removeVoxelRTs(this._voxelMrtsZaxis)}_removeVoxelRTs(e){const t=this._renderTargets.findIndex(i=>i===e[0]);if(t>=0)this._renderTargets.splice(t,e.length);else{const i=this._scene.customRenderTargets.findIndex(n=>n===e[0]);i>=0&&this._scene.customRenderTargets.splice(i,e.length)}}updateVoxelGrid(e){this._stopVoxelization(),this._voxelizationInProgress=!0,this._triPlanarVoxelization?(this._addRTsForRender(this._voxelMrtsXaxis,e,0),this._addRTsForRender(this._voxelMrtsYaxis,e,1),this._addRTsForRender(this._voxelMrtsZaxis,e,2)):this._addRTsForRender(this._voxelMrtsZaxis,e,2),this._voxelDebugEnabled&&(this._removeVoxelRTs([this._voxelSlabDebugRT]),this._addRTsForRender([this._voxelSlabDebugRT],[],this._voxelDebugAxis,1,!0)),this.boundVoxelGridRenderFn=this._renderVoxelGrid.bind(this),this._scene.onAfterRenderTargetsRenderObservable.add(this.boundVoxelGridRenderFn)}_renderVoxelGrid(){this._voxelizationInProgress&&this._renderTargets.every(t=>t.isReadyForRendering())&&(this._scene.prePassRenderer._setEnabled(!1),this._renderTargets.forEach(t=>{t.render()}),this._stopVoxelization(),this._triPlanarVoxelization&&(this._voxelGridRT._generateMipMaps=!1,this._voxelGridRT.render()),this._generateMipMaps(),this._copyMipMaps(),this._voxelizationInProgress=!1,this._scene.onAfterRenderTargetsRenderObservable.removeCallback(this.boundVoxelGridRenderFn),this.onReadyObservable.notifyObservers(),this._scene.prePassRenderer._setEnabled(!0))}_addRTsForRender(e,t,i,n=0,s=!1){const a=1/this._computeNumberOfSlabs(),o=this._scene.meshes;e.forEach((l,c)=>{l.renderList=[];const u=c*a,h=(c+1)*a,d=a/this._maxDrawBuffers;let f;n===0?f=this._createVoxelMaterial():(f=new ua("voxelSlabDebug",this._scene,"voxelSlabDebug",{uniforms:["world","viewMatrix","cameraViewMatrix","projection","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers]}),this._scene.onBeforeRenderObservable.add(()=>{f.setMatrix("projection",this._scene.activeCamera.getProjectionMatrix()),f.setMatrix("cameraViewMatrix",this._scene.activeCamera.getViewMatrix())}));const p=new O(0,0,0);let g=new O(0,0,1);i===0?g=new O(1,0,0):i===1&&(g=new O(0,1,0));let m=new O(0,1,0);i===1&&(m=new O(1,0,0)),f.setMatrix("viewMatrix",pe.LookAtLH(p,g,m)),f.setMatrix("invWorldScale",this._invWorldScaleMatrix),f.setFloat("nearPlane",u),f.setFloat("farPlane",h),f.setFloat("stepSize",d),o.forEach(_=>{var y;_ instanceof Re&&_.material&&t.indexOf(_.uniqueId)===-1&&((y=l.renderList)==null||y.push(_),l.setMaterialForRendering(_,f))})}),s?this._scene.customRenderTargets=this._scene.customRenderTargets.concat(e):this._renderTargets=this._renderTargets.concat(e)}resize(){var e;(e=this._voxelSlabDebugRT)==null||e.resize({width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight()})}dispose(){this._disposeVoxelTextures(),this._voxelSlabDebugRT&&(this._removeVoxelRTs([this._voxelSlabDebugRT]),this._voxelSlabDebugRT.dispose()),this._voxelDebugPass&&this._voxelDebugPass.dispose()}}const A5t="iblShadowVoxelTracingPixelShader",S5t=`precision highp sampler2D;precision highp sampler3D; #define PI 3.1415927 varying vec2 vUV; #define DISABLE_UNIFORMITY_ANALYSIS uniform sampler2D depthSampler;uniform sampler2D linearDepthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D worldPositionSampler;uniform sampler2D blueNoiseSampler;uniform sampler2D icdfxSampler;uniform sampler2D icdfySampler;uniform sampler3D voxelGridSampler;uniform vec4 shadowParameters; #define SHADOWdirs shadowParameters.x #define SHADOWframe shadowParameters.y #define SHADOWdownscale shadowParameters.z #define SHADOWenvRot shadowParameters.w uniform vec4 offsetDataParameters; #define PixelOffset offsetDataParameters.xy #define highestMipLevel offsetDataParameters.z uniform vec4 sssParameters; #define SSSsamples sssParameters.x #define SSSstride sssParameters.y #define SSSmaxDistance sssParameters.z #define SSSthickness sssParameters.w uniform vec4 shadowOpacity;uniform mat4 projMtx;uniform mat4 viewMtx;uniform mat4 invProjMtx;uniform mat4 invViewMtx;uniform mat4 wsNormalizationMtx;uniform mat4 invVPMtx; #define PI 3.1415927 #define GOLD 0.618034 struct AABB3f {vec3 m_min;vec3 m_max;};struct Ray {vec3 orig;vec3 dir;vec3 dir_rcp;float t_min;float t_max;};Ray make_ray(const vec3 origin,const vec3 direction,const float tmin, const float tmax) {Ray ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;} bool ray_box_intersection(const in AABB3f aabb,const in Ray ray, out float distance_near,out float distance_far) {vec3 tbot=ray.dir_rcp*(aabb.m_min-ray.orig);vec3 ttop=ray.dir_rcp*(aabb.m_max-ray.orig);vec3 tmin=min(ttop,tbot);vec3 tmax=max(ttop,tbot);distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return distance_near<=distance_far;} #if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION struct VoxelMarchDiagnosticInfo {float heat;ivec3 voxel_intersect_coords;}; #endif uint hash(uint i) {i ^= i>>16u;i*=0x7FEB352Du;i ^= i>>15u;i*=0x846CA68Bu;i ^= i>>16u;return i;} float uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;} vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;} vec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u), uint2float(rstate*2447445414u));} float goldenSequence(const uint rstate) {return uint2float(rstate*2654435769u);} float distanceSquared(vec2 a,vec2 b) {vec2 diff=a-b;return dot(diff,diff);} void genTB(const vec3 N,out vec3 T,out vec3 B) {float s=N.z<0.0 ? -1.0 : 1.0;float a=-1.0/(s+N.z);float b=N.x*N.y*a;T=vec3(1.0+s*N.x*N.x*a,s*b,-s*N.x);B=vec3(b,s+N.y*N.y*a,-N.y);} int stack[24]; #define PUSH(i) stack[stackLevel++]=i; #define POP() stack[--stackLevel] #ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION bool anyHitVoxels(const Ray ray_vs, out VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) { #else bool anyHitVoxels(const Ray ray_vs) { #endif vec3 invD=ray_vs.dir_rcp;vec3 D=ray_vs.dir;vec3 O=ray_vs.orig;ivec3 negD=ivec3(lessThan(D,vec3(0,0,0)));int voxel0=negD.x | negD.y<<1 | negD.z<<2;vec3 t0=-O*invD,t1=(vec3(1.0)-O)*invD;int maxLod=int(highestMipLevel);int stackLevel=0; #if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION uint steps=0u; #endif PUSH(maxLod<<24);while (stackLevel>0) {int elem=POP();ivec4 Coords = ivec4(elem & 0xFF,elem>>8 & 0xFF,elem>>16 & 0xFF,elem>>24);if (Coords.w==0) { #if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION voxel_march_diagnostic_info.heat=float(steps)/24.0; #endif return true;} #if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION ++steps; #endif float invRes=exp2(float(Coords.w-maxLod));vec3 bbmin=invRes*vec3(Coords.xyz+negD);vec3 bbmax=invRes*vec3(Coords.xyz-negD+ivec3(1));vec3 mint=mix(t0,t1,bbmin);vec3 maxt=mix(t0,t1,bbmax);vec3 midt=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);int nodeMask=int( round(texelFetch(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;int voxelBit=voxel0;Coords.xyz=(Coords.xyz<<1)+negD;int packedCoords = Coords.x | Coords.y<<8 | Coords.z<<16 | Coords.w<<24;if (max(mint.x,max(mint.y,mint.z))0.0 ? 1.0 : -1.0;float ssSamples=SSSsamples;float ssMaxDist=SSSmaxDistance;float ssStride=SSSstride;float ssThickness=SSSthickness;float rayLength = csZDir*(csOrigin.z+ssMaxDist*csDirection.z)0.0 && stepCount0.0 ? -0.001 : -0.1;float cosNL=dot(N,L.xyz);float opacity=cosNLedge_tint_const) {vec4 VP2=VP;VP2.y*=-1.0;vec4 unormWP=invViewMtx*VP2;vec3 WP=(wsNormalizationMtx*unormWP).xyz;vec2 vxNoise = vec2(uint2float(hash(dirId*2u)),uint2float(hash(dirId*2u+1u))); #ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION VoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity, shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise, voxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat; #else opacity = max(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise)); #endif vec3 VL=(viewMtx*L).xyz;float nearPlaneZ = -projMtx[3][2]/projMtx[2][2]; float ssShadow=shadowOpacity.y * screenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ, abs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);shadowAccum+=min(1.0-opacity,smoothstep(-0.1,0.2,cosNL));} else {shadowAccum+=min(1.0-opacity,smoothstep(-0.1,0.2,cosNL));} noise.z=fract(noise.z+GOLD);} #ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION gl_FragColor = vec4(shadowAccum/float(nbDirs),heat/float(nbDirs),0.0,1.0); #else gl_FragColor=vec4(shadowAccum/float(nbDirs),0.0,0.0,1.0); #endif }`;me.ShadersStore[A5t]=S5t;const E5t="iblShadowDebugPixelShader",T5t=`#ifdef GL_ES precision mediump float; #endif varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D debugSampler;uniform vec4 sizeParams; #define offsetX sizeParams.x #define offsetY sizeParams.y #define widthScale sizeParams.z #define heightScale sizeParams.w void main(void) {vec2 uv = vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 debugColour=texture2D(debugSampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {gl_FragColor.rgb=mix(debugColour.rgb,background.rgb,0.0);gl_FragColor.a=1.0;}}`;me.ShadersStore[E5t]=T5t;class M5t{get voxelShadowOpacity(){return this._voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelShadowOpacity=e}get ssShadowOpacity(){return this._ssShadowOpacity}set ssShadowOpacity(e){this._ssShadowOpacity=e}get sssSamples(){return this._sssSamples}set sssSamples(e){this._sssSamples=e}get sssStride(){return this._sssStride}set sssStride(e){this._sssStride=e}get sssMaxDist(){return this._sssMaxDist}set sssMaxDist(e){this._sssMaxDist=e}get sssThickness(){return this._sssThickness}set sssThickness(e){this._sssThickness=e}get sampleDirections(){return this._sampleDirections}set sampleDirections(e){this._sampleDirections=e}get envRotation(){return this._envRotation}set envRotation(e){this._envRotation=e}getPassPP(){return this._outputPP}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScaleMatrix(e){this._invWorldScaleMatrix=e}setDebugDisplayParams(e,t,i,n){this._debugSizeParams.set(e,t,i,n)}_createDebugPass(){if(!this._debugPassPP){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1};this._debugPassPP=new ii(this.debugPassName,"iblShadowDebug",e),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add(t=>{t.setTextureFromPostProcessOutput("debugSampler",this._outputPP),t.setVector4("sizeParams",this._debugSizeParams)})}}constructor(e,t){this._voxelShadowOpacity=1,this._sssSamples=16,this._sssStride=8,this._sssMaxDist=.05,this._sssThickness=.01,this._ssShadowOpacity=1,this._cameraInvView=pe.Identity(),this._cameraInvProj=pe.Identity(),this._invWorldScaleMatrix=pe.Identity(),this._frameId=0,this._sampleDirections=4,this.debugEnabled=!1,this._debugPassName="Voxel Tracing Debug Pass",this._envRotation=-Math.PI/2,this._downscale=1,this._debugVoxelMarchEnabled=!1,this._debugSizeParams=new It(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){let e="";this._debugVoxelMarchEnabled&&(e+=`#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u `);const t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:7,textureType:0,samplingMode:1,uniforms:["viewMtx","projMtx","invProjMtx","invViewMtx","wsNormalizationMtx","shadowParameters","offsetDataParameters","sssParameters","shadowOpacity"],samplers:["voxelGridSampler","icdfySampler","icdfxSampler","blueNoiseSampler","worldNormalSampler","linearDepthSampler","depthSampler","worldPositionSampler"],defines:e,engine:this._engine,reusable:!1};this._outputPP=new ii("voxelTracingPass","iblShadowVoxelTracing",t),this._outputPP.autoClear=!1,this._outputPP.onApplyObservable.add(i=>{this._updatePostProcess(i,this._scene.activeCamera)})}_updatePostProcess(e,t){e.setMatrix("viewMtx",t.getViewMatrix()),e.setMatrix("projMtx",t.getProjectionMatrix()),t.getProjectionMatrix().invertToRef(this._cameraInvProj),t.getViewMatrix().invertToRef(this._cameraInvView),e.setMatrix("invProjMtx",this._cameraInvProj),e.setMatrix("invViewMtx",this._cameraInvView),e.setMatrix("wsNormalizationMtx",this._invWorldScaleMatrix),this._frameId++;const i=this._downscale*this._downscale,n=this._scene.useRightHandedSystem?this._envRotation:(this._envRotation+Math.PI)%(2*Math.PI);e.setVector4("shadowParameters",new It(this._sampleDirections,this._frameId/i,this._downscale,n));const s=new Ne(0,0),a=this._renderPipeline.getVoxelGridTexture(),o=Math.floor(Math.log2(a.getSize().width));e.setVector4("offsetDataParameters",new It(s.x,s.y,o,0));const l=1/this._invWorldScaleMatrix.m[0]*2,c=this._sssMaxDist*l,u=this._sssThickness*l;e.setVector4("sssParameters",new It(this._sssSamples,this._sssStride,c,u)),e.setVector4("shadowOpacity",new It(this._voxelShadowOpacity,this._ssShadowOpacity,0,0)),e.setTexture("voxelGridSampler",a),e.setTexture("blueNoiseSampler",this._renderPipeline._noiseTexture),e.setTexture("icdfySampler",this._renderPipeline.getIcdfyTexture()),e.setTexture("icdfxSampler",this._renderPipeline.getIcdfxTexture()),this._debugVoxelMarchEnabled&&(e.defines=`#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u `);const h=this._scene.prePassRenderer;if(h){const d=h.getIndex(8),f=h.getIndex(5),p=h.getIndex(10),g=h.getIndex(1);d>=0&&e.setTexture("worldNormalSampler",h.getRenderTarget().textures[d]),f>=0&&e.setTexture("linearDepthSampler",h.getRenderTarget().textures[f]),p>=0&&e.setTexture("depthSampler",h.getRenderTarget().textures[p]),g>=0&&e.setTexture("worldPositionSampler",h.getRenderTarget().textures[g])}}isReady(){return this._outputPP.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())&&this._renderPipeline.getIcdfyTexture().isReady()&&this._renderPipeline.getIcdfxTexture().isReady()&&this._renderPipeline.getVoxelGridTexture().isReady()}dispose(){this._outputPP.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}const R5t="iblShadowGBufferDebugPixelShader",I5t=`#ifdef GL_ES precision mediump float; #endif varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D prePass_NdcDepth;uniform sampler2D prePass_WorldNormal;uniform sampler2D prePass_Position;uniform sampler2D prePass_LocalPosition;uniform sampler2D prePass_VelocityLinear;uniform vec4 sizeParams;uniform float maxDepth; #define offsetX sizeParams.x #define offsetY sizeParams.y #define widthScale sizeParams.z #define heightScale sizeParams.w void main(void) {vec2 uv = vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 backgroundColour=texture2D(textureSampler,vUV).rgba;vec4 depth=texture2D(prePass_NdcDepth,vUV);vec4 worldNormal=texture2D(prePass_WorldNormal,vUV);vec4 worldPosition=texture2D(prePass_Position,vUV);vec4 localPosition=texture2D(prePass_LocalPosition,vUV);vec4 velocityLinear=texture2D(prePass_VelocityLinear,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=backgroundColour;} else {gl_FragColor.a=1.0;if (uv.x<=0.2) { gl_FragColor.rgb=depth.rgb;gl_FragColor.a=1.0;} else if (uv.x<=0.4) {velocityLinear.rg=velocityLinear.rg*0.5+0.5;gl_FragColor.rgb=velocityLinear.rgb;} else if (uv.x<=0.6) {gl_FragColor.rgb=worldPosition.rgb;} else if (uv.x<=0.8) {gl_FragColor.rgb=localPosition.rgb;} else {gl_FragColor.rgb=worldNormal.rgb;}}}`;me.ShadersStore[R5t]=I5t;const P5t="iblShadowsCombinePixelShader",w5t=`precision highp float;varying vec2 vUV;uniform sampler2D sceneTexture;uniform sampler2D textureSampler;uniform float shadowOpacity;void main(void) {vec3 color=texture(sceneTexture,vUV).rgb;vec3 shadow=texture(textureSampler,vUV).rgb;float shadowValue=mix(1.0,shadow.x,shadowOpacity);gl_FragColor=vec4(color*shadowValue,1.0);}`;me.ShadersStore[P5t]=w5t;const D5t="iblShadowsImportanceSamplingDebugPixelShader",O5t=`precision highp samplerCube; #define PI 3.1415927 varying vec2 vUV;uniform sampler2D cdfy;uniform sampler2D icdfy;uniform sampler2D cdfx;uniform sampler2D icdfx; #ifdef IBL_USE_CUBE_MAP uniform samplerCube iblSource; #else uniform sampler2D iblSource; #endif uniform sampler2D textureSampler; #define cdfyVSize 0.4 #define cdfxVSize 0.1 #define cdfyHSize 0.5 uniform vec4 sizeParams; #define offsetX sizeParams.x #define offsetY sizeParams.y #define widthScale sizeParams.z #define heightScale sizeParams.w #ifdef IBL_USE_CUBE_MAP vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} #endif void main(void) {vec3 colour=vec3(0.0);vec2 uv = vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec3 backgroundColour=texture2D(textureSampler,vUV).rgb;const float iblStart=1.0-cdfyVSize;const float cdfyStart=1.0-2.0*cdfyVSize;const float cdfxStart=1.0-2.0*cdfyVSize-cdfxVSize;const float icdfxStart=1.0-2.0*cdfyVSize-2.0*cdfxVSize; #ifdef IBL_USE_CUBE_MAP vec3 direction=equirectangularToCubemapDirection( (uv-vec2(0.0,iblStart))*vec2(1.0,1.0/cdfyVSize));vec3 iblColour=textureCubeLodEXT(iblSource,direction,0.0).rgb; #else vec3 iblColour=texture2D(iblSource,(uv-vec2(0.0,iblStart)) * vec2(1.0,1.0/cdfyVSize)) .rgb; #endif float cdfyColour = texture2D(cdfy,(uv-vec2(0.0,cdfyStart))*vec2(2.0,1.0/cdfyVSize)) .r;float icdfyColour = texture2D(icdfy,(uv-vec2(0.5,cdfyStart))*vec2(2.0,1.0/cdfyVSize)) .r;float cdfxColour = texture2D(cdfx,(uv-vec2(0.0,cdfxStart))*vec2(1.0,1.0/cdfxVSize)) .r;float icdfxColour=texture2D(icdfx,(uv-vec2(0.0,icdfxStart)) * vec2(1.0,1.0/cdfxVSize)) .r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=0.003*cdfyColour;} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=0.00003*cdfxColour;} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;} gl_FragColor=vec4(colour,1.0);glFragColor.rgb=mix(gl_FragColor.rgb,backgroundColour,0.5);}`;me.ShadersStore[D5t]=O5t;const L5t="iblShadowsCdfxPixelShader",N5t=`precision highp sampler2D; #define PI 3.1415927 varying vec2 vUV;uniform sampler2D cdfy;void main(void) {ivec2 cdfyRes=textureSize(cdfy,0);ivec2 currentPixel=ivec2(gl_FragCoord.xy);float cdfx=0.0;for (int x=1; x<=currentPixel.x; x++) {cdfx+=texelFetch(cdfy,ivec2(x-1,cdfyRes.y-1),0).x;} gl_FragColor=vec4(vec3(cdfx),1.0);}`;me.ShadersStore[L5t]=N5t;const F5t="iblShadowsIcdfxPixelShader",B5t=`precision highp sampler2D; #define PI 3.1415927 varying vec2 vUV;uniform sampler2D cdfx;float fetchCDF(int x) {return texelFetch(cdfx,ivec2(x,0),0).x;} float bisect(int size,float targetValue) {int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDF(c)1) {int c=a+b>>1;if (fetchCDF(c,invocationId){this.onReadyObservable.notifyObservers()})}getIcdfyTexture(){return this._icdfyPT}getIcdfxTexture(){return this._icdfxPT}setDebugDisplayParams(e,t,i,n){this._debugSizeParams.set(e,t,i,n)}get debugPassName(){return this._debugPassName}getDebugPassPP(){return this._debugPass||this._createDebugPass(),this._debugPass}constructor(e){this.debugEnabled=!1,this._debugSizeParams=new It(0,0,0,0),this._debugPassName="Importance Sample Debug",this.onReadyObservable=new Ce,this._scene=e,this._engine=e.getEngine()}_createTextures(){const e=this._iblSource?this._iblSource.getSize():{width:1,height:1};this._iblSource||(this._iblSource=Vs.CreateRTexture(new Uint8Array([255]),1,1,this._scene,!1,!1,1,0),this._iblSource.name="Placeholder IBL Source"),this._iblSource.isCube&&(e.width*=4,e.height*=2);const t={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:1,samplingMode:1},i={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:2,samplingMode:1};this._cdfyPT=new Bu("cdfyTexture",{width:e.width,height:e.height+1},"iblShadowsCdfy",this._scene,t,!1,!1),this._cdfyPT.autoClear=!1,this._cdfyPT.setTexture("iblSource",this._iblSource),this._cdfyPT.setInt("iblHeight",e.height),this._iblSource.isCube&&(this._cdfyPT.defines=`#define IBL_USE_CUBE_MAP `),this._cdfyPT.refreshRate=0,this._icdfyPT=new Bu("icdfyTexture",{width:e.width,height:e.height},"iblShadowsIcdfy",this._scene,i,!1,!1),this._icdfyPT.autoClear=!1,this._icdfyPT.setTexture("cdfy",this._cdfyPT),this._icdfyPT.refreshRate=0,this._cdfxPT=new Bu("cdfxTexture",{width:e.width+1,height:1},"iblShadowsCdfx",this._scene,t,!1,!1),this._cdfxPT.autoClear=!1,this._cdfxPT.setTexture("cdfy",this._cdfyPT),this._cdfxPT.refreshRate=0,this._icdfxPT=new Bu("icdfxTexture",{width:e.width,height:1},"iblShadowsIcdfx",this._scene,i,!1,!1),this._icdfxPT.autoClear=!1,this._icdfxPT.setTexture("cdfx",this._cdfxPT),this._icdfxPT.refreshRate=0}_disposeTextures(){var e,t,i,n,s;(e=this._cdfyPT)==null||e.dispose(),(t=this._icdfyPT)==null||t.dispose(),(i=this._cdfxPT)==null||i.dispose(),(n=this._icdfxPT)==null||n.dispose(),(s=this._iblSource)==null||s.dispose()}_createDebugPass(){var i,n,s;this._debugPass&&this._debugPass.dispose();const e={width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight(),samplingMode:be.BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:0,uniforms:["sizeParams"],samplers:["cdfy","icdfy","cdfx","icdfx","iblSource"],defines:(i=this._iblSource)!=null&&i.isCube?`#define IBL_USE_CUBE_MAP `:""};this._debugPass=new ii(this._debugPassName,"iblShadowsImportanceSamplingDebug",e);const t=this._debugPass.getEffect();t&&(t.defines=(n=this._iblSource)!=null&&n.isCube?`#define IBL_USE_CUBE_MAP `:""),(s=this._iblSource)!=null&&s.isCube&&this._debugPass.updateEffect(`#define IBL_USE_CUBE_MAP `),this._debugPass.onApplyObservable.add(a=>{a.setTexture("cdfy",this._cdfyPT),a.setTexture("icdfy",this._icdfyPT),a.setTexture("cdfx",this._cdfxPT),a.setTexture("icdfx",this._icdfxPT),a.setTexture("iblSource",this._iblSource),a.setFloat4("sizeParams",this._debugSizeParams.x,this._debugSizeParams.y,this._debugSizeParams.z,this._debugSizeParams.w)})}isReady(){return this._iblSource&&this._iblSource.name!=="Placeholder IBL Source"&&this._iblSource.isReady()&&this._cdfyPT.isReady()&&this._icdfyPT.isReady()&&this._cdfxPT.isReady()&&this._icdfxPT.isReady()}dispose(){this._disposeTextures(),this._debugPass&&this._debugPass.dispose()}}const W5t="iblShadowSpatialBlurPixelShader",K5t=`precision highp sampler2D; #define PI 3.1415927 varying vec2 vUV;uniform sampler2D linearDepthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D textureSampler;uniform vec4 blurParameters; #define stridef blurParameters.x #define worldScale blurParameters.y const float weights[5]=float[5](0.0625,0.25,0.375,0.25,0.0625);const int nbWeights=5;vec2 max2(vec2 v,vec2 w) {return vec2(max(v.x,w.x),max(v.y,w.y));} void main(void) {vec2 Resolution=vec2(textureSize(linearDepthSampler,0));ivec2 PixelCoord=ivec2(vUV*Resolution);vec3 N=texelFetch(worldNormalSampler,PixelCoord,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;} float depth=-texelFetch(linearDepthSampler,PixelCoord,0).x;vec2 X=vec2(0.0);for(int y=0; y>1),y-(nbWeights>>1));vec2 T=texelFetch(textureSampler,Coords,0).xy;float ddepth=-texelFetch(linearDepthSampler,Coords,0).x-depth;vec3 dN=texelFetch(worldNormalSampler,Coords,0).xyz-N;float w=weights[x]*weights[y] * exp2(max(-1000.0/(worldScale*worldScale),-0.5) * (ddepth*ddepth) - 1e1*dot(dN,dN));X+=vec2(w*T.x,w);}} gl_FragColor=vec4(X.x/X.y,1.0,0.0,1.0);}`;me.ShadersStore[W5t]=K5t;class H5t{getPassPP(){return this._outputPP}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScale(e){this._worldScale=e}setDebugDisplayParams(e,t,i,n){this._debugSizeParams.set(e,t,i,n)}_createDebugPass(){if(!this._debugPassPP){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:6,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1};this._debugPassPP=new ii(this.debugPassName,"iblShadowDebug",e),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add(t=>{t.setTextureFromPostProcessOutput("debugSampler",this._outputPP),t.setVector4("sizeParams",this._debugSizeParams)})}}constructor(e){this._worldScale=1,this._debugPassName="Spatial Blur Debug Pass",this.debugEnabled=!1,this._debugSizeParams=new It(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._createTextures()}_createTextures(){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:7,textureType:0,samplingMode:1,uniforms:["blurParameters"],samplers:["shadowSampler","worldNormalSampler","linearDepthSampler"],engine:this._engine,reusable:!1};this._outputPP=new ii("spacialBlurPP","iblShadowSpatialBlur",e),this._outputPP.autoClear=!1,this._outputPP.onApplyObservable.add(t=>{this._updatePostProcess(t)})}_updatePostProcess(e){e.setVector4("blurParameters",new It(1,this._worldScale,0,0));const i=this._scene.prePassRenderer;if(i){const n=i.getIndex(8),s=i.getIndex(5);n>=0&&e.setTexture("worldNormalSampler",i.getRenderTarget().textures[n]),s>=0&&e.setTexture("linearDepthSampler",i.getRenderTarget().textures[s])}}isReady(){return this._outputPP.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._outputPP.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}const j5t="iblShadowAccumulationPixelShader",$5t=`#ifdef GL_ES precision mediump float; #endif varying vec2 vUV;uniform vec4 accumulationParameters; #define remanence accumulationParameters.x #define resetb accumulationParameters.y uniform sampler2D motionSampler; uniform sampler2D localPositionSampler; uniform sampler2D textureSampler; uniform sampler2D oldAccumulationSampler; uniform sampler2D prevLocalPositionSampler; vec2 max2(vec2 v,vec2 w) { return vec2(max(v.x,w.x),max(v.y,w.y)); } void main(void) {bool reset=bool(resetb);vec2 Resolution=vec2(textureSize(textureSampler,0));ivec2 currentPixel=ivec2(vUV*Resolution);vec4 LP=texelFetch(localPositionSampler,currentPixel,0);if (0.0==LP.w) {gl_FragColor=vec4(1.0,0.0,0.0,1.0);return;} vec2 velocityColor=texelFetch(motionSampler,currentPixel,0).xy;vec2 prevCoord=vUV+velocityColor;vec3 PrevLP=textureLod(prevLocalPositionSampler,prevCoord,0.0).xyz;vec2 PrevShadows=textureLod(oldAccumulationSampler,prevCoord,0.0).xy;float newShadows=texelFetch(textureSampler,currentPixel,0).x;PrevShadows.y = !reset && all(lessThan(abs(prevCoord-vec2(0.5)),vec2(0.5))) && distance(LP.xyz,PrevLP)<5e-2 ? max(PrevShadows.y/(1.0+PrevShadows.y),1.0-remanence) : 1.0;PrevShadows=max(vec2(0.0),PrevShadows);gl_FragColor=vec4(mix(PrevShadows.x,newShadows,PrevShadows.y), PrevShadows.y,0,1.0);}`;me.ShadersStore[j5t]=$5t;class X5t{getPassPP(){return this._outputPP}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}get remenance(){return this._remenance}set remenance(e){this._remenance=e}get reset(){return this._reset}set reset(e){this._reset=e}setDebugDisplayParams(e,t,i,n){this._debugSizeParams.set(e,t,i,n)}_createDebugPass(){if(!this._debugPassPP){const e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:7,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1};this._debugPassPP=new ii(this.debugPassName,"iblShadowDebug",e),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add(t=>{t.setTextureFromPostProcessOutput("debugSampler",this._outputPP),t.setVector4("sizeParams",this._debugSizeParams)})}}constructor(e){this.debugEnabled=!1,this._debugPassName="Shadow Accumulation Debug Pass",this._remenance=.9,this._reset=!0,this._debugSizeParams=new It(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._createTextures()}_createTextures(){const e={generateDepthBuffer:!1,generateMipMaps:!1,format:5,type:2,samplingMode:2};this._oldLocalPositionRT=new vn("oldLocalPositionRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},this._scene,e);const t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:5,textureType:2,samplingMode:1,engine:this._engine,reusable:!1,defines:"#define PASS_SAMPLER sampler"},i=new ii("Copy Local Position Texture","pass",t);i.autoClear=!1,i.onApplyObservable.add(l=>{const c=this._scene.prePassRenderer,u=c.getIndex(9);u>=0&&l.setTexture("textureSampler",c.getRenderTarget().textures[u])}),this._oldLocalPositionRT.addPostProcess(i),this._oldLocalPositionRT.skipInitialClear=!0,this._oldLocalPositionRT.noPrePassRenderer=!0,this._scene.customRenderTargets.push(this._oldLocalPositionRT);const n={generateDepthBuffer:!1,generateMipMaps:!1,format:7,type:2,samplingMode:1};this._oldAccumulationRT=new vn("oldAccumulationRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},this._scene,n);const s={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:7,textureType:2,samplingMode:1,engine:this._engine,reusable:!1,defines:"#define PASS_SAMPLER sampler"},a=new ii("Copy Accumulation Texture","pass",s);a.autoClear=!1,a.onApplyObservable.add(l=>{l.setTextureFromPostProcessOutput("textureSampler",this._outputPP)}),this._oldAccumulationRT.addPostProcess(a),this._oldAccumulationRT.skipInitialClear=!0,this._oldAccumulationRT.noPrePassRenderer=!0,this._scene.customRenderTargets.push(this._oldAccumulationRT);const o={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:7,textureType:2,samplingMode:1,uniforms:["accumulationParameters"],samplers:["oldAccumulationSampler","prevLocalPositionSampler","localPositionSampler","motionSampler"],engine:this._engine,reusable:!1};this._outputPP=new ii("accumulationPassPP","iblShadowAccumulation",o),this._outputPP.autoClear=!1,this._outputPP.onApplyObservable.add(l=>{this._updatePostProcess(l)})}_updatePostProcess(e){e.setVector4("accumulationParameters",new It(this.remenance,this.reset?1:0,0,0)),e.setTexture("oldAccumulationSampler",this._oldAccumulationRT),e.setTexture("prevLocalPositionSampler",this._oldLocalPositionRT);const t=this._scene.prePassRenderer;if(t){const i=t.getIndex(9);i>=0&&e.setTexture("localPositionSampler",t.getRenderTarget().textures[i]);const n=t.getIndex(11);n>=0&&e.setTexture("motionSampler",t.getRenderTarget().textures[n])}this.reset=!1}resize(){this._oldAccumulationRT.resize({width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()}),this._oldLocalPositionRT.resize({width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()})}_disposeTextures(){this._oldAccumulationRT.dispose(),this._oldLocalPositionRT.dispose()}isReady(){return this._oldAccumulationRT&&this._oldAccumulationRT.isReadyForRendering()&&this._oldLocalPositionRT&&this._oldLocalPositionRT.isReadyForRendering()&&this._outputPP.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._disposeTextures(),this._outputPP.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}class Y5t{constructor(){this.enabled=!0,this.name="iblShadows",this.texturesRequired=[5,10,8,11,1,9]}}class Q5t extends V_{get shadowOpacity(){return this._shadowOpacity}set shadowOpacity(e){this._shadowOpacity=e}get voxelShadowOpacity(){var e;return(e=this._voxelTracingPass)==null?void 0:e.voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.voxelShadowOpacity=e)}get ssShadowOpacity(){var e;return(e=this._voxelTracingPass)==null?void 0:e.ssShadowOpacity}set ssShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.ssShadowOpacity=e)}get ssShadowSamples(){var e;return(e=this._voxelTracingPass)==null?void 0:e.sssSamples}set ssShadowSamples(e){this._voxelTracingPass&&(this._voxelTracingPass.sssSamples=e)}get ssShadowStride(){var e;return(e=this._voxelTracingPass)==null?void 0:e.sssStride}set ssShadowStride(e){this._voxelTracingPass&&(this._voxelTracingPass.sssStride=e)}get ssShadowMaxDist(){var e;return(e=this._voxelTracingPass)==null?void 0:e.sssMaxDist}set ssShadowMaxDist(e){this._voxelTracingPass&&(this._voxelTracingPass.sssMaxDist=e)}get ssShadowThickness(){var e;return(e=this._voxelTracingPass)==null?void 0:e.sssThickness}set ssShadowThickness(e){this._voxelTracingPass&&(this._voxelTracingPass.sssThickness=e)}setIblTexture(e){this._importanceSamplingRenderer&&(this._importanceSamplingRenderer.iblSource=e)}getVoxelGridTexture(){var e;return(e=this._voxelRenderer)==null?void 0:e.getVoxelGrid()}getIcdfyTexture(){return this._importanceSamplingRenderer.getIcdfyTexture()}getIcdfxTexture(){return this._importanceSamplingRenderer.getIcdfxTexture()}get gbufferDebugEnabled(){return this._gbufferDebugEnabled}set gbufferDebugEnabled(e){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable G-Buffer debug view without setting allowDebugPasses to true.");return}this._gbufferDebugEnabled=e,e?this._enableEffect(this._getGBufferDebugPass().name,this.cameras):this._disableEffect(this._getGBufferDebugPass().name,this.cameras)}get importanceSamplingDebugEnabled(){var e;return(e=this._importanceSamplingRenderer)==null?void 0:e.debugEnabled}set importanceSamplingDebugEnabled(e){if(this._importanceSamplingRenderer){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable importance sampling debug view without setting allowDebugPasses to true.");return}e!==this._importanceSamplingRenderer.debugEnabled&&(this._importanceSamplingRenderer.debugEnabled=e,e?this._enableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras):this._disableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras))}}get voxelDebugEnabled(){var e;return(e=this._voxelRenderer)==null?void 0:e.voxelDebugEnabled}set voxelDebugEnabled(e){if(this._voxelRenderer){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable voxel debug view without setting allowDebugPasses to true.");return}this._voxelRenderer.voxelDebugEnabled=e,e?this._enableEffect(this._voxelRenderer.debugPassName,this.cameras):this._disableEffect(this._voxelRenderer.debugPassName,this.cameras)}}get voxelDebugAxis(){var e;return(e=this._voxelRenderer)==null?void 0:e.voxelDebugAxis}set voxelDebugAxis(e){this._voxelRenderer&&(this._voxelRenderer.voxelDebugAxis=e)}set voxelDebugDisplayMip(e){this._voxelRenderer&&this._voxelRenderer.setDebugMipNumber(e)}get voxelTracingDebugEnabled(){var e;return(e=this._voxelTracingPass)==null?void 0:e.debugEnabled}set voxelTracingDebugEnabled(e){if(this._voxelTracingPass){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable voxel tracing debug view without setting allowDebugPasses to true.");return}e!==this._voxelTracingPass.debugEnabled&&(this._voxelTracingPass.debugEnabled=e,e?this._enableEffect(this._voxelTracingPass.debugPassName,this.cameras):this._disableEffect(this._voxelTracingPass.debugPassName,this.cameras))}}get spatialBlurPassDebugEnabled(){var e;return(e=this._spatialBlurPass)==null?void 0:e.debugEnabled}set spatialBlurPassDebugEnabled(e){if(this._spatialBlurPass){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable spatial blur debug view without setting allowDebugPasses to true.");return}e!==this._spatialBlurPass.debugEnabled&&(this._spatialBlurPass.debugEnabled=e,e?this._enableEffect(this._spatialBlurPass.debugPassName,this.cameras):this._disableEffect(this._spatialBlurPass.debugPassName,this.cameras))}}get accumulationPassDebugEnabled(){var e;return(e=this._accumulationPass)==null?void 0:e.debugEnabled}set accumulationPassDebugEnabled(e){if(this._accumulationPass){if(e&&!this.allowDebugPasses){ge.Warn("Can't enable accumulation pass debug view without setting allowDebugPasses to true.");return}e!==this._accumulationPass.debugEnabled&&(this._accumulationPass.debugEnabled=e,e?this._enableEffect(this._accumulationPass.debugPassName,this.cameras):this._disableEffect(this._accumulationPass.debugPassName,this.cameras))}}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)}get resolutionExp(){return this._voxelRenderer.voxelResolutionExp}set resolutionExp(e){if(e!==this._voxelRenderer.voxelResolutionExp){if(this._voxelRenderer.isVoxelizationInProgress()){ge.Warn("Can't change the resolution of the voxel grid while voxelization is in progress.");return}this._voxelRenderer.voxelResolutionExp=e,this.updateVoxelization(),this._accumulationPass.reset=!0}}get sampleDirections(){var e;return(e=this._voxelTracingPass)==null?void 0:e.sampleDirections}set sampleDirections(e){this._voxelTracingPass&&(this._voxelTracingPass.sampleDirections=e)}get shadowRemenance(){var e;return(e=this._accumulationPass)==null?void 0:e.remenance}set shadowRemenance(e){this._accumulationPass&&(this._accumulationPass.remenance=e)}get envRotation(){var e;return(e=this._voxelTracingPass)==null?void 0:e.envRotation}set envRotation(e){this._voxelTracingPass&&(this._voxelTracingPass.envRotation=e)}get allowDebugPasses(){return this._allowDebugPasses}set allowDebugPasses(e){this._allowDebugPasses!==e&&(this._allowDebugPasses=e,e?this._createDebugPasses():this._disposeDebugPasses())}static get IsSupported(){const e=ei.LastCreatedEngine;return e?e._features.supportIBLShadows:!1}constructor(e,t,i={},n){if(super(t.getEngine(),e),this._voxelizationDirty=!0,this._boundsNeedUpdate=!0,this._allowDebugPasses=!1,this._debugPasses=[],this._excludedMeshes=[],this._shadowOpacity=1,this._enabled=!0,this._gbufferDebugEnabled=!1,this._gBufferDebugSizeParams=new It(0,0,0,0),this.scene=t,!t.enablePrePassRenderer()){ge.Warn("IBL Shadows Render Pipeline could not enable PrePass, aborting.");return}this.shadowOpacity=i.shadowOpacity||1,this._prePassEffectConfiguration=new Y5t,this._voxelRenderer=new C5t(this.scene,this,i?i.resolutionExp:6,i.triPlanarVoxelization!==void 0?i.triPlanarVoxelization:!0),this._importanceSamplingRenderer=new G5t(this.scene),this._voxelTracingPass=new M5t(this.scene,this),this.sampleDirections=i.sampleDirections||2,this.ssShadowOpacity=i.ssShadowsEnabled===void 0||i.ssShadowsEnabled?1:0,this.ssShadowMaxDist=i.ssShadowMaxDist||.05,this.ssShadowSamples=i.ssShadowSampleCount||16,this.ssShadowStride=i.ssShadowStride||8,this.ssShadowThickness=i.ssShadowThickness||.01,this._spatialBlurPass=new H5t(this.scene),this._accumulationPass=new X5t(this.scene),this.shadowRemenance=i.shadowRemenance||.75,this._noiseTexture=new be("https://assets.babylonjs.com/textures/blue_noise/blue_noise_rgb.png",this.scene,!1,!0,1),this.scene.environmentTexture&&(this._importanceSamplingRenderer.iblSource=this.scene.environmentTexture),this._createShadowCombinePostProcess(),t.postProcessRenderPipelineManager.addPipeline(this),this._createEffectPasses(n),this.scene.onNewMeshAddedObservable.add(this.updateSceneBounds.bind(this)),this.scene.onMeshRemovedObservable.add(this.updateSceneBounds.bind(this)),this.scene.onActiveCameraChanged.add(this._listenForCameraChanges.bind(this)),this.scene.onBeforeRenderObservable.add(this._updateBeforeRender.bind(this)),this._listenForCameraChanges(),this.scene.getEngine().onResizeObservable.add(this._handleResize.bind(this)),this._importanceSamplingRenderer.onReadyObservable.add(()=>{this._voxelRenderer.isReady()?this.toggleShadow(this._enabled):this._voxelRenderer.onReadyObservable.addOnce(()=>{this.toggleShadow(this._enabled)})})}toggleShadow(e){this._enabled=e,e?(this._enableEffect("IBLShadowVoxelTracingPass",this.cameras),this._enableEffect("IBLShadowSpatialBlurPass",this.cameras),this._enableEffect("IBLShadowAccumulationBlurPass",this.cameras),this._enableEffect("IBLShadowCompositePass",this.cameras)):(this._disableEffect("IBLShadowVoxelTracingPass",null),this._disableEffect("IBLShadowSpatialBlurPass",null),this._disableEffect("IBLShadowAccumulationBlurPass",null),this._disableEffect("IBLShadowCompositePass",null))}_handleResize(){var e;this._voxelRenderer.resize(),(e=this._accumulationPass)==null||e.resize()}_createShadowCombinePostProcess(){const e={width:this.scene.getEngine().getRenderWidth(),height:this.scene.getEngine().getRenderHeight(),uniforms:["shadowOpacity"],samplers:["sceneTexture"],samplingMode:2,engine:this.scene.getEngine(),textureType:0,reusable:!1};this._shadowCompositePP=new ii("iblShadowsCombine","iblShadowsCombine",e),this._shadowCompositePP.autoClear=!1,this._shadowCompositePP.onApplyObservable.add(t=>{var i,n,s,a,o;t.setTextureFromPostProcess("sceneTexture",this._voxelTracingPass.getPassPP()),t.setFloat("shadowOpacity",this._shadowOpacity),(i=this._importanceSamplingRenderer)!=null&&i.isReady()&&((n=this._voxelRenderer)!=null&&n.isReady())&&((s=this._voxelTracingPass)!=null&&s.isReady())&&((a=this._spatialBlurPass)!=null&&a.isReady())&&((o=this._accumulationPass)!=null&&o.isReady())&&this.update()}),this._shadowCompositePP._prePassEffectConfiguration=this._prePassEffectConfiguration,setTimeout(()=>{this._voxelizationDirty=!0},500)}_createEffectPasses(e){this.addEffect(new sn(this.scene.getEngine(),"IBLShadowVoxelTracingPass",()=>this._voxelTracingPass.getPassPP(),!0)),this.addEffect(new sn(this.scene.getEngine(),"IBLShadowSpatialBlurPass",()=>this._spatialBlurPass.getPassPP(),!0)),this.addEffect(new sn(this.scene.getEngine(),"IBLShadowAccumulationBlurPass",()=>this._accumulationPass.getPassPP(),!0)),this.addEffect(new sn(this.scene.getEngine(),"IBLShadowCompositePass",()=>this._shadowCompositePP,!0)),e&&this.scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this.name,e),this.toggleShadow(!1),this._enabled=!0,this.allowDebugPasses&&this._createDebugPasses()}_getGBufferDebugPass(){if(this._gbufferDebugPass)return this._gbufferDebugPass;const e=this._prePassEffectConfiguration.texturesRequired.map(i=>hc.TextureFormats[i].name.toString()),t={width:this.scene.getEngine().getRenderWidth(),height:this.scene.getEngine().getRenderHeight(),samplingMode:1,engine:this.scene.getEngine(),textureType:0,textureFormat:5,uniforms:["sizeParams"],samplers:e,reusable:!1};return this._gbufferDebugPass=new ii("iblShadowGBufferDebug","iblShadowGBufferDebug",t),this._gbufferDebugPass.autoClear=!1,this._gbufferDebugPass.onApplyObservable.add(i=>{this._prePassEffectConfiguration.texturesRequired.forEach(n=>{const s=this.scene.prePassRenderer;if(!s){ge.Error("Can't enable G-Buffer debug rendering since prepassRenderer doesn't exist.");return}const a=s.getIndex(n);a>=0&&i.setTexture(hc.TextureFormats[n].name,s.getRenderTarget().textures[a])}),i.setVector4("sizeParams",this._gBufferDebugSizeParams),this.scene.activeCamera&&i.setFloat("maxDepth",this.scene.activeCamera.maxZ)}),this._gbufferDebugPass}_createDebugPasses(){var t,i,n,s,a;this._debugPasses=[(t=this._importanceSamplingRenderer)==null?void 0:t.getDebugPassPP(),(i=this._voxelRenderer)==null?void 0:i.getDebugPassPP(),(n=this._voxelTracingPass)==null?void 0:n.getDebugPassPP(),(s=this._spatialBlurPass)==null?void 0:s.getDebugPassPP(),(a=this._accumulationPass)==null?void 0:a.getDebugPassPP(),this._getGBufferDebugPass()];for(let o=0;othis._debugPasses[o],!0));const e=this.cameras.slice();this.scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this.name,this.cameras),this.scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this.name,e);for(let o=0;o{e instanceof mn?e.inertialAlphaOffset!==0||e.inertialBetaOffset!==0||e.inertialRadiusOffset!==0||e.inertialPanningX!==0||e.inertialPanningY:e instanceof ql&&(e.cameraDirection.x!==0||e.cameraDirection.y!==0||e.cameraDirection.z!==0||e.cameraRotation.x!==0||e.cameraRotation.y),this._accumulationPass})}setPrePassRenderer(e){return!!e.addEffectConfiguration(this._prePassEffectConfiguration)}isReady(){return this._noiseTexture.isReady()&&this._voxelRenderer.isReady()&&this._importanceSamplingRenderer.isReady()&&(!this._voxelTracingPass||this._voxelTracingPass.isReady())&&(!this._spatialBlurPass||this._spatialBlurPass.isReady())&&(!this._accumulationPass||this._accumulationPass.isReady())}update(){var e,t;if(!this._voxelRenderer.isVoxelizationInProgress()){if(this._boundsNeedUpdate){const i=this.scene.getWorldExtends(c=>c instanceof Re&&this._excludedMeshes.indexOf(c.uniqueId)===-1),n=i.max.subtract(i.min),s=Math.max(n.x,Math.max(n.y,n.z))*.5,a=i.max.add(i.min).multiplyByFloats(-.5,-.5,-.5),o=pe.Compose(new O(1/s,1/s,1/s),new Oe,new O(0,0,0));pe.Compose(new O(1,1,1),new Oe,a).multiplyToRef(o,o),(e=this._voxelTracingPass)==null||e.setWorldScaleMatrix(o),this._voxelRenderer.setWorldScaleMatrix(o),(t=this._spatialBlurPass)==null||t.setWorldScale(s*2),this._boundsNeedUpdate=!1,ge.Log("IBL Shadows: Scene size: "+n),ge.Log("Half size: "+s),ge.Log("Centre translation: "+a)}this._voxelizationDirty&&(this._voxelRenderer.updateVoxelGrid(this._excludedMeshes),this._voxelizationDirty=!1)}}getClassName(){return"IBLShadowsRenderPipeline"}dispose(){var e,t,i;this._disposeEffectPasses(),this._noiseTexture.dispose(),this._voxelRenderer.dispose(),this._importanceSamplingRenderer.dispose(),(e=this._voxelTracingPass)==null||e.dispose(),(t=this._spatialBlurPass)==null||t.dispose(),(i=this._accumulationPass)==null||i.dispose(),super.dispose()}}Object.defineProperty(Ut.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(r){r&&r.isSupported&&(this._prePassRenderer=r)},enumerable:!0,configurable:!0});Ut.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new hc(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,ge.Error(`PrePassRenderer needs WebGL 2 support. Maybe you tried to use the following features that need the PrePassRenderer : + Subsurface Scattering`)),this._prePassRenderer)};Ut.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class Iqe{constructor(e){this.name=bt.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(bt.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(bt.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(bt.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(bt.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(bt.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(bt.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(bt.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(bt.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,n){if(!n)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(n,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}hc._SceneComponentInitialization=r=>{let e=r._getComponent(bt.NAME_PREPASSRENDERER);e||(e=new Iqe(r),r._addComponent(e))};const Z5t="fibonacci",q5t=`#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);}`;me.IncludesShadersStore[Z5t]=q5t;const J5t="diffusionProfile",ewt="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";me.IncludesShadersStore[J5t]=ewt;const twt="subSurfaceScatteringPixelShader",iwt=`#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){ge.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 SV{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=bt.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Pe(1,1,1)),this._scene=e,SV._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return ge.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw Ji("SubSurfaceSceneComponent")};vo.AddParser(bt.NAME_SUBSURFACE,(r,e)=>{if(r.ssDiffusionProfileColors!==void 0&&r.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=r.ssDiffusionProfileColors.length;t{let e=r._getComponent(bt.NAME_SUBSURFACE);e||(e=new Pqe(r),r._addComponent(e))};Ut.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new vw(this)),this._outlineRenderer};Object.defineProperty(Re.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(r){r&&this.getScene().getOutlineRenderer(),this._renderOutline=r},enumerable:!0,configurable:!0});Object.defineProperty(Re.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(r){r&&this.getScene().getOutlineRenderer(),this._renderOverlay=r},enumerable:!0,configurable:!0});class vw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=bt.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(bt.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(bt.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 n=[],s=[ee.PositionKind,ee.NormalKind],a=e.getMesh(),o=e.getMaterial();if(!o)return!1;const l=a.getScene();o.needAlphaTesting()&&(n.push("#define ALPHATEST"),a.isVerticesDataPresent(ee.UVKind)&&(s.push(ee.UVKind),n.push("#define UV1")),a.isVerticesDataPresent(ee.UV2Kind)&&(s.push(ee.UV2Kind),n.push("#define UV2"))),o.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH"),x3(o,l,n);const c=new ha;if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){s.push(ee.MatricesIndicesKind),s.push(ee.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(ee.MatricesIndicesExtraKind),s.push(ee.MatricesWeightsExtraKind));const m=a.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),a.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,a),m.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(m.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=a.morphTargetManager;let h=0;u&&(h=u.numMaxInfluencers||u.numInfluencers,h>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+h),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),tb(s,a,h))),t&&(n.push("#define INSTANCES"),k_(s),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const d=a.bakedVertexAnimationManager;d&&d.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&s.push("bakedVertexAnimationSettingsInstanced"));const f=e._getDrawWrapper(i,!0),p=f.defines,g=n.join(` `);if(p!==g){const m=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],_=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];Yo(m),f.setEffect(this.scene.getEngine().createEffect("outline",{attributes:s,uniformsNames:m,uniformBuffersNames:[],samplers:_,defines:g,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:h},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([je(()=>Promise.resolve().then(()=>rDt),void 0),je(()=>Promise.resolve().then(()=>nDt),void 0)]):await Promise.all([je(()=>Promise.resolve().then(()=>tDt),void 0),je(()=>Promise.resolve().then(()=>iDt),void 0)])}},this.scene.getEngine()),g)}return f.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const n=t.getMaterial();n&&n.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(vw._StencilReference),this._engine.setStencilFunctionReference(vw._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),n&&n.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const n=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(n),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}vw._StencilReference=4;class z2e{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 Ce,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 _g({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new _g({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 wqe extends z2e{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 Pae{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 n=0;n{this._postProcessRunningIndex===0?m.setTexture("textureSampler",e):m._bindTexture("textureSampler",f.inputTexture.texture),m.setInt("filterSize",this.blurFilterSize),m.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(m=>{m.texture.wrapU=be.CLAMP_ADDRESSMODE,m.texture.wrapV=be.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const p=new ii("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(m=>{m.setInt("filterSize",this.blurFilterSize),m.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),p.onSizeChangedObservable.add(()=>{p._textures.forEach(m=>{m.texture.wrapU=be.CLAMP_ADDRESSMODE,m.texture.wrapV=be.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p),f.autoClear=!1,p.autoClear=!1;const g=[];for(let m=0;m{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=be.CLAMP_ADDRESSMODE,_.texture.wrapV=be.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(p);const g=new ii("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);g.samples=this._samples,g.onApplyObservable.add(_=>{_.setInt("maxFilterSize",this.blurMaxFilterSize),_.setFloat2("blurDir",0,1/this._blurTextureSizeY),_.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),_.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),g.onSizeChangedObservable.add(()=>{g._textures.forEach(_=>{_.texture.wrapU=be.CLAMP_ADDRESSMODE,_.texture.wrapV=be.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(g),p.autoClear=!1,g.autoClear=!1;const m=[];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,n;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,(n=this._textureBlurred)==null||n.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var sfe;(function(r){r[r.DepthTexture=0]="DepthTexture",r[r.DepthBlurredTexture=1]="DepthBlurredTexture",r[r.ThicknessTexture=2]="ThicknessTexture",r[r.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",r[r.DiffuseTexture=4]="DiffuseTexture",r[r.Normals=5]="Normals",r[r.DiffuseRendering=6]="DiffuseRendering"})(sfe||(sfe={}));class afe{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 Pe(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new O(-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 Ce,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 pe,this._depthClearColor=new at(1e6,1e6,1e6,1),this._thicknessClearColor=new at(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 Pae("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const s=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 Pae("Diffuse",this._scene,s,a,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),n=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Pae("Thickness",this._scene,i,n,i,n,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"],n=[];if(this.dispose(!0),!this._camera)return;const s=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new Ne(1/s.getSize().width,1/s.getSize().height);this._scene.useRightHandedSystem&&n.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),n.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),n.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),n.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),n.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&n.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(n.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===5?n.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===6?n.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(n.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),(this._debugFeature===0||this._debugFeature===1)&&n.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new ii("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(n.join(` `)),this._renderPostProcess.samples=this._samples;const o=e,l=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add(c=>{var u,h,d,f,p,g,m,_,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",((g=this._thicknessRenderTarget.textureBlur)==null?void 0:g.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=((m=this._thicknessRenderTarget)==null?void 0:m.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,n,s,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)),(n=this._diffuseRenderTarget)!=null&&n.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(s=this._thicknessRenderTarget)!=null&&s.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,n,s;e||((t=this._depthRenderTarget)==null||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)==null||i.dispose(),this._diffuseRenderTarget=null,(n=this._thicknessRenderTarget)==null||n.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(s=this._renderPostProcess)==null||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Dqe extends z2e{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,n=!0;switch(t){case"velocity":i=3;break;case"offset":n=!1;break}this._vertexBuffers[t]=new ee(this._engine,e[t],t,!0,!1,i,n)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new _g({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 ee(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 ofe;(function(r){r[r.None=0]="None",r[r.ToLinearSpace=1]="ToLinearSpace",r[r.ToGammaSpace=2]="ToGammaSpace"})(ofe||(ofe={}));class Oqe{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 aD(e),this._initShaderSourceAsync(t)}async _initShaderSourceAsync(e){const t=this._engine;t.isWebGPU?(this._shaderLanguage=1,await je(()=>Promise.resolve().then(()=>UDt),void 0)):await je(()=>Promise.resolve().then(()=>kDt),void 0),this._shadersLoaded=!0,this._effectWrapper=new _g({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 n=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&n&&(this._engine.depthCullingState.depthFunc=n),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class nwt{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,n=1){this._engine=e,this._copyTextureToTexture=new Oqe(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:n,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"});const s=this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil");s.label=`FluidDepthTextureCopy${t}x${i}x${n}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const swt="fluidRenderingParticleDepthVertexShader",awt=`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 } `;me.ShadersStore[swt]=awt;const owt="fluidRenderingParticleDepthPixelShader",lwt=`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 } `;me.ShadersStore[owt]=lwt;const cwt="fluidRenderingParticleThicknessVertexShader",uwt=`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;} `;me.ShadersStore[cwt]=uwt;const hwt="fluidRenderingParticleThicknessPixelShader",dwt=`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);} `;me.ShadersStore[hwt]=dwt;const fwt="fluidRenderingParticleDiffuseVertexShader",pwt=`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;} `;me.ShadersStore[fwt]=pwt;const mwt="fluidRenderingParticleDiffusePixelShader",gwt=`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);} `;me.ShadersStore[mwt]=gwt;const _wt="fluidRenderingBilateralBlurPixelShader",vwt=`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.);} `;me.ShadersStore[_wt]=vwt;const ywt="fluidRenderingStandardBlurPixelShader",xwt=`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.);} `;me.ShadersStore[ywt]=xwt;const bwt="fluidRenderingRenderPixelShader",Cwt=`#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);} `;me.ShadersStore[bwt]=Cwt;Object.defineProperty(Ut.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(r){this._fluidRenderer=r},enumerable:!0,configurable:!0});Ut.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new rte(this),this._fluidRenderer)};Ut.prototype.disableFluidRenderer=function(){var r;(r=this._fluidRenderer)==null||r.dispose(),this._fluidRenderer=null};function Awt(r){return!!r.particleSystem}function Swt(r){return!!r.addBuffers}class Lqe{constructor(e){this.name=bt.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(bt.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(bt.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 rte{static _SceneComponentInitialization(e){let t=e._getComponent(bt.NAME_FLUIDRENDERER);t||(t=new Lqe(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,rte._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,n){const s=new wqe(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new afe(this._scene,n),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),t!==void 0&&(i.generateDiffuseTexture=t);const a={object:s,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}addCustomParticles(e,t,i,n,s){const a=new Dqe(this._scene,e,t);a.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),n||(n=new afe(this._scene,s),this.targetRenderers.push(n)),n._onUseVelocityChanged.hasObservers()||n._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(n.generateDiffuseTexture=i);const o={object:a,targetRenderer:n};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 n=0;n{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 nwt(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 n=i.value,a=this._cameras.get(n)[1],o=e.get(n);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 n=0;n{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class Ewt{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=pe.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,n=t.rg11b10ufColorRenderable?4:5;this._mrt=new r_("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,n]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new at(0,0,0,1),this._mrt.noPrePassRenderer=!0;let s,a;const o=this._scene.getEngine().supportsUniformBuffers;o&&(s=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=>{s&&this._scene.setSceneUniformBuffer(s);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;s&&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 n;(n=this._mrt.renderList)==null||n.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 s=new cb(i);s.isEnabled=!0,s.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class Twt extends Kn{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class cb extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,cb.Name,300,new Twt),this._lightColor=new Pe,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof an?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===Dr.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()===Dr.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=oe.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 `}}}cb.Name="RSMCreate";V([Q()],cb.prototype,"light",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],cb.prototype,"isEnabled",void 0);xe("BABYLON.RSMCreatePluginMaterial",cb);class Mwt{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 nte{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(yp.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 n=0;n{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(()=>Owt),void 0),je(()=>Promise.resolve().then(()=>Lwt),void 0),je(()=>Promise.resolve().then(()=>Nwt),void 0),je(()=>Promise.resolve().then(()=>Fwt),void 0)])):await Promise.all([je(()=>Promise.resolve().then(()=>Iwt),void 0),je(()=>Promise.resolve().then(()=>Pwt),void 0),je(()=>Promise.resolve().then(()=>wwt),void 0),je(()=>Promise.resolve().then(()=>Dwt),void 0)]),this._shadersLoaded=!0,this._onShaderLoadedObservable.notifyObservers()}_disposePostProcesses(e=!1){var t,i,n,s,a;(t=this._blurRTT)==null||t.dispose(),this._blurRTT=null,this._blurPostProcesses=[],(i=this._blurXPostprocess)==null||i.dispose(),this._blurXPostprocess=null,(n=this._blurYPostprocess)==null||n.dispose(),this._blurYPostprocess=null,(s=this._upsamplingXPostprocess)==null||s.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(yp.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,nte.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,n=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let s="";i&&(s+=`#define DECODE_NORMAL `),n||(s+=`#define TRANSFORM_NORMAL `);for(let l=0;l{d.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(dn.POSITION_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(dn.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)),n||(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 vn("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 ii(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(dn.DEPTH_TEXTURE_TYPE)]),h.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(dn.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 ii("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(dn.DEPTH_TEXTURE_TYPE)]),h.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(dn.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 ii(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(dn.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(dn.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 ii("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(dn.DEPTH_TEXTURE_TYPE)]),d.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(dn.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 Cn(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){var i;if((i=e.pluginManager)!=null&&i.getPlugin(yp.Name))return;const t=new yp(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)}}nte.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class Rwt extends Kn{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class yp extends Yu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,yp.Name,310,new Rwt),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof an}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}}yp.Name="GIRSMRender";V([Q()],yp.prototype,"textureGIContrib",void 0);V([Q()],yp.prototype,"outputTextureWidth",void 0);V([Q()],yp.prototype,"outputTextureHeight",void 0);V([Q(),Ke("_markAllSubMeshesAsTexturesDirty")],yp.prototype,"isEnabled",void 0);xe("BABYLON.GIRSMRenderPluginMaterial",yp);const Nqe="bilateralBlurPixelShader",Fqe=`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.);} `;me.ShadersStore[Nqe]=Fqe;const Bqe={name:Nqe,shader:Fqe},Iwt=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurPixelShader:Bqe},Symbol.toStringTag,{value:"Module"})),kqe="bilateralBlurQualityPixelShader",Uqe=`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.);} `;me.ShadersStore[kqe]=Uqe;const zqe={name:kqe,shader:Uqe},Pwt=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurQualityPixelShader:zqe},Symbol.toStringTag,{value:"Module"})),Vqe="rsmGlobalIlluminationPixelShader",Gqe=`/** * 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;} `;me.ShadersStore[Vqe]=Gqe;const Wqe={name:Vqe,shader:Gqe},wwt=Object.freeze(Object.defineProperty({__proto__:null,rsmGlobalIlluminationPixelShader:Wqe},Symbol.toStringTag,{value:"Module"})),Kqe="rsmFullGlobalIlluminationPixelShader",Hqe=`/** * 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.);} `;me.ShadersStoreWGSL[$qe]=Xqe;const Yqe={name:$qe,shader:Xqe},Owt=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurPixelShaderWGSL:Yqe},Symbol.toStringTag,{value:"Module"})),Qqe="bilateralBlurQualityPixelShader",Zqe=`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.);} `;me.ShadersStoreWGSL[Qqe]=Zqe;const qqe={name:Qqe,shader:Zqe},Lwt=Object.freeze(Object.defineProperty({__proto__:null,bilateralBlurQualityPixelShaderWGSL:qqe},Symbol.toStringTag,{value:"Module"})),Jqe="rsmGlobalIlluminationPixelShader",eJe=`/** * 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);} `;me.ShadersStoreWGSL[Jqe]=eJe;const tJe={name:Jqe,shader:eJe},Nwt=Object.freeze(Object.defineProperty({__proto__:null,rsmGlobalIlluminationPixelShaderWGSL:tJe},Symbol.toStringTag,{value:"Module"})),iJe="rsmFullGlobalIlluminationPixelShader",rJe=`/** * 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);} `;me.ShadersStoreWGSL[iJe]=rJe;const nJe={name:iJe,shader:rJe},Fwt=Object.freeze(Object.defineProperty({__proto__:null,rsmFullGlobalIlluminationPixelShaderWGSL:nJe},Symbol.toStringTag,{value:"Module"})),sJe="depthPixelShader",aJe=`#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 }`;me.ShadersStoreWGSL[sJe]=aJe;const oJe={name:sJe,shader:aJe},Bwt=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShaderWGSL:oJe},Symbol.toStringTag,{value:"Module"})),lJe="depthVertexShader",cJe=`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 } `;me.ShadersStoreWGSL[lJe]=cJe;const uJe={name:lJe,shader:cJe},kwt=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShaderWGSL:uJe},Symbol.toStringTag,{value:"Module"})),hJe="geometryPixelShader",dJe=`#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 #if defined(PREPASS_NORMAL) || defined(PREPASS_WORLD_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 } `;me.ShadersStoreWGSL[hJe]=dJe;const fJe={name:hJe,shader:dJe},Uwt=Object.freeze(Object.defineProperty({__proto__:null,geometryPixelShaderWGSL:fJe},Symbol.toStringTag,{value:"Module"})),pJe="geometryVertexShader",mJe=`#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 } `;me.ShadersStoreWGSL[pJe]=mJe;const gJe={name:pJe,shader:mJe},zwt=Object.freeze(Object.defineProperty({__proto__:null,geometryVertexShaderWGSL:gJe},Symbol.toStringTag,{value:"Module"})),Vwt="boundingBoxRendererFragmentDeclaration",Gwt=`uniform vec4 color; `;me.IncludesShadersStore[Vwt]=Gwt;const Wwt="boundingBoxRendererUboDeclaration",Kwt=`#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 `;me.IncludesShadersStore[Wwt]=Kwt;const _Je="boundingBoxRendererPixelShader",vJe=`#include<__decl__boundingBoxRendererFragment> #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END }`;me.ShadersStore[_Je]=vJe;const yJe={name:_Je,shader:vJe},bRe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererPixelShader:yJe},Symbol.toStringTag,{value:"Module"})),Hwt="boundingBoxRendererVertexDeclaration",jwt=`uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif `;me.IncludesShadersStore[Hwt]=jwt;const xJe="boundingBoxRendererVertexShader",bJe=`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 } `;me.ShadersStore[xJe]=bJe;const CJe={name:xJe,shader:bJe},CRe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererVertexShader:CJe},Symbol.toStringTag,{value:"Module"})),AJe="boundingBoxRendererPixelShader",SJe=`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 }`;me.ShadersStoreWGSL[AJe]=SJe;const EJe={name:AJe,shader:SJe},ARe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererPixelShaderWGSL:EJe},Symbol.toStringTag,{value:"Module"})),TJe="boundingBoxRendererVertexShader",MJe=`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 } `;me.ShadersStoreWGSL[TJe]=MJe;const RJe={name:TJe,shader:MJe},SRe=Object.freeze(Object.defineProperty({__proto__:null,boundingBoxRendererVertexShaderWGSL:RJe},Symbol.toStringTag,{value:"Module"})),IJe="linePixelShader",PJe=`#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 }`;me.ShadersStore[IJe]=PJe;const wJe={name:IJe,shader:PJe},$wt=Object.freeze(Object.defineProperty({__proto__:null,linePixelShader:wJe},Symbol.toStringTag,{value:"Module"})),Xwt="lineVertexDeclaration",Ywt=`uniform mat4 viewProjection; #define ADDITIONAL_VERTEX_DECLARATION `;me.IncludesShadersStore[Xwt]=Ywt;const Qwt="lineUboDeclaration",Zwt=`layout(std140,column_major) uniform; #include #include `;me.IncludesShadersStore[Qwt]=Zwt;const DJe="lineVertexShader",OJe=`#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 }`;me.ShadersStore[DJe]=OJe;const LJe={name:DJe,shader:OJe},qwt=Object.freeze(Object.defineProperty({__proto__:null,lineVertexShader:LJe},Symbol.toStringTag,{value:"Module"})),NJe="linePixelShader",FJe=`#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 }`;me.ShadersStoreWGSL[NJe]=FJe;const BJe={name:NJe,shader:FJe},Jwt=Object.freeze(Object.defineProperty({__proto__:null,linePixelShaderWGSL:BJe},Symbol.toStringTag,{value:"Module"})),kJe="lineVertexShader",UJe=`#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 }`;me.ShadersStoreWGSL[kJe]=UJe;const zJe={name:kJe,shader:UJe},eDt=Object.freeze(Object.defineProperty({__proto__:null,lineVertexShaderWGSL:zJe},Symbol.toStringTag,{value:"Module"})),VJe="outlinePixelShader",GJe=`#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 }`;me.ShadersStore[VJe]=GJe;const WJe={name:VJe,shader:GJe},tDt=Object.freeze(Object.defineProperty({__proto__:null,outlinePixelShader:WJe},Symbol.toStringTag,{value:"Module"})),KJe="outlineVertexShader",HJe=`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 } `;me.ShadersStore[KJe]=HJe;const jJe={name:KJe,shader:HJe},iDt=Object.freeze(Object.defineProperty({__proto__:null,outlineVertexShader:jJe},Symbol.toStringTag,{value:"Module"})),$Je="outlinePixelShader",XJe=`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 }`;me.ShadersStoreWGSL[$Je]=XJe;const YJe={name:$Je,shader:XJe},rDt=Object.freeze(Object.defineProperty({__proto__:null,outlinePixelShaderWGSL:YJe},Symbol.toStringTag,{value:"Module"})),QJe="outlineVertexShader",ZJe=`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 } `;me.ShadersStoreWGSL[QJe]=ZJe;const qJe={name:QJe,shader:ZJe},nDt=Object.freeze(Object.defineProperty({__proto__:null,outlineVertexShaderWGSL:qJe},Symbol.toStringTag,{value:"Module"})),sDt="spriteMapPixelShader",aDt=`#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;} `;me.ShadersStore[sDt]=aDt;const oDt="spriteMapVertexShader",lDt=`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;}`;me.ShadersStore[oDt]=lDt;class cDt{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,n,s){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=n,n.stageSize=n.stageSize||new Ne(1,1),n.outputSize=n.outputSize||n.stageSize,n.outputPosition=n.outputPosition||O.Zero(),n.outputRotation=n.outputRotation||O.Zero(),n.layerCount=n.layerCount||1,n.maxAnimationFrames=n.maxAnimationFrames||0,n.baseTile=n.baseTile||0,n.flipU=n.flipU||!1,n.colorMultiply=n.colorMultiply||new O(1,1,1),this._scene=s,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 Ne(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1));return}c<100&&setTimeout(()=>{c++,u()},100)};u(),this._material.setVector3("colorMul",n.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=U_(e+":output",{size:1,updatable:!0},s),this._output.scaling.x=n.outputSize.x,this._output.scaling.y=n.outputSize.y,this.position=n.outputPosition,this.rotation=n.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||Ne.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,n=>n===e);if(!t||!t.hit||!t.getTextureCoordinates)return new Ne(-1,-1);const i=t.getTextureCoordinates();return i||new Ne(-1,-1)}_createFrameBuffer(){const e=[];for(let n=0;n0&&(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 n=t.response.split(` \r`);for(let s=0;s{e.dispose()}),this._frameMap.dispose()}}class uDt extends hg{constructor(e,t,i,n,s=null,a=.01,o=be.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,n,a,o,!0,s),this.name=e}}const hDt="imageProcessingCompatibility",dDt=`#ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); #endif `;me.IncludesShadersStore[hDt]=dDt;const JJe="spritesPixelShader",eet=`#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 }`;me.ShadersStore[JJe]=eet;const tet={name:JJe,shader:eet},fDt=Object.freeze(Object.defineProperty({__proto__:null,spritesPixelShader:tet},Symbol.toStringTag,{value:"Module"})),iet="spritesVertexShader",ret=`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 }`;me.ShadersStore[iet]=ret;const net={name:iet,shader:ret},pDt=Object.freeze(Object.defineProperty({__proto__:null,spritesVertexShader:net},Symbol.toStringTag,{value:"Module"})),mDt="imageProcessingCompatibility",gDt=`#ifdef IMAGEPROCESSINGPOSTPROCESS fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a); #endif `;me.IncludesShadersStoreWGSL[mDt]=gDt;const set="spritesPixelShader",aet=`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 }`;me.ShadersStoreWGSL[set]=aet;const oet={name:set,shader:aet},_Dt=Object.freeze(Object.defineProperty({__proto__:null,spritesPixelShaderWGSL:oet},Symbol.toStringTag,{value:"Module"})),cet="spritesVertexShader",uet=`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 }`;me.ShadersStoreWGSL[cet]=uet;const het={name:cet,shader:uet},vDt=Object.freeze(Object.defineProperty({__proto__:null,spritesVertexShaderWGSL:het},Symbol.toStringTag,{value:"Module"}));var lfe;(function(r){r[r.INIT=0]="INIT",r[r.RUNNING=1]="RUNNING",r[r.DONE=2]="DONE",r[r.ERROR=3]="ERROR"})(lfe||(lfe={}));class Kg{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)},(n,s)=>{this._onErrorCallback(i,n,s)})}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 det{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class fet extends Kg{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){bs.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,n=>{this.loadedContainer=n,this.loadedMeshes=n.meshes,this.loadedTransformNodes=n.transformNodes,this.loadedParticleSystems=n.particleSystems,this.loadedSkeletons=n.skeletons,this.loadedAnimationGroups=n.animationGroups,t()},null,(n,s,a)=>{i(s,a)},this.extension)}}class pet extends Kg{constructor(e,t,i,n,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=n,this.extension=s}runTask(e,t,i){bs.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,(n,s,a,o,l)=>{this.loadedMeshes=n,this.loadedTransformNodes=l,this.loadedParticleSystems=s,this.loadedSkeletons=a,this.loadedAnimationGroups=o,t()},null,(n,s,a)=>{i(s,a)},this.extension)}}class yDt extends Kg{constructor(e,t,i,n,s){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=n,this.extension=s}runTask(e,t,i){const n=e.animatables.length,s=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],bs.ImportAnimations(this.rootUrl,this.filename,e,!1,3,this.targetConverter,()=>{this.loadedAnimatables=e.animatables.slice(n),this.loadedAnimationGroups=e.animationGroups.slice(s),t()},null,(a,o,l)=>{i(o,l)},this.extension)}}class met extends Kg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,n=>{this.text=n,t()},void 0,!1,!1,(n,s)=>{n&&i(n.status+" "+n.statusText,s)})}}class get extends Kg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,n=>{this.data=n,t()},void 0,!0,!0,(n,s)=>{n&&i(n.status+" "+n.statusText,s)})}}class _et extends Kg{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const n=new Image;Ie.SetCorsBehavior(this.url,n),n.onload=()=>{this.image=n,t()},n.onerror=s=>{i("Error loading image",s)},n.src=this.url}}class vet extends Kg{constructor(e,t,i,n=!0,s=be.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=n,this.samplingMode=s}runTask(e,t,i){const n=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new be(this.url,e,this.noMipmap,this.invertY,this.samplingMode,n,s)}}class yet extends Kg{constructor(e,t,i,n,s,a){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=n,this.files=s,this.prefiltered=a}runTask(e,t,i){const n=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new Za(this.url,e,this.extensions,this.noMipmap,this.files,n,s,void 0,this.prefiltered)}}class xet extends Kg{constructor(e,t,i,n=!1,s=!0,a=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.generateHarmonics=s,this.gammaSpace=a,this.reserved=o}runTask(e,t,i){const n=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new Cg(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,n,s)}}class bet extends Kg{constructor(e,t,i,n=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=n,this.gammaSpace=s}runTask(e,t,i){const n=()=>{t()},s=(a,o)=>{i(a,o)};this.texture=new hw(this.url,e,this.size,this.noMipmap,this.gammaSpace,n,s)}}class xDt{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new Ce,this.onTaskErrorObservable=new Ce,this.onTasksDoneObservable=new Ce,this.onProgressObservable=new Ce,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||ei.LastCreatedScene}addContainerTask(e,t,i,n,s){const a=new fet(e,t,i,n,s);return this._tasks.push(a),a}addMeshTask(e,t,i,n,s){const a=new pet(e,t,i,n,s);return this._tasks.push(a),a}addTextFileTask(e,t){const i=new met(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new get(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new _et(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,n,s=be.TRILINEAR_SAMPLINGMODE){const a=new vet(e,t,i,n,s);return this._tasks.push(a),a}addCubeTextureTask(e,t,i,n,s,a){const o=new yet(e,t,i,n,s,a);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,n=!1,s=!0,a=!1,o=!1){const l=new xet(e,t,i,n,s,a,o);return this._tasks.push(l),l}addEquiRectangularCubeTextureAssetTask(e,t,i,n=!1,s=!0){const a=new bet(e,t,i,n,s);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 det(this._waitingTasksCount,this._totalTasksCount,e))}catch(t){ge.Error("Error running progress callbacks."),ge.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 n=this._tasks.indexOf(i);n>-1&&this._tasks.splice(n,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(t){ge.Error("Error running tasks-done callbacks."),ge.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(n){i("Error executing task success callbacks",n)}},i=(n,s)=>{e._setErrorObject(n,s),this.onTaskError?this.onTaskError(e):e.onError||ge.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 yS{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}class bDt{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new O(1,1,1),this._newPosition=O.Zero(),this._centerPosition=O.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 n=0;n!0,this.displayLoadingUI=!0,this.loadAsync=(h,d)=>this.useAppend?bs.AppendAsync("file:",h,this._currentScene,d):bs.LoadAsync("file:",h,this._engine,d),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=n,this._additionalRenderLoopLogicCallback=s,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,n){const s=e.createReader(),a=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");s.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&&n()}):l.isDirectory&&this._traverseFolder(l,t,i,n);--i.count===0&&n()})}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=s)&&(bs.IsPluginForExtensionAvailable("."+n)&&(this._sceneFileToLoad=e[t]),V2e.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=[],n=e.dataTransfer?e.dataTransfer.items:null;for(let s=0;s{this._processFiles(t),s.count===0&&this._processReload()})}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){if(this._sceneFileToLoad)this.useAppend||this._currentScene&&(ge.errorsCount>0&&ge.ClearLogCache(),this._engine.stopRenderLoop()),bs.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}}ge.Error("Please provide a valid .babylon file.")}}}class G2e{dispose(){if(this._observers&&this._observables)for(let e=0;e{a.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?s=s.then(l=>(a.lastReturnValue=l,o.callback.apply(o.scope,[r,a]))):s=s.then(l=>(a.lastReturnValue=l,o.callback(r,a))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await s,r};class G_{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class nQ extends G_{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 n=0;nthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class cfe extends G_{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 sQ extends G_{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class aQ extends G_{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class oQ extends G_{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class Cet extends G_{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return this.onApply?this.onApply(e,t):!0}}class lQ extends G_{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class ufe extends G_{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class Zv extends G_{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Re))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 Zv._UpdateSelectionTree}static set UpdateSelectionTree(e){Zv._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const n=e.meshes.slice(0);let s=n.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,n=!0;for(let s=0;s{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,n){const s=new W2e(e,t||US.ModerateDegradationAllowed(),!1);return i&&s.onSuccessObservable.add(()=>{i()}),n&&s.onFailureObservable.add(()=>{n()}),s.start(),s}}let hfe=[];const K2e=(r,e)=>{r.doNotSerialize||(e.vertexData.push(r.serializeVerticeData()),hfe[r.id]=!0)},Aet=(r,e)=>{const t={},i=r._geometry;return i&&(r.getScene().getGeometryById(i.id)||K2e(i,e.geometries)),r.serialize&&r.serialize(t),t},CDt=(r,e)=>{if(r._isMesh){const t=r;if(t.delayLoadState===1||t.delayLoadState===0){const i=s=>{e.materials=e.materials||[],t.material&&!e.materials.some(a=>a.id===t.material.id)&&e.materials.push(s.serialize())};if(t.material&&!t.material.doNotSerialize)if(t.material instanceof Tf){if(e.multiMaterials=e.multiMaterials||[],!e.multiMaterials.some(s=>s.id===t.material.id)){e.multiMaterials.push(t.material.serialize());for(const s of t.material.subMaterials)s&&i(s)}}else i(t.material);else t.material||i(t.getScene().defaultMaterial);const n=t._geometry;n&&(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=[]),K2e(n,e.geometries)),t.skeleton&&!t.skeleton.doNotSerialize&&(e.skeletons=e.skeletons||[],e.skeletons.push(t.skeleton.serialize())),e.meshes=e.meshes||[],e.meshes.push(Aet(t,e))}}else if(r.getClassName()==="TransformNode"){const t=r;e.transformNodes.push(t.serialize())}else if(r.getClassName().indexOf("Camera")!==-1){const t=r;e.cameras.push(t.serialize())}else if(r.getClassName().indexOf("Light")!==-1){const t=r;e.lights.push(t.serialize())}};class m_{static ClearCache(){hfe=[]}static Serialize(e){return m_._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&be.ForceSerializeBuffers&&ge.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),m_.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 n,s;for(n=0;n0){i.animationGroups=[];for(let l=0;l0)for(i.reflectionProbes=[],n=0;nt)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=s)):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}else if(e instanceof Object){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const n=e[i];n instanceof Promise?t.push(n.then(s=>e[i]=s)):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}}}static SerializeMesh(e,t=!1,i=!1){const n={};if(n.meshes=[],n.transformNodes=[],n.cameras=[],n.lights=[],m_.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(a)<0&&!a.doNotSerialize&&e.push(a)}),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach(s=>{CDt(s,n)}),n}}class lU{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(!lU.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={...lU._DefaultOptions,...t};const n=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const s of this._options.audioTracks)n.addTrack(s);this._mediaRecorder=new MediaRecorder(n,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=s=>this._handleDataAvailable(s),this._mediaRecorder.onerror=s=>this._handleError(s),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,n)=>{this._resolve=i,this._reject=n})}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&&Ie.Download(e,this._fileName)}}lU._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let by=null;function EV(r,e,t,i,n="image/png",s=!1,a){const{height:o,width:l}=Tet(r,e,t);if(!(o&&l)){ge.Error("Invalid 'size' parameter !");return}by||(by=document.createElement("canvas")),by.width=l,by.height=o;const c=by.getContext("2d"),u=r.getRenderWidth()/r.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?TV(r,e,t,m=>{if(s){const _=new Blob([m]);Ie.DownloadBlob(_),i&&i("")}else i&&i(m)},n,1,r.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):r.onEndFrameObservable.addOnce(()=>{const m=r.getRenderingCanvas();c&&m&&c.drawImage(m,f,p,h,d),by&&(s?(Ie.EncodeScreenshotCanvasData(by,void 0,n,void 0,a),i&&i("")):Ie.EncodeScreenshotCanvasData(by,i,n,void 0,a))})}function H2e(r,e,t,i="image/png",n){return new Promise((s,a)=>{EV(r,e,t,o=>{typeof o<"u"?s(o):a(new Error("Data is undefined"))},i,void 0,n)})}function Eet(r,e,t,i,n="image/png",s){return new Promise(a=>{EV(r,e,{width:t,height:i},()=>{a()},n,!0,s)})}function TV(r,e,t,i,n="image/png",s=1,a=!1,o,l=!1,c=!1,u=!0,h,d){const{height:f,width:p,finalWidth:g,finalHeight:m}=Tet(r,e,t),_={width:p,height:f};if(!(f&&p)){ge.Error("Invalid 'size' parameter !");return}const y={width:r.getRenderWidth(),height:r.getRenderHeight()};r.setSize(p,f);const v=e.getScene(),x=new vn("screenShot",_,v,!1,!1,0,!1,be.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,s);x.renderList=v.meshes.slice(),x.samples=s,x.renderSprites=l,x.activeCamera=e,x.forceLayerMaskCheck=u,d==null||d(x);const b=()=>{x.isReadyForRendering()&&e.isReady(!0)?(r.onEndFrameObservable.addOnce(()=>{g===p&&m===f?x.readPixels(void 0,void 0,void 0,!1).then(A=>{eE(p,f,A,i,n,o,!0,void 0,h),x.dispose()}):vee("pass",x.getInternalTexture(),v,void 0,void 0,void 0,g,m).then(A=>{r._readTexturePixels(A,g,m,-1,0,null,!0,!1,0,0).then(E=>{eE(g,m,E,i,n,o,!0,void 0,h),A.dispose()})})}),v.incrementRenderId(),v.resetCachedMaterial(),x.render(!0),r.setSize(y.width,y.height),e.getProjectionMatrix(!0),v.render()):setTimeout(b,16)},C=()=>{v.incrementRenderId(),v.resetCachedMaterial(),b()};if(a){const A=new pT("antialiasing",1,v.activeCamera);x.addPostProcess(A),A.onEffectCreatedObservable.addOnce(E=>{E.isReady()?C():E.onCompiled=()=>{C()}})}else C()}function j2e(r,e,t,i="image/png",n=1,s=!1,a,o=!1,l=!1,c=!0,u){return new Promise((h,d)=>{TV(r,e,t,f=>{typeof f<"u"?h(f):d(new Error("Data is undefined"))},i,n,s,a,o,l,c,u)})}function Tet(r,e,t){let i=0,n=0,s=0,a=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,n=t.width*o):t.width&&!t.height?(n=t.width*o,i=Math.round(n/r.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,n=Math.round(i*r.getAspectRatio(e))):(n=Math.round(r.getRenderWidth()*o),i=Math.round(n/r.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(a=t.finalHeight,s=t.finalWidth):t.finalWidth&&!t.finalHeight?(s=t.finalWidth,a=Math.round(s/r.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(a=t.finalHeight,s=Math.round(a*r.getAspectRatio(e))):(s=n,a=i)}else isNaN(t)||(i=t,n=t,s=t,a=t);return n&&(n=Math.floor(n)),i&&(i=Math.floor(i)),s&&(s=Math.floor(s)),a&&(a=Math.floor(a)),{height:i|0,width:n|0,finalWidth:s|0,finalHeight:a|0}}const ADt={CreateScreenshot:EV,CreateScreenshotAsync:H2e,CreateScreenshotWithResizeAsync:Eet,CreateScreenshotUsingRenderTarget:TV,CreateScreenshotUsingRenderTargetAsync:j2e},SDt=()=>{Ie.CreateScreenshot=EV,Ie.CreateScreenshotAsync=H2e,Ie.CreateScreenshotUsingRenderTarget=TV,Ie.CreateScreenshotUsingRenderTargetAsync=j2e};SDt();var dfe;(function(r){r[r.Checkbox=0]="Checkbox",r[r.Slider=1]="Slider",r[r.Vector3=2]="Vector3",r[r.Quaternion=3]="Quaternion",r[r.Color3=4]="Color3",r[r.String=5]="String",r[r.Button=6]="Button",r[r.Options=7]="Options",r[r.Tab=8]="Tab",r[r.FileButton=9]="FileButton",r[r.Vector2=10]="Vector2"})(dfe||(dfe={}));class E9{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 i1e(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class ffe{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())}}ffe._Storage=ffe._GetStorage();class EDt{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,ot.AllowLoadingUniqueId=!0,this._savedJSON=m_.Serialize(e),ot.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=be.ForceSerializeBuffers;be.ForceSerializeBuffers=!1,ot.AllowLoadingUniqueId=!0;const t=m_.Serialize(this._trackedScene);ot.AllowLoadingUniqueId=!1;const i={};for(const n in t)this._compareCollections(n,this._savedJSON[n],t[n],i);return be.ForceSerializeBuffers=e,i}_compareArray(e,t,i,n){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)||(n[e]||(n[e]=[]),h.__state={id:u.id||u.name},n[e].push(h))}else{const u={__state:{deleteId:o.id||o.name}};n[e]||(n[e]=[]),n[e].push(u)}}for(let a=0;an.getShadowGenerators());for(const n of i)if(n){const s=n.values();for(let a=s.next();a.done!==!0;a=s.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 n in e){const s=e[n],a=i[n];if(Array.isArray(a)||n==="shadowGenerators")switch(n){case"cameras":this._ApplyDeltaForEntity(s,t,t.getCameraById.bind(t),o=>di.Parse(o,t));break;case"lights":this._ApplyDeltaForEntity(s,t,t.getLightById.bind(t),o=>Dr.Parse(o,t));break;case"shadowGenerators":this._ApplyDeltaForEntity(s,t,o=>this.GetShadowGeneratorById(t,o),o=>Qi.Parse(o,t));break;case"meshes":this._ApplyDeltaForEntity(s,t,t.getMeshById.bind(t),o=>Re.Parse(o,t,""));break;case"skeletons":this._ApplyDeltaForEntity(s,t,t.getSkeletonById.bind(t),o=>Ig.Parse(o,t));break;case"materials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),o=>tt.Parse(o,t,""));break;case"multiMaterials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),o=>Tf.Parse(o,t,""));break;case"transformNodes":this._ApplyDeltaForEntity(s,t,t.getTransformNodeById.bind(t),o=>Yt.Parse(o,t,""));break;case"particleSystems":this._ApplyDeltaForEntity(s,t,t.getParticleSystemById.bind(t),o=>$n.Parse(o,t,""));break;case"morphTargetManagers":this._ApplyDeltaForEntity(s,t,t.getMorphTargetById.bind(t),o=>L0.Parse(o,t));break;case"postProcesses":this._ApplyDeltaForEntity(s,t,t.getPostProcessByName.bind(t),o=>ii.Parse(o,t,""));break}else isNaN(a)?a.fromArray&&a.fromArray(s):i[n]=s}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const n=e[i],s=t[i];s!==void 0&&(!isNaN(s)||Array.isArray(s)?t[i]=n:s.fromArray?s.fromArray(n):typeof s=="object"&&s!==null&&this._ApplyPropertiesToEntity(n,s))}}static _ApplyDeltaForEntity(e,t,i,n){for(const s of e)if(s.__state&&s.__state.id!==void 0){const a=i(s.__state.id);a&&(this._ApplyPropertiesToEntity(s,a),ot.ParseProperties(s,a,t,null))}else if(s.__state&&s.__state.deleteId!==void 0){const a=i(s.__state.deleteId);a==null||a.dispose()}else n(s)}}var yw;(function(r){class e{serialize(){const n={},s=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((a,o)=>{s[a]=o}),n.characters=s,n.insertionCosts=this._insertionCosts,n.deletionCosts=this._deletionCosts,n.substitutionCosts=this._substitutionCosts,JSON.stringify(n)}static Deserialize(n){const s=JSON.parse(n),a=new e(s.characters);return a._insertionCosts=s.insertionCosts,a._deletionCosts=s.deletionCosts,a._substitutionCosts=s.substitutionCosts,a}constructor(n,s=null,a=null,o=null){s=s??(()=>1),a=a??(()=>1),o=o??((c,u)=>c===u?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(n.length),this._deletionCosts=new Array(n.length),this._substitutionCosts=new Array(n.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=s,this._characters=n.map(a=>this._alphabet.getCharacterIdx(a))}distance(n){return t._Distance(this,n)}static _Distance(n,s){const a=n._alphabet;if(a!==s._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=n._characters,l=s._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)),r.Sequence=t})(yw||(yw={}));class gs{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new gs(t._segmentLength);return i._points=t._points.map(n=>new O(n._x,n._y,n._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/O.Distance(this._points[t-1],e);for(let n=i();n<=1;n=i()){const s=this._points[t-1].scale(1-n);e.scaleAndAddToRef(n,s),this._points.push(s),++t}}}resampleAtTargetResolution(e){const t=new gs(this.getLength()/e);return this._points.forEach(i=>{t.add(i)}),t}tokenize(e){const t=[],i=new O;for(let n=2;n.98?!1:(O.CrossToRef(gs._ForwardDir,gs._InverseFromVec,gs._UpDir),gs._UpDir.normalize(),pe.LookAtLHToRef(e,t,gs._UpDir,gs._LookMatrix),i.subtractToRef(t,gs._FromToVec),gs._FromToVec.normalize(),O.TransformNormalToRef(gs._FromToVec,gs._LookMatrix,n),!0)}static _TokenizeSegment(e,t){gs._BestMatch=0,gs._Score=O.Dot(e,t[0]),gs._BestScore=gs._Score;for(let i=1;igs._BestScore&&(gs._BestMatch=i,gs._BestScore=gs._Score);return gs._BestMatch}}gs._ForwardDir=new O;gs._InverseFromVec=new O;gs._UpDir=new O;gs._FromToVec=new O;gs._LookMatrix=new pe;class cU{static Generate(e=64,t=256,i=.1,n=.001,s=[]){const l=new cU(e);for(let p=0;p(1-m)*p+m*g;for(let p=0;p{l.chars[g].subtractToRef(m,d),u=d.lengthSquared(),u>1e-6&&d.scaleAndAddToRef(1/(d.lengthSquared()*u),h)}),h.scaleInPlace(c),l.chars[g].addInPlace(h),l.chars[g].normalize()}return l}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new cU(t.length);for(let n=0;ne.serialize()))}static Deserialize(e,t){const i=new s_;return i._sequences=JSON.parse(e).map(n=>yw.Sequence.Deserialize(n,t)),i}static CreateFromTrajectory(e,t,i){return s_.CreateFromTokenizationPyramid(s_._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new s_;return i._sequences=e.map(n=>new yw.Sequence(n,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=s_._FINEST_DESCRIPTOR_RESOLUTION){const n=[];for(let s=i;s>4;s=Math.floor(s/2))n.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return n}distance(e){let t=0,i;for(let n=0;nt.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),n=new xw;return n._descriptors=i.descriptors.map(s=>s_.Deserialize(s,t)),n._centroidIdx=i.centroidIdx,n._averageDistance=i.averageDistance,n}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(n=>{e+=i.distance(n)}),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,xw._MIN_AVERAGE_DISTANCE))}}xw._MIN_AVERAGE_DISTANCE=1;class LZ{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 LZ;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=cU.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=yw.Alphabet.Deserialize(t.levenshteinAlphabet);for(let n=0;ns===0?0:1,s=>s===0?0:1,(s,a)=>Math.min(1-O.Dot(e.chars[s],e.chars[a]),1)),n=new LZ;return n._vector3Alphabet=e,n._levenshteinAlphabet=i,n}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new xw),this._nameToDescribedTrajectory.get(t).add(s_.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=s_.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach((o,l)=>{o.getMatchCost(t){const s=n.data;if(s.startsWith(uU._SERVER_PREFIX)){const a=s.substr(uU._SERVER_PREFIX.length);ge.Log(`[Reflector] Received server message: ${a.substr(0,64)}`),this._handleServerMessage(a);return}else ge.Log(`[Reflector] Received client message: ${s.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=n=>{ge.Log(`[Reflector] Disconnected ${n.code} ${n.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){switch(e){case"connected":{m_.SerializeAsync(this._scene).then(t=>{this._webSocket.send(`load|${JSON.stringify(t)}`)});break}}}_handleClientMessage(){}}uU._SERVER_PREFIX="$$";class ste{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new Ce,ste.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 TDt=1.5;class hv{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*TDt),t=new Float32Array(e);t.set(this._view),this._view=t}}const Cy=1800,MDt=24,RDt="0",ERe="timestamp",TRe="numPoints",IDt=/\r/g,wae="@";class _0{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=hn.Now-this._startingTimestamp,n=this.datasets.ids.length,s=this.datasets.startingIndices.itemLength;let a=0;if(s>0){const o=this.datasets.startingIndices.at(s-1);a=o+this.datasets.data.at(o+_0.NumberOfPointsOffset)+_0.SliceDataOffset}if(this.datasets.startingIndices.push(a),this.datasets.data.push(i),this.datasets.data.push(n),this.datasets.ids.forEach(o=>{const l=this._strategies.get(o);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const o=[i,n];for(let l=0;li.callback(this._datasetMeta,new jge(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 n=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)}}},s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:n,category:i}),s}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:n}of e){const s=t(this._scene);if(this._strategies.has(s.id)){s.dispose();continue}this.datasets.ids.push(s.id),i&&(i=i.replace(new RegExp(wae,"g"),"")),this._datasetMeta.set(s.id,{color:this._getHexColorFromId(s.id),category:i,hidden:n}),this._strategies.set(s.id,s)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let n=0;n>n&255;i+=(RDt+s.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=hn.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(n=>{const s=this._strategies.get(n);s&&this.datasetObservable.hasObservers()&&i.push(s.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const n=this._datasetMeta.get(e);n&&(n[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new hv(Cy),this.datasets.ids.length=0,this.datasets.startingIndices=new hv(Cy),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(IDt,"").split(` `).map(h=>h.split(",").filter(d=>d.length>0)).filter(h=>h.length>0),n=0,s=_0.NumberOfPointsOffset;if(i.length<2)return!1;const a={ids:[],data:new hv(Cy),startingIndices:new hv(Cy)},[o,...l]=i;if(o.length<2||o[n]!==ERe||o[s]!==TRe)return!1;const c=new Map;for(let h=_0.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+=`${ERe},${TRe}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const o0=()=>{};class PDt{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:o0}}}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 n=new ste;return n.observe("cpu"),n.onPressureChanged.add(s=>{var a;for(const o of s)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:()=>n.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:o0})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:o0})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:o0})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:o0})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:o0})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:o0})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add(()=>{e.getEngine()._drawCalls.fetchNewFrame()}),n=e.onAfterRenderObservable.add(()=>{t=e.getEngine()._drawCalls.current});return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(n)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:o0})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:o0})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:o0})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:o0})}static AbsoluteFpsStrategy(){return e=>{const t=new XUe(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:o0}}}static MeshesSelectionStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeActiveMeshesEvaluationObservable.add(()=>{t=hn.Now}),s=e.onAfterActiveMeshesEvaluationObservable.add(()=>{i=hn.Now-t});return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(n),e.onAfterActiveMeshesEvaluationObservable.remove(s)}}}}static RenderTargetsStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeRenderTargetsRenderObservable.add(()=>{t=hn.Now}),s=e.onAfterRenderTargetsRenderObservable.add(()=>{i=hn.Now-t});return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(n),e.onAfterRenderTargetsRenderObservable.remove(s)}}}}static ParticlesStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeParticlesRenderingObservable.add(()=>{t=hn.Now}),s=e.onAfterParticlesRenderingObservable.add(()=>{i=hn.Now-t});return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(n),e.onAfterParticlesRenderingObservable.remove(s)}}}}static SpritesStrategy(){return e=>{var a,o;let t=hn.Now,i=0;const n=(a=e.onBeforeSpritesRenderingObservable)==null?void 0:a.add(()=>{t=hn.Now}),s=(o=e.onAfterSpritesRenderingObservable)==null?void 0:o.add(()=>{i=hn.Now-t});return{id:"Sprites",getData:()=>i,dispose:()=>{var l,c;(l=e.onBeforeSpritesRenderingObservable)==null||l.remove(n),(c=e.onAfterSpritesRenderingObservable)==null||c.remove(s)}}}}static AnimationsStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeAnimationsObservable.add(()=>{t=hn.Now}),s=e.onAfterAnimationsObservable.add(()=>{i=hn.Now-t});return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterAnimationsObservable.remove(s)}}}}static PhysicsStrategy(){return e=>{var a,o;let t=hn.Now,i=0;const n=(a=e.onBeforePhysicsObservable)==null?void 0:a.add(()=>{t=hn.Now}),s=(o=e.onAfterPhysicsObservable)==null?void 0:o.add(()=>{i=hn.Now-t});return{id:"Physics",getData:()=>i,dispose:()=>{var l,c;(l=e.onBeforePhysicsObservable)==null||l.remove(n),(c=e.onAfterPhysicsObservable)==null||c.remove(s)}}}}static RenderStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeDrawPhaseObservable.add(()=>{t=hn.Now}),s=e.onAfterDrawPhaseObservable.add(()=>{i=hn.Now-t});return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(n),e.onAfterDrawPhaseObservable.remove(s)}}}}static FrameTotalStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeAnimationsObservable.add(()=>{t=hn.Now}),s=e.onAfterRenderObservable.add(()=>{i=hn.Now-t});return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterRenderObservable.remove(s)}}}}static InterFrameStrategy(){return e=>{let t=hn.Now,i=0;const n=e.onBeforeAnimationsObservable.add(()=>{i=hn.Now-t}),s=e.onAfterRenderObservable.add(()=>{t=hn.Now});return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(n),e.onAfterRenderObservable.remove(s)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new $Ue(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(t.gpuFrameTimeCounter.current*1e-6,0),dispose:()=>{t.dispose()}}}}}Ut.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new _0(this)),this._perfCollector};function wDt(r){const e=new Array,t=new Array,i=new Array,n=r.add(()=>{const a=e.length;for(let o=0;o{e.push(a),t.push(o),i.push(l)},dispose:()=>{r.remove(n)}}}Ce.prototype.runCoroutineAsync=function(r){if(!this._coroutineScheduler){const e=wDt(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return VJ(r,this._coroutineScheduler)};Ce.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const DDt="equirectangularPanoramaPixelShader",ODt=`#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 );}`;me.ShadersStore[DDt]=ODt;async function LDt(r,e){var a;const t=e.probe??new cT("tempProbe",e.size,r),i=!!e.probe;i||(e.position?t.position=e.position.clone():r.activeCamera&&(t.position=r.activeCamera.position.clone()));const n=e.meshesFilter?r.meshes.filter(e.meshesFilter):r.meshes;(a=t.renderList)==null||a.push(...n),t.refreshRate=vn.REFRESHRATE_RENDER_ONCE,t.cubeTexture.render();const s=new gHe("tempProceduralTexture","equirectangularPanorama",{width:e.size*2,height:e.size},r);return s.setTexture("cubeMap",t.cubeTexture),new Promise((o,l)=>{s.onGeneratedObservable.addOnce(()=>{const c=s.readPixels();if(!c){l(new Error("No Pixel Data found on procedural texture")),s.dispose(),i||t.dispose();return}c.then(u=>{s.dispose(),i||t.dispose(),e.filename?(eE(e.size*2,e.size,u,void 0,"image/png",e.filename),o(null)):o(u)})})})}class NDt{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t==null||t.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,n=this._currentOperation.then(i);return this._currentOperation=new Promise(s=>n.then(()=>s(),s)),n}static async LockAsync(e,t,i){if(i==null||i.throwIfAborted(),t.length===0)return await e();const n=new yS;let s=0;return t.forEach(a=>a.lockAsync(async()=>(s++,s===t.length&&n.resolve(await e()),n.promise),i).catch(o=>n.reject(o))),n.promise}}const Met="rgbdDecodePixelShader",Ret=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;me.ShadersStore[Met]=Ret;const Iet={name:Met,shader:Ret},Pet=Object.freeze(Object.defineProperty({__proto__:null,rgbdDecodePixelShader:Iet},Symbol.toStringTag,{value:"Module"})),wet="rgbdEncodePixelShader",Det=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;me.ShadersStore[wet]=Det;const Oet={name:wet,shader:Det},FDt=Object.freeze(Object.defineProperty({__proto__:null,rgbdEncodePixelShader:Oet},Symbol.toStringTag,{value:"Module"})),Let="rgbdDecodePixelShader",Net=`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);}`;me.ShadersStoreWGSL[Let]=Net;const Fet={name:Let,shader:Net},Bet=Object.freeze(Object.defineProperty({__proto__:null,rgbdDecodePixelShaderWGSL:Fet},Symbol.toStringTag,{value:"Module"})),ket="rgbdEncodePixelShader",Uet=`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);}`;me.ShadersStoreWGSL[ket]=Uet;const zet={name:ket,shader:Uet},BDt=Object.freeze(Object.defineProperty({__proto__:null,rgbdEncodePixelShaderWGSL:zet},Symbol.toStringTag,{value:"Module"})),Vet="copyTextureToTexturePixelShader",Get=`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 } `;me.ShadersStore[Vet]=Get;const Wet={name:Vet,shader:Get},kDt=Object.freeze(Object.defineProperty({__proto__:null,copyTextureToTexturePixelShader:Wet},Symbol.toStringTag,{value:"Module"})),Ket="copyTextureToTexturePixelShader",Het=`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 } `;me.ShadersStoreWGSL[Ket]=Het;const jet={name:Ket,shader:Het},UDt=Object.freeze(Object.defineProperty({__proto__:null,copyTextureToTexturePixelShaderWGSL:jet},Symbol.toStringTag,{value:"Module"}));var pfe;(function(r){r[r.ENTERING_XR=0]="ENTERING_XR",r[r.EXITING_XR=1]="EXITING_XR",r[r.IN_XR=2]="IN_XR",r[r.NOT_IN_XR=3]="NOT_IN_XR"})(pfe||(pfe={}));var mfe;(function(r){r[r.NOT_TRACKING=0]="NOT_TRACKING",r[r.TRACKING_LOST=1]="TRACKING_LOST",r[r.TRACKING=2]="TRACKING"})(mfe||(mfe={}));class qv extends nc{constructor(e,t={}){super(e),this.options=t,this._direction=new O(0,0,-1),this._mat=new pe,this._onSelectEnabled=!1,this._origin=new O(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new Ce,this._onHitTestResults=i=>{const n=i.map(s=>{const a=pe.FromArray(s.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||a.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&a.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),a),{xrHitResult:s,transformationMatrix:a}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(n)},this._onSelect=i=>{this._onSelectEnabled&&qv.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ie.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,n){return e.requestHitTest(t,i).then(s=>{const a=n||(o=>!!o.hitMatrix);return s.filter(a)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const n=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,n,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;pe.FromArrayToRef(t.transform.matrix,0,this._mat),O.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),O.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});qv.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}qv.Name=ln.HIT_TEST;qv.Version=1;Ea.AddWebXRFeature(qv.Name,(r,e)=>()=>new qv(r,e),qv.Version,!1);let zDt=0;class f5 extends nc{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 Ce,this.onAnchorRemovedObservable=new Ce,this.onAnchorUpdatedObservable=new Ce,this._tmpVector=new O,this._tmpQuaternion=new Oe,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 O,i=new Oe){this._populateTmpTransformation(t,i);const n=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 s=await e.xrHitResult.createAnchor(n);return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!0,xrTransformation:n,resolve:a,reject:o})})}catch(s){throw new Error(s)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new Oe,i=!1){this._populateTmpTransformation(e,t);const n=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}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(n,this._xrSessionManager.currentFrame):void 0;return new Promise((a,o)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:n,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(s=>!t.has(s.xrAnchor)).map(s=>this._trackedAnchors.indexOf(s));let n=0;i.forEach(s=>{const a=this._trackedAnchors.splice(s-n,1)[0];this.onAnchorRemovedObservable.notifyObservers(a),n++}),t.forEach(s=>{if(this._lastFrameDetected.has(s)){const a=this._findIndexInAnchorArray(s),o=this._trackedAnchors[a];try{this._updateAnchorWithXRFrame(s,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new Oe,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{Ie.Warn("Anchor could not be updated")}}else{const a={id:zDt++,xrAnchor:s,remove:()=>s.delete()},o=this._updateAnchorWithXRFrame(s,a,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const c=this._futureAnchors.filter(u=>u.nativeAnchor===s)[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(n=>{i.nativeAnchor=n},n=>{i.resolved=!0,i.reject(n)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new f5(r,e),f5.Version);let VDt=0;class p5 extends nc{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new Ce,this.onPlaneRemovedObservable=new Ce,this.onPlaneUpdatedObservable=new Ce,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 n=0;n{if(this._lastFrameDetected.has(n)){if(n.lastChangedTime===this._xrSessionManager.currentTimestamp){const s=this._findIndexInPlaneArray(n),a=this._detectedPlanes[s];this._updatePlaneWithXRPlane(n,a,e),this.onPlaneUpdatedObservable.notifyObservers(a)}}else{const s={id:VDt++,xrPlane:n,polygonDefinition:[]},a=this._updatePlaneWithXRPlane(n,s,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(s=>{const a=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new O(s.x,s.y,s.z*a)});const n=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(n){const s=t.transformationMatrix||new pe;pe.FromArrayToRef(n.transform.matrix,0,s),this._xrSessionManager.scene.useRightHandedSystem||s.toggleModelMatrixHandInPlace(),t.transformationMatrix=s,this._options.worldParentNode&&s.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),s)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new p5(r,e),p5.Version);class m5 extends nc{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new Ce}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)}}m5.Name=ln.BACKGROUND_REMOVER;m5.Version=1;Ea.AddWebXRFeature(m5.Name,(r,e)=>()=>new m5(r,e),m5.Version,!0);class GDt{}class g5 extends nc{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||Gi.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,n=bu("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});n.isVisible=this._debugMode,n.isPickable=!1,n.rotationQuaternion=new Oe;const s=e.grip||e.pointer;n.position.copyFrom(s.position),n.rotationQuaternion.copyFrom(s.rotationQuaternion);const a=new Gi(n,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:a,impostorMesh:n}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||ge.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(n=>{n._doNotLoadControllerMesh?this._createPhysicsImpostor(i):n.onModelLoadedObservable.addOnce(()=>{const s=new Gi(n.rootMesh,Gi.MeshImpostor,{mass:0,...this._options.physicsProperties}),a=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:s,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 Oe,this._tmpVector=new O,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:Gi.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=bu("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 Oe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Gi(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 n=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(n.x,n.y,n.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if((i=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&i.angularVelocity){const n=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(n.x,n.y,n.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(n=>{var c,u;const s=this._controllers[n],a=s.xrController.grip||s.xrController.pointer,o=s.oldPos||s.impostorMesh.position;if((c=s.xrController._lastXRPose)!=null&&c.linearVelocity){const h=s.xrController._lastXRPose.linearVelocity;this._tmpVector.set(h.x,h.y,h.z),s.impostor.setLinearVelocity(this._tmpVector)}else a.position.subtractToRef(o,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),s.impostor.setLinearVelocity(this._tmpVector);o.copyFrom(a.position),this._debugMode&&ge.Log([this._tmpVector,"linear"]);const l=s.oldRotation||s.impostorMesh.rotationQuaternion;if((u=s.xrController._lastXRPose)!=null&&u.angularVelocity){const h=s.xrController._lastXRPose.angularVelocity;this._tmpVector.set(h.x,h.y,h.z),s.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)))}s.impostor.setAngularVelocity(this._tmpVector)}l.copyFrom(a.rotationQuaternion),this._debugMode&&ge.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}g5.Name=ln.PHYSICS_CONTROLLERS;g5.Version=1;Ea.AddWebXRFeature(g5.Name,(r,e)=>()=>new g5(r,e),g5.Version,!0);class _5 extends nc{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new pe,this._tmpPos=new O,this._tmpQuat=new Oe,this._initHitTestSource=i=>{if(!i)return;const n=new XRRay(this.options.offsetRay||{}),s={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:n};if(this.options.entityTypes&&(s.entityTypes=this.options.entityTypes),!s.space){Ie.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(s).then(a=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=a})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new Ce,this.paused=!1,this.xrNativeFeatureName="hit-test",Ie.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(n=>{const s=n.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const a=s.transform.position,o=s.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),pe.FromFloat32ArrayToRefScaled(s.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:n};i.push(l)}),this.onHitTestResultObservable.notifyObservers(i)}}_5.Name=ln.HIT_TEST;_5.Version=2;Ea.AddWebXRFeature(_5.Name,(r,e)=>()=>new _5(r,e),_5.Version,!1);class v5 extends nc{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new Ce,this.onFeaturePointsUpdatedObservable=new Ce,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,n=[],s=[];for(let a=0;a0&&this.onFeaturePointsAddedObservable.notifyObservers(s),n.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(n)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}v5.Name=ln.FEATURE_POINTS;v5.Version=1;Ea.AddWebXRFeature(v5.Name,r=>()=>new v5(r),v5.Version);let WDt=0;class y5 extends nc{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new Ce,this.onMeshRemovedObservable=new Ce,this.onMeshUpdatedObservable=new Ce,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 n=new Set;this._detectedMeshes.forEach((s,a)=>{i.has(a)||n.add(a)}),n.forEach(s=>{const a=this._detectedMeshes.get(s);a&&(this.onMeshRemovedObservable.notifyObservers(a),this._detectedMeshes.delete(s))}),i.forEach(s=>{if(this._detectedMeshes.has(s)){if(s.lastChangedTime===this._xrSessionManager.currentTimestamp){const a=this._detectedMeshes.get(s);a&&(this._updateVertexDataWithXRMesh(s,a,e),this.onMeshUpdatedObservable.notifyObservers(a))}}else{const a={id:WDt++,xrMesh:s},o=this._updateVertexDataWithXRMesh(s,a,e);this._detectedMeshes.set(s,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){ge.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 s;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const n=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=n,t.normals=e.normals;else{t.positions=new Float32Array(n.length);for(let o=0;o()=>new y5(r,e),y5.Version,!1);var V1;(function(r){r[r.NotReceived=0]="NotReceived",r[r.Waiting=1]="Waiting",r[r.Received=2]="Received"})(V1||(V1={}));class x5 extends nc{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new Ce,this.onTrackableImageFoundObservable=new Ce,this.onTrackedImageUpdatedObservable=new Ce,this._trackableScoreStatus=V1.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,n)=>({image:i,widthInMeters:this.options.images[n].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return Ie.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===V1.Waiting)return;if(this._trackableScoreStatus===V1.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let n=!1;const s=i.index,a=this._trackedImages[s];if(!a)continue;a.xrTrackingResult=i,a.realWorldWidth!==i.measuredWidthInMeters&&(a.realWorldWidth=i.measuredWidthInMeters,n=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const u=a.transformationMatrix;pe.FromArrayToRef(o.transform.matrix,0,u),this._xrSessionManager.scene.useRightHandedSystem||u.toggleModelMatrixHandInPlace(),n=!0}const c=i.trackingState==="emulated";a.emulated!==c&&(a.emulated=c,n=!0),n&&this.onTrackedImageUpdatedObservable.notifyObservers(a)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==V1.NotReceived)return;this._trackableScoreStatus=V1.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=V1.NotReceived;return}for(let t=0;t0?V1.Received:V1.NotReceived}}x5.Name=ln.IMAGE_TRACKING;x5.Version=1;Ea.AddWebXRFeature(x5.Name,(r,e)=>()=>new x5(r,e),x5.Version,!1);class b5 extends nc{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ie.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 Ie.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 Ie.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}}}}b5.Name=ln.DOM_OVERLAY;b5.Version=1;Ea.AddWebXRFeature(b5.Name,(r,e)=>()=>new b5(r,e),b5.Version,!1);class Jv extends nc{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 Oe,this._tmpRotationMatrix=pe.Identity(),this._tmpTranslationDirection=new O,this._tmpMovementTranslation=new O,this._tempCacheQuaternion=new Oe,this._attachController=i=>{if(this._controllers[i.uniqueId])return;this._controllers[i.uniqueId]={xrController:i,registeredComponents:[]};const n=this._controllers[i.uniqueId];if(n.xrController.inputSource.targetRayMode==="tracked-pointer"&&n.xrController.inputSource.gamepad){const s=()=>{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};n.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?s():i.onMotionControllerInitObservable.addOnce(()=>{s()})}},!t||t.xrInput===void 0){Ie.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Jv.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,Oe.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 n=this._featureContext.orientationPreferredHandedness||"right",s=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)===n})||Object.keys(this._controllers)[0],a=this._controllers[s];Oe.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),((a==null?void 0:a.xrController.pointer.rotationQuaternion)||Oe.Identity()).multiplyToRef(this._tempCacheQuaternion,this._movementDirection)}else Oe.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(s=>{var a;return((a=this._controllers[s])==null?void 0:a.xrController.inputSource.handedness)===t})||Object.keys(this._controllers)[0],n=this._controllers[i];this._movementDirection.copyFrom((n==null?void 0:n.xrController.pointer.rotationQuaternion)||Oe.Identity())}(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(pe.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),O.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]}}}Jv.Name=ln.MOVEMENT;Jv.REGISTRATIONS={default:[{allowedComponentTypes:[wd.THUMBSTICK_TYPE,wd.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(r,e,t)=>{e.rotateX=Math.abs(r.x)>t.rotationThreshold?r.x:0,e.rotateY=Math.abs(r.y)>t.rotationThreshold?r.y:0}},{allowedComponentTypes:[wd.THUMBSTICK_TYPE,wd.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(r,e,t)=>{e.moveX=Math.abs(r.x)>t.movementThreshold?r.x:0,e.moveY=Math.abs(r.y)>t.movementThreshold?r.y:0}}]};Jv.Version=1;Ea.AddWebXRFeature(Jv.Name,(r,e)=>()=>new Jv(r,e),Jv.Version,!0);class C5 extends nc{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=O.Up().negateInPlace(),this._lightColor=Pe.White(),this._intensity=1,this._sphericalHarmonics=new Ux,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new Ce,this._updateReflectionCubeMap=()=>{var n;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const s=Date.now();if(s-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 qc("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new O(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=us.FALLOFF_GLTF),this._hdrFilter=new z_e(this._xrSessionManager.scene.getEngine()),Ie.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 Cn(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 C5(r,e),C5.Version,!1);class A5 extends nc{constructor(e){super(e),this.onEyeTrackingStartedObservable=new Ce,this.onEyeTrackingEndedObservable=new Ce,this.onEyeTrackingFrameUpdateObservable=new Ce,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new wr(O.Zero(),O.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;oe.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?O.RightHandedForwardReadOnly.rotateByQuaternionToRef(oe.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,oe.Quaternion[0].z*=-1,oe.Quaternion[0].w*=-1,O.LeftHandedForwardReadOnly.rotateByQuaternionToRef(oe.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))}}A5.Name=ln.EYE_TRACKING;A5.Version=1;Ea.AddWebXRFeature(A5.Name,r=>()=>new A5(r),A5.Version,!1);class KDt{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 HDt{constructor(){this._samples=new KDt(20),this._entropy=0,this.onFirstStepDetected=new Ce}update(e,t,i,n){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=Ne.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let a;for(a=this._samePointCheckStartIdx;ao&&(l=b,o=x);if(oa*this._squaredProjectionDistanceThreshold)return;const g=oe.Vector3[0];g.set(i,n,0);const m=oe.Vector3[1];m.set(u.x,u.y,0);const _=O.Cross(g,m).z>0,y=s.clone(),v=s.clone();c.subtractToRef(s,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:s,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 ik{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new HDt,this._walker=null,this._movement=new Ne,this._millisecondsSinceLastUpdate=ik._MillisecondsPerUpdate,this.movementThisFrame=O.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new jDt(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{ge.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>=ik._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=ik._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 cQ extends nc{static get Name(){return ln.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 O,this._forward=new O,this._position=new O,this._movement=new O,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&ge.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 ik(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,n=t.transform.matrix;this._up.copyFromFloats(n[4],n[5],i*n[6]),this._forward.copyFromFloats(n[8],n[9],i*n[10]),this._position.copyFromFloats(n[12],n[13],i*n[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||O.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}Ea.AddWebXRFeature(cQ.Name,(r,e)=>()=>new cQ(r,e),cQ.Version,!1);class $et extends G1e{constructor(e,t,i,n,s,a,o=null){super(e,t,i,n,a),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.isMultiview=s,this.createRTTProvider=a,this._originalInternalTexture=o}}class Xet extends iee{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new Ce,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),n=t=="right"?1:0,s=e.colorTextureWidth??e.textureWidth,a=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[n]||(i==null?void 0:i.textureWidth)!==s||(i==null?void 0:i.textureHeight)!==a){let o;const l=e.depthStencilTextureWidth??s,c=e.depthStencilTextureHeight??a;(s===l||a===c)&&(o=e.depthStencilTexture),this._renderTargetTextures[n]=this._createRenderTargetTexture(s,a,null,e.colorTexture,o,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[n],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[n]}_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,n=t.colorTextureHeight??t.textureHeight,s=t.viewport;e.x=s.x/i,e.y=s.y/n,e.width=s.width/i,e.height=s.height/n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class $Dt extends $et{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,n=>new XDt(n,i,this)),this.layer=e}}class XDt 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 MRe={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},YDt={};class S5 extends nc{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={...MRe,...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=YDt){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new W1e(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=MRe,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),n=new $Dt(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(n),n}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,n=this._existingLayers[0].layer.textureHeight,s={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:n,clearOnAccess:!0,...e.params};this._validateLayerInit(s,!1);const a=this._xrWebGLBinding.createQuadLayer(s);a.width=this._isMultiviewEnabled?1:2,a.height=1;const o=new $et(()=>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),n=i.layer,a={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)},o={x:0,y:0,z:0,w:1};n.transform=new XRRigidTransform(a,o);const l=this._layerToRTTProviderMapping.get(n);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 at(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 s={x:0,y:0,z:-10},a={x:0,y:0,z:0,w:1};i.transform=new XRRigidTransform(s,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 at(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 S5(r,e),S5.Version,!1);class E5 extends nc{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 _n(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 iT(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 Ce,this.xrNativeFeatureName="depth-sensing",Ie.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 n of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,n,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,n,this.depthDataFormat);break;default:Ie.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(n===null)return;const{data:s,width:a,height:o,rawValueToMeters:l,getDepthInMeters:c}=n;switch(this._width=a,this._height=o,this._rawValueToMeters=l,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(c.bind(n)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Vs.CreateRTexture(null,a,o,this._xrSessionManager.scene,!1,!0,be.NEAREST_SAMPLINGMODE,1)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(u=>u*l));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(u=>u*l));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(n===null)return;const{texture:s,width:a,height:o}=n;this._width=a,this._height=o,this._cachedWebGLTexture=s;const l=this._xrSessionManager.scene,u=l.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Vs.CreateRTexture(null,a,o,l,!1,!0,be.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 n=this.options.usagePreference.map(a=>{switch(a){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),s=this.options.dataFormatPreference.map(a=>{switch(a){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:n,dataFormatPreference:s}})}else i({})})}}E5.Name=ln.DEPTH_SENSING;E5.Version=1;Ea.AddWebXRFeature(E5.Name,(r,e)=>()=>new E5(r,e),E5.Version,!1);const QDt="velocityPixelShader",ZDt=`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 }`;me.ShadersStore[QDt]=ZDt;const qDt="velocityVertexShader",JDt=`#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 }`;me.ShadersStore[qDt]=JDt;class Yet extends vn{constructor(e,t,i,n=512){super("spacewarp rtt",n,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[pe.Identity(),pe.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 ua("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(s=>{this._previousWorldMatrices[s.uniqueId]=this._previousWorldMatrices[s.uniqueId]||s.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[s.uniqueId]),this._previousWorldMatrices[s.uniqueId]=s.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(n=>{this._originalPairing.push([n,n.material]),n.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(n=>{n[0].material=n[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 Qet{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,n,s){if(!this._engine)throw new Error("Engine is disposed");const a={width:e,height:t},o=new Yet(n,s,this._scene,a),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=n,l._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let n=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,a=e.motionVectorTextureHeight;return(!n||(i==null?void 0:i.textureWidth)!==s||(i==null?void 0:i.textureHeight)!=a)&&(n=this._createRenderTargetTexture(s,a,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,n),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a}),this._lastSubImages.set(t,e),n}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 T5 extends nc{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[ln.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 Qet(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)}}T5.Name=ln.SPACE_WARP;T5.Version=1;Ea.AddWebXRFeature(T5.Name,r=>()=>new T5(r),T5.Version,!1);class M5 extends nc{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new Ce,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},n=e.projectionMatrix,s=(1-n[8])*i.width/2+i.x,a=(1-n[9])*i.height/2+i.y,o=i.width/2*n[0],l=i.height/2*n[5],c=i.width/2*n[4];this.cameraIntrinsics[t]={u0:s,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 n,s;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(n=this._glBinding)==null?void 0:n.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(s=this._cachedInternalTextures[t]._hardwareTexture)==null||s.set(i);else{const a=new _n(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 iT(i,this._glContext),this._cachedInternalTextures[t]=a;const o=new Cn(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 n=!0;i.views.forEach((s,a)=>{n=n&&this._updateInternalTextures(s,a)}),n&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}M5.Name=ln.RAW_CAMERA_ACCESS;M5.Version=1;Ea.AddWebXRFeature(M5.Name,(r,e)=>()=>new M5(r,e),M5.Version,!1);class Zet extends lT{constructor(e,t,i){super(e,eOt[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(){}}Xl.RegisterController("generic-hand-select-grasp",(r,e)=>new Zet(e,r.gamepad,r.handedness));const eOt={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 e3 extends lT{constructor(e,t,i){super(e,tOt["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=e3.MODEL_LEFT_FILENAME:e=e3.MODEL_RIGHT_FILENAME;const i=e3.MODEL_BASE_URL+"default"+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=bs.IsPluginForExtensionAvailable(".glb");return e||ge.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 n=this._mapping.buttons[t],s=n.rootNodeName;if(!s){ge.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const a=this._getChildByName(this.rootMesh,s);if(!a){ge.Warn("Missing button mesh with name: "+s);return}if(n.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.valueNodeName),n.pressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.pressedNodeName),n.unpressedMesh=this._getImmediateChildByName(a,this._mapping.defaultButton.unpressedNodeName),n.valueMesh&&n.pressedMesh&&n.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(n,l.value)},void 0,!0)}else ge.Warn("Missing button submesh under mesh with name: "+s)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(n=>{if(!this.rootMesh)return;const s=this._mapping.axes[t][n],a=this._getChildByName(this.rootMesh,s.rootNodeName);if(!a){ge.Warn("Missing axis mesh with name: "+s.rootNodeName);return}s.valueMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(a,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=n==="x-axis"?o.x:o.y;this._lerpTransform(s,l,!0)},void 0,!0):ge.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new Re(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew e3(e,r.gamepad,r.handedness));const tOt={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 F0 extends lT{constructor(e,t,i,n=!1,s=!1){super(e,iOt[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=F0.MODEL_LEFT_FILENAME:e=F0.MODEL_RIGHT_FILENAME;const t=this._isQuest()?F0.QUEST_MODEL_BASE_URL:F0.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(n=>{const s=n&&this.getComponent(n);s&&s.onButtonStateChangedObservable.add(a=>{if(!(!this.rootMesh||this.disableAnimation))switch(n){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 Re(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Oe.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}}F0.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";F0.MODEL_LEFT_FILENAME="left.babylon";F0.MODEL_RIGHT_FILENAME="right.babylon";F0.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";Xl.RegisterController("oculus-touch",(r,e)=>new F0(e,r.gamepad,r.handedness));Xl.RegisterController("oculus-touch-legacy",(r,e)=>new F0(e,r.gamepad,r.handedness,!0));const iOt={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 uE extends lT{constructor(e,t,i){super(e,rOt[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=uE.MODEL_FILENAME,t=uE.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(n=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-n.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new Re(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=Oe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}uE.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";uE.MODEL_FILENAME="wand.babylon";Xl.RegisterController("htc-vive",(r,e)=>new uE(e,r.gamepad,r.handedness));const rOt={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 qet{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 n=this._xrTransform.orientation;return n.x=this._xrPoseVectorData[4],n.y=this._xrPoseVectorData[5],n.z=this._xrPoseVectorData[6],n.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")}}dUe("NativeXRFrame",qet);var gfe;(function(r){r[r.Input=0]="Input",r[r.Output=1]="Output"})(gfe||(gfe={}));class NZ{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Xh(),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=Ie.Instantiate(e.className),n=new i(e.name,e._connectionType,t);return n.deserialize(e),n}}class Io{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new Io(this.value+e.value)}subtract(e){return new Io(this.value-e.value)}multiply(e){return new Io(Math.imul(this.value,e.value))}divide(e){return new Io(this.value/e.value)}getClassName(){return Io.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Io(e.value)}}Io.ClassName="FlowGraphInteger";xe("FlowGraphInteger",Io);class ad{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new ad(e.typeName,e.defaultValue)}}const hi=new ad("any",void 0),Jet=new ad("string",""),Es=new ad("number",0),xc=new ad("boolean",!1),FZ=new ad("Vector2",Ne.Zero()),x_=new ad("Vector3",O.Zero()),ett=new ad("Vector4",It.Zero()),t3=new ad("Matrix",pe.Identity()),ttt=new ad("Color3",Pe.Black()),itt=new ad("Color4",new at(0,0,0,0)),rtt=new ad("Quaternion",Oe.Identity()),_o=new ad("FlowGraphInteger",new Io(0));function ntt(r){switch(typeof r){case"string":return Jet;case"number":return Es;case"boolean":return xc;case"object":return r instanceof Ne?FZ:r instanceof O?x_:r instanceof It?ett:r instanceof Pe?ttt:r instanceof at?itt:r instanceof Oe?rtt:r instanceof Io?_o:hi;default:return hi}}class BZ extends NZ{constructor(e,t,i,n){super(e,t,i),this.richType=n}_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=NZ.Parse(e,t);return i.richType=ad.Parse(e.richType),i}}xe("FGDataConnection",BZ);function stt(r){return r==="Mesh"||r==="AbstractMesh"||r==="GroundMesh"||r==="InstanceMesh"||r==="LinesMesh"||r==="GoldbergMesh"||r==="GreasedLineMesh"||r==="TrailMesh"}function att(r){return r==="Vector2"||r==="Vector3"||r==="Vector4"||r==="Quaternion"||r==="Color3"||r==="Color4"}function nOt(r,e){if(r==="Vector2")return Ne.FromArray(e);if(r==="Vector3")return O.FromArray(e);if(r==="Vector4")return It.FromArray(e);if(r==="Quaternion")return Oe.FromArray(e);if(r==="Color3")return new Pe(e[0],e[1],e[2]);if(r==="Color4")return new at(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${r}`)}function $2e(r,e,t){var n;const i=((n=e==null?void 0:e.getClassName)==null?void 0:n.call(e))??"";stt(i)?t[r]={name:e.name,className:i}:att(i)?t[r]={value:e.asArray(),className:i}:t[r]=e}function ate(r,e,t){const i=e[r];let n;const s=i==null?void 0:i.className;return stt(s)?n=t.getMeshByName(i.name):att(s)?n=nOt(s,i.value):s==="Matrix"?n=pe.FromArray(i.value):s===Io.ClassName?n=Io.Parse(i):i&&i.value!==void 0?n=i.value:n=i,n}function sOt(r){return r==="FGSetPropertyBlock"||r==="FGGetPropertyBlock"||r==="FGPlayAnimationBlock"||r==="FGMeshPickEventBlock"}class E3{constructor(e){var t;this.config=e,this.uniqueId=Xh(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new BZ(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new BZ(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=$2e){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 n={};i.serialize(n),e.dataInputs.push(n)}for(const i of this.dataOutputs){const n={};i.serialize(n),e.dataOutputs.push(n)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ie.Instantiate(e.className),n={},s=t.valueParseFunction??ate;if(e.config)for(const o in e.config)n[o]=s(o,e.config,t.scene);sOt(e.className)&&(n.pathConverter=t.pathConverter);const a=new i(n);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;s.type===Wt.POINTERPICK&&((a=s.pickInfo)!=null&&a.pickedMesh)&&(((o=s.pickInfo)==null?void 0:o.pickedMesh)===i||Y2e((l=s.pickInfo)==null?void 0:l.pickedMesh,i))&&this._execute(e)});const n=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",n)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),n=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(n),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return hE.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}hE.ClassName="FGMeshPickEventBlock";xe(hE.ClassName,hE);var _fe;(function(r){r[r.Stopped=0]="Stopped",r[r.Started=1]="Started"})(_fe||(_fe={}));class dE{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 UZ({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()===hE.ClassName){const i=t._getReferencedMesh();let n=0;for(;n0;){const n=t.pop();e(n);for(const s of n.dataInputs)for(const a of s._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId));if(n instanceof Ag)for(const s of n.signalOutputs)for(const a of s._connectedPoint)i.has(a._ownerBlock.uniqueId)||(t.push(a._ownerBlock),i.add(a._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const n={};i.serialize(n),e.allBlocks.push(n)}),e.executionContexts=[];for(const i of this._executionContexts){const n={};i.serialize(n,t),e.executionContexts.push(n)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const n of i.dataOutputs)if(n.uniqueId===t)return n;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 Ag){for(const n of i.signalInputs)if(n.uniqueId===t)return n}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),n=[],s=t.valueParseFunction??ate;for(const a of e.allBlocks){const o=E3.Parse(a,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:s});n.push(o),o instanceof vD&&i.addEventBlock(o)}for(const a of n){for(const o of a.dataInputs)for(const l of o.connectedPointIds){const c=dE.GetDataOutConnectionByUniqueId(n,l);o.connectTo(c)}if(a instanceof Ag)for(const o of a.signalOutputs)for(const l of o.connectedPointIds){const c=dE.GetSignalInConnectionByUniqueId(n,l);o.connectTo(c)}}for(const a of e.executionContexts)UZ.Parse(a,{graph:i,valueParseFunction:s});return i}}class zS{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(zS.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new dE({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=zS.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 n={};i.serialize(n,t),e._flowGraphs.push(n)})}static Parse(e,t){var s;const i=t.valueParseFunction??ate,n=new zS({scene:t.scene});return(s=e._flowGraphs)==null||s.forEach(a=>{dE.Parse(a,{coordinator:n,valueParseFunction:i,pathConverter:t.pathConverter})}),n}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new Ce,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}zS.SceneCoordinators=new Map;class aOt{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add(t=>{Ie.Log(`Node executed: ${t.getClassName()}`)})}}class Bp extends Ag{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class fE extends Bp{constructor(e){super(e),this.message=this.registerDataInput("message",hi)}_execute(e){const t=this.message.getValue(e);ge.Log(t),this.out._activateSignal(e)}getClassName(){return fE.ClassName}}fE.ClassName="FGConsoleLogBlock";xe(fE.ClassName,fE);class pE extends Bp{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,hi)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return pE.ClassName}}pE.ClassName="FGSetVariableBlock";xe(pE.ClassName,pE);const RRe=new RegExp(/\{(\w+)\}/g);class zZ{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=RRe.exec(e);for(;i;){const[,n]=i;this.templatedInputs.push(t.registerDataInput(n,_o)),i=RRe.exec(e)}}getAccessor(e,t){let i=this.path;for(const n of this.templatedInputs){const s=n.getValue(t).value;i=i.replace(`{${n.name}}`,s.toString())}return e.convert(i)}}class yD extends Bp{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",hi),this.templateComponent=new zZ(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 yD.ClassName}}yD.ClassName="FGSetPropertyBlock";xe("FGSetPropertyBlock",yD);class xD extends Bp{constructor(e){super(e),this.config=e;for(let t=0;tn.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return xD.ClassName}}xD.ClassName="FGSendCustomEventBlock";xe("FGSendCustomEventBlock",xD);class ott extends Ag{constructor(e){super(e),this.condition=this.registerDataInput("condition",xc),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"}}xe("FGBranchBlock",ott);class mE extends Bp{constructor(e={startIndex:new Io(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",_o),this.value=this.registerDataOutput("value",_o)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.valuen)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{const a=n-(s-i);this.timeRemaining.setValue(a,e)}}getClassName(){return"FGThrottleBlock"}}xe("FGThrottleBlock",ctt);class bD extends X2e{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Es)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],n=e.configuration.scene,s=new jUe({timeout:t,contextObservable:n.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],n=i.indexOf(e);n!==-1?i.splice(n,1):Ie.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 bD.ClassName}}bD.ClassName="FGTimerBlock";xe("FGTimerBlock",bD);class utt extends Ag{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",Es),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)s=0;else if(s>=this.config.numberOutputFlows&&!this.config.loop)return;if(n=n.filter(a=>a!==s),n.length===0)for(let a=0;a=0&&(i[n+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(n=>n)){this.out._activateSignal(e);for(let n=0;n=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}xe("FGDebounceBlock",ptt);class mtt extends Ag{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",xc)}_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"}}xe("FGFlipFlopBlock",mtt);class _E extends Ag{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")??[],n=i.indexOf(e);n!==-1&&i.splice(n,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 bw.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}bw.ClassName="FGPlayAnimationBlock";xe(bw.ClassName,bw);class gtt extends Bp{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",hi)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}xe("FGStopAnimationBlock",gtt);class _tt extends Bp{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",hi)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}xe("FGPauseAnimationBlock",_tt);class vtt extends E3{constructor(e){super(e),this.condition=this.registerDataInput("condition",xc),this.trueValue=this.registerDataInput("trueValue",hi),this.falseValue=this.registerDataInput("falseValue",hi),this.output=this.registerDataOutput("output",hi)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}xe("FGConditionalDataBlock",vtt);class vE extends E3{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,hi)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return vE.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}vE.ClassName="FGGetVariableBlock";xe(vE.ClassName,vE);class ytt extends E3{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",hi),this.destinationSystem=this.registerDataInput("destinationSystem",hi),this.inputCoordinates=this.registerDataInput("inputCoordinates",x_),this.outputCoordinates=this.registerDataOutput("outputCoordinates",x_)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),n=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),a=i.getWorldMatrix(),o=oe.Matrix[0].copyFrom(a);o.invert();const l=oe.Matrix[1];o.multiplyToRef(s,l);const c=this.outputCoordinates.getValue(e);O.TransformCoordinatesToRef(n,l,c)}getClassName(){return"FGCoordinateTransformBlock"}}xe("FGCoordinateTransformBlock",ytt);class xtt extends E3{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",ntt(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=$2e){super.serialize(e),t("value",this.config.value,e.config)}}xe("FGConstantBlock",xtt);class yE extends E3{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",hi),this.templateComponent=new zZ(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 yE.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}yE.ClassName="FGGetPropertyBlock";xe(yE.ClassName,yE);const IRe="cachedOperationValue",PRe="cachedExecutionId";class ote extends E3{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,PRe),i=e._getExecutionVariable(this,IRe);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const n=this._doOperation(e);e._setExecutionVariable(this,IRe,n),e._setExecutionVariable(this,PRe,e.executionId),this.value.setValue(n,e)}}}class yl extends ote{constructor(e,t,i,n,s,a){super(i,a),this._operation=n,this._className=s,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 ote{constructor(e,t,i,n,s){super(t,s),this._operation=i,this._className=n,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const CD="FGLogic",btt="AndBlock",Ctt="OrBlock",Att="NotBlock";class Stt extends yl{constructor(e){super(xc,xc,xc,(t,i)=>t&&i,`${CD}${btt}`,e)}}xe(`${CD}${btt}`,Stt);class Ett extends yl{constructor(e){super(xc,xc,xc,(t,i)=>t||i,`${CD}${Ctt}`,e)}}xe(`${CD}${Ctt}`,Ett);class Ttt extends ns{constructor(e){super(xc,xc,t=>!t,`${CD}${Att}`,e)}}xe(`${CD}${Att}`,Ttt);class MV extends ote{constructor(e,t,i,n){super(e,n),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Q2e extends ote{constructor(e,t,i,n,s,a,o){super(n,o),this._operation=s,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 tu(r){return r.getClassName?r.getClassName():""}function RV(r,e){return r==="Vector2"&&e==="Vector2"||r==="Vector3"&&e==="Vector3"||r==="Vector4"&&e==="Vector4"}function IV(r,e){return r==="Matrix"&&e==="Matrix"}function PV(r,e){return r==="FlowGraphInteger"&&e==="FlowGraphInteger"}class xE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicAdd(t,i),xE.ClassName,e)}_polymorphicAdd(e,t){const i=tu(e),n=tu(t);return RV(i,n)||IV(i,n)||PV(i,n)?e.add(t):e+t}}xE.ClassName="FGAddBlock";xe(xE.ClassName,xE);class bE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicAdd(t,i),bE.ClassName,e)}_polymorphicAdd(e,t){const i=tu(e),n=tu(t);return RV(i,n)||PV(i,n)?e.subtract(t):IV(i,n)?e.add(t.scale(-1)):e-t}}bE.ClassName="FGSubBlock";xe(bE.ClassName,bE);class CE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicMultiply(t,i),CE.ClassName,e)}_polymorphicMultiply(e,t){const i=tu(e),n=tu(t);return RV(i,n)||PV(i,n)?e.multiply(t):IV(i,n)?pe.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}}CE.ClassName="FGMultiplyBlock";xe(CE.ClassName,CE);class AE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicDivide(t,i),AE.ClassName,e)}_polymorphicDivide(e,t){const i=tu(e),n=tu(t);return RV(i,n)||PV(i,n)?e.divide(t):IV(i,n)?pe.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}}AE.ClassName="FGDivideBlock";xe(AE.ClassName,AE);class SE extends MV{constructor(e){super(Es,()=>Math.random(),SE.ClassName,e)}}SE.ClassName="FGRandomBlock";xe(SE.ClassName,SE);class EE extends yl{constructor(e){super(hi,hi,Es,(t,i)=>this._polymorphicDot(t,i),EE.ClassName,e)}_polymorphicDot(e,t){switch(tu(e)){case"Vector2":return Ne.Dot(e,t);case"Vector3":return O.Dot(e,t);case"Vector4":return It.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}EE.ClassName="FGDotBlock";xe(EE.ClassName,EE);class TE extends MV{constructor(e){super(Es,()=>Math.E,TE.ClassName,e)}}TE.ClassName="FGEBlock";xe(TE.ClassName,TE);class ME extends MV{constructor(e){super(Es,()=>Math.PI,ME.ClassName,e)}}ME.ClassName="FGPIBlock";xe(ME.ClassName,ME);class RE extends MV{constructor(e){super(Es,()=>Number.POSITIVE_INFINITY,RE.ClassName,e)}}RE.ClassName="FGInfBlock";xe(RE.ClassName,RE);class IE extends MV{constructor(e){super(Es,()=>Number.NaN,IE.ClassName,e)}}IE.ClassName="FGNaNBlock";xe(IE.ClassName,IE);function bo(r,e){switch(tu(r)){case"FlowGraphInteger":return new Io(e(r.value));case"Vector2":return new Ne(e(r.x),e(r.y));case"Vector3":return new O(e(r.x),e(r.y),e(r.z));case"Vector4":return new It(e(r.x),e(r.y),e(r.z),e(r.w));case"Matrix":return pe.FromValues(e(r.m[0]),e(r.m[4]),e(r.m[8]),e(r.m[12]),e(r.m[1]),e(r.m[5]),e(r.m[9]),e(r.m[13]),e(r.m[2]),e(r.m[6]),e(r.m[10]),e(r.m[14]),e(r.m[3]),e(r.m[7]),e(r.m[11]),e(r.m[15]));default:return e(r)}}class PE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicAbs(t),PE.ClassName,e)}_polymorphicAbs(e){return bo(e,Math.abs)}}PE.ClassName="FGAbsBlock";xe(PE.ClassName,PE);class wE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicSign(t),wE.ClassName,e)}_polymorphicSign(e){return bo(e,Math.sign)}}wE.ClassName="FGSignBlock";xe(wE.ClassName,wE);class DE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicTrunc(t),DE.ClassName,e)}_polymorphicTrunc(e){return bo(e,Math.trunc)}}DE.ClassName="FGTruncBlock";xe(DE.ClassName,DE);class OE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicFloor(t),OE.ClassName,e)}_polymorphicFloor(e){return bo(e,Math.floor)}}OE.ClassName="FGFloorBlock";xe(OE.ClassName,OE);class LE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicCeiling(t),LE.ClassName,e)}_polymorphicCeiling(e){return bo(e,Math.ceil)}}LE.ClassName="FGCeilBlock";xe(LE.ClassName,LE);class NE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicFract(t),NE.ClassName,e)}_polymorphicFract(e){return bo(e,t=>t-Math.floor(t))}}NE.ClassName="FGFractBlock";xe(NE.ClassName,NE);class FE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicNeg(t),FE.ClassName,e)}_polymorphicNeg(e){return bo(e,t=>-t)}}FE.ClassName="FGNegBlock";xe(FE.ClassName,FE);function wV(r,e,t){switch(tu(r)){case"FlowGraphInteger":return new Io(t(r.value,e.value));case"Vector2":return new Ne(t(r.x,e.x),t(r.y,e.y));case"Vector3":return new O(t(r.x,e.x),t(r.y,e.y),t(r.z,e.z));case"Vector4":return new It(t(r.x,e.x),t(r.y,e.y),t(r.z,e.z),t(r.w,e.w));case"Matrix":return pe.FromValues(t(r.m[0],e.m[0]),t(r.m[4],e.m[4]),t(r.m[8],e.m[8]),t(r.m[12],e.m[12]),t(r.m[1],e.m[1]),t(r.m[5],e.m[5]),t(r.m[9],e.m[9]),t(r.m[13],e.m[13]),t(r.m[2],e.m[2]),t(r.m[6],e.m[6]),t(r.m[10],e.m[10]),t(r.m[14],e.m[14]),t(r.m[3],e.m[3]),t(r.m[7],e.m[7]),t(r.m[11],e.m[11]),t(r.m[15],e.m[15]));default:return t(r,e)}}class BE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicRemainder(t,i),BE.ClassName,e)}_polymorphicRemainder(e,t){return wV(e,t,(i,n)=>i%n)}}BE.ClassName="FGRemainderBlock";xe(BE.ClassName,BE);class kE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicMin(t,i),kE.ClassName,e)}_polymorphicMin(e,t){return wV(e,t,Math.min)}}kE.ClassName="FGMinBlock";xe(kE.ClassName,kE);class UE extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicMax(t,i),UE.ClassName,e)}_polymorphicMax(e,t){return wV(e,t,Math.max)}}UE.ClassName="FGMaxBlock";xe(UE.ClassName,UE);function oOt(r,e,t){return Math.min(Math.max(r,Math.min(e,t)),Math.max(e,t))}function Mtt(r,e,t,i){switch(tu(r)){case"FlowGraphInteger":return new Io(i(r.value,e.value,t.value));case"Vector2":return new Ne(i(r.x,e.x,t.x),i(r.y,e.y,t.y));case"Vector3":return new O(i(r.x,e.x,t.x),i(r.y,e.y,t.y),i(r.z,e.z,t.z));case"Vector4":return new It(i(r.x,e.x,t.x),i(r.y,e.y,t.y),i(r.z,e.z,t.z),i(r.w,e.w,t.w));case"Matrix":return pe.FromValues(i(r.m[0],e.m[0],t.m[0]),i(r.m[4],e.m[4],t.m[4]),i(r.m[8],e.m[8],t.m[8]),i(r.m[12],e.m[12],t.m[12]),i(r.m[1],e.m[1],t.m[1]),i(r.m[5],e.m[5],t.m[5]),i(r.m[9],e.m[9],t.m[9]),i(r.m[13],e.m[13],t.m[13]),i(r.m[2],e.m[2],t.m[2]),i(r.m[6],e.m[6],t.m[6]),i(r.m[10],e.m[10],t.m[10]),i(r.m[14],e.m[14],t.m[14]),i(r.m[3],e.m[3],t.m[3]),i(r.m[7],e.m[7],t.m[7]),i(r.m[11],e.m[11],t.m[11]),i(r.m[15],e.m[15],t.m[15]));default:return i(r,e,t)}}class zE extends Q2e{constructor(e){super(hi,hi,hi,hi,(t,i,n)=>this._polymorphicClamp(t,i,n),zE.ClassName,e)}_polymorphicClamp(e,t,i){return Mtt(e,t,i,oOt)}}zE.ClassName="FGClampBlock";xe(zE.ClassName,zE);function lOt(r){return Math.min(Math.max(r,0),1)}class VE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicSaturate(t),VE.ClassName,e)}_polymorphicSaturate(e){return bo(e,lOt)}}VE.ClassName="FGSaturateBlock";xe(VE.ClassName,VE);class GE extends Q2e{constructor(e){super(hi,hi,hi,hi,(t,i,n)=>this._polymorphicInterpolate(t,i,n),GE.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return Mtt(e,t,i,this._interpolate)}}GE.ClassName="FGInterpolateBlock";xe(GE.ClassName,GE);class WE extends yl{constructor(e){super(hi,hi,xc,(t,i)=>this._polymorphicEq(t,i),WE.ClassName,e)}_polymorphicEq(e,t){const i=tu(e),n=tu(t);return RV(i,n)||IV(i,n)||PV(i,n)?e.equals(t):e===t}}WE.ClassName="FGEqBlock";xe(WE.ClassName,WE);function lte(r,e,t){const i=tu(r),n=tu(e);if(i===n){if(i==="")return t(r,e);if(i==="FlowGraphInteger")return t(r.value,e.value);throw new Error(`Cannot compare ${r} and ${e}`)}throw new Error(`${r} and ${e} are of different types.`)}class KE extends yl{constructor(e){super(hi,hi,xc,(t,i)=>this._polymorphicLessThan(t,i),KE.ClassName,e)}_polymorphicLessThan(e,t){return lte(e,t,(i,n)=>ithis._polymorphicLessThanOrEqual(t,i),DV.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return lte(e,t,(i,n)=>i<=n)}}DV.ClassName="FGLessThanOrEqualBlock";class HE extends yl{constructor(e){super(hi,hi,xc,(t,i)=>this._polymorphicGreaterThan(t,i),HE.ClassName,e)}_polymorphicGreaterThan(e,t){return lte(e,t,(i,n)=>i>n)}}HE.ClassName="FGGreaterThanBlock";xe(HE.ClassName,HE);class jE extends yl{constructor(e){super(hi,hi,xc,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),jE.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return lte(e,t,(i,n)=>i>=n)}}jE.ClassName="FGGreaterThanOrEqualBlock";xe(jE.ClassName,jE);class $E extends ns{constructor(e){super(hi,xc,t=>this._polymorphicIsNan(t),$E.ClassName,e)}_polymorphicIsNan(e){const t=tu(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}$E.ClassName="FGIsNanBlock";xe($E.ClassName,$E);class OV extends ns{constructor(e){super(hi,xc,t=>this._polymorphicIsInf(t),OV.ClassName,e)}_polymorphicIsInf(e){const t=tu(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}OV.ClassName="FGIsInfBlock";class XE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicDegToRad(t),XE.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return bo(e,this._degToRad)}}XE.ClassName="FGDegToRadBlock";xe(XE.ClassName,XE);class YE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicRadToDeg(t),YE.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return bo(e,this._radToDeg)}}YE.ClassName="FGRadToDegBlock";xe(YE.ClassName,YE);class QE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicSin(t),QE.ClassName,e)}_polymorphicSin(e){return bo(e,Math.sin)}}QE.ClassName="FGSinBlock";xe(QE.ClassName,QE);class ZE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicCos(t),ZE.ClassName,e)}_polymorphicCos(e){return bo(e,Math.cos)}}ZE.ClassName="FGCosBlock";xe(ZE.ClassName,ZE);class qE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicTan(t),qE.ClassName,e)}_polymorphicTan(e){return bo(e,Math.tan)}}qE.ClassName="FGTanBlock";xe(qE.ClassName,qE);class JE extends ns{constructor(e){super(hi,hi,t=>this._polymorphicAsin(t),JE.ClassName,e)}_polymorphicAsin(e){return bo(e,Math.asin)}}JE.ClassName="FGAsinBlock";xe(JE.ClassName,JE);class e6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicAcos(t),e6.ClassName,e)}_polymorphicAcos(e){return bo(e,Math.acos)}}e6.ClassName="FGAcosBlock";xe(e6.ClassName,e6);class t6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicAtan(t),t6.ClassName,e)}_polymorphicAtan(e){return bo(e,Math.atan)}}t6.ClassName="FGAtanBlock";xe(t6.ClassName,t6);class i6 extends yl{constructor(e){super(hi,hi,hi,(t,i)=>this._polymorphicAtan2(t,i),i6.ClassName,e)}_polymorphicAtan2(e,t){return wV(e,t,Math.atan2)}}i6.ClassName="FGAtan2Block";xe(i6.ClassName,i6);class r6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicSinh(t),r6.ClassName,e)}_polymorphicSinh(e){return bo(e,Math.sinh)}}r6.ClassName="FGSinhBlock";xe(r6.ClassName,r6);class n6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicCosh(t),n6.ClassName,e)}_polymorphicCosh(e){return bo(e,Math.cosh)}}n6.ClassName="FGCoshBlock";xe(n6.ClassName,n6);class s6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicTanh(t),s6.ClassName,e)}_polymorphicTanh(e){return bo(e,Math.tanh)}}s6.ClassName="FGTanhBlock";xe(s6.ClassName,s6);class a6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicAsinh(t),a6.ClassName,e)}_polymorphicAsinh(e){return bo(e,Math.asinh)}}a6.ClassName="FGAsinhBlock";xe(a6.ClassName,a6);class o6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicAcosh(t),o6.ClassName,e)}_polymorphicAcosh(e){return bo(e,Math.acosh)}}o6.ClassName="FGAcoshBlock";xe(o6.ClassName,o6);class l6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicAtanh(t),l6.ClassName,e)}_polymorphicAtanh(e){return bo(e,Math.atanh)}}l6.ClassName="FGAtanhBlock";xe(l6.ClassName,l6);class c6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicExp(t),c6.ClassName,e)}_polymorphicExp(e){return bo(e,Math.exp)}}c6.ClassName="FGExpBlock";xe(c6.ClassName,c6);class u6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicLog(t),u6.ClassName,e)}_polymorphicLog(e){return bo(e,Math.log)}}u6.ClassName="FGLogBlock";xe(u6.ClassName,u6);class h6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicLog2(t),h6.ClassName,e)}_polymorphicLog2(e){return bo(e,Math.log2)}}h6.ClassName="FGLog2Block";xe(h6.ClassName,h6);class d6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicLog10(t),d6.ClassName,e)}_polymorphicLog10(e){return bo(e,Math.log10)}}d6.ClassName="FGLog10Block";xe(d6.ClassName,d6);class f6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicSqrt(t),f6.ClassName,e)}_polymorphicSqrt(e){return bo(e,Math.sqrt)}}f6.ClassName="FGSqrtBlock";xe(f6.ClassName,f6);class p6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicCubeRoot(t),p6.ClassName,e)}_polymorphicCubeRoot(e){return bo(e,Math.cbrt)}}p6.ClassName="FGCubeRootBlock";xe(p6.ClassName,p6);class m6 extends yl{constructor(e){super(hi,Es,Es,(t,i)=>this._polymorphicPow(t,i),m6.ClassName,e)}_polymorphicPow(e,t){return wV(e,t,Math.pow)}}m6.ClassName="FGPowBlock";xe(m6.ClassName,m6);class g6 extends ns{constructor(e){super(hi,Es,t=>this._polymorphicLength(t),g6.ClassName,e)}_polymorphicLength(e){switch(tu(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}g6.ClassName="FGLengthBlock";xe(g6.ClassName,g6);class _6 extends ns{constructor(e){super(hi,hi,t=>this._polymorphicNormalize(t),_6.ClassName,e)}_polymorphicNormalize(e){switch(tu(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}_6.ClassName="FGNormalizeBlock";xe(_6.ClassName,_6);class v6 extends yl{constructor(e){super(x_,x_,x_,(t,i)=>O.Cross(t,i),v6.ClassName,e)}}v6.ClassName="FGCrossBlock";xe(v6.ClassName,v6);class y6 extends yl{constructor(e){super(FZ,Es,FZ,(t,i)=>Ne.Transform(t,pe.RotationZ(i)),y6.ClassName,e)}}y6.ClassName="FGRotate2DBlock";xe(y6.ClassName,y6);class x6 extends Q2e{constructor(e){super(x_,x_,Es,x_,(t,i,n)=>O.TransformCoordinates(t,pe.RotationAxis(i,n)),x6.ClassName,e)}}x6.ClassName="FGRotate3DBlock";xe(x6.ClassName,x6);class b6 extends ns{constructor(e){super(t3,t3,t=>pe.Transpose(t),b6.ClassName,e)}}b6.ClassName="FGTransposeBlock";xe(b6.ClassName,b6);class C6 extends ns{constructor(e){super(t3,Es,t=>t.determinant(),C6.ClassName,e)}}C6.ClassName="FGDeterminantBlock";xe(C6.ClassName,C6);class A6 extends ns{constructor(e){super(t3,t3,t=>pe.Invert(t),A6.ClassName,e)}}A6.ClassName="FGInvertMatrixBlock";xe(A6.ClassName,A6);class S6 extends yl{constructor(e){super(t3,t3,t3,(t,i)=>i.multiply(t),S6.ClassName,e)}}S6.ClassName="FGMatMulBlock";xe(S6.ClassName,S6);class E6 extends ns{constructor(e){super(_o,_o,t=>new Io(~t.value),E6.ClassName,e)}}E6.ClassName="FGBitwiseNotBlock";xe(E6.ClassName,E6);class T6 extends yl{constructor(e){super(_o,_o,_o,(t,i)=>new Io(t.value&i.value),T6.ClassName,e)}}T6.ClassName="FGBitwiseAndBlock";xe(T6.ClassName,T6);class M6 extends yl{constructor(e){super(_o,_o,_o,(t,i)=>new Io(t.value|i.value),M6.ClassName,e)}}M6.ClassName="FGBitwiseOrBlock";xe(M6.ClassName,M6);class R6 extends yl{constructor(e){super(_o,_o,_o,(t,i)=>new Io(t.value^i.value),R6.ClassName,e)}}R6.ClassName="FGBitwiseXorBlock";xe(R6.ClassName,R6);class I6 extends yl{constructor(e){super(_o,_o,_o,(t,i)=>new Io(t.value<new Io(t.value>>i.value),P6.ClassName,e)}}P6.ClassName="FGBitwiseRightShiftBlock";xe(P6.ClassName,P6);class w6 extends ns{constructor(e){super(_o,_o,t=>new Io(Math.clz32(t.value)),w6.ClassName,e)}}w6.ClassName="FGCountLeadingZerosBlock";xe(w6.ClassName,w6);class D6 extends ns{constructor(e){super(_o,_o,t=>new Io(t.value?31-Math.clz32(t.value&-t.value):32),D6.ClassName,e)}}D6.ClassName="FGCountTrailingZerosBlock";xe(D6.ClassName,D6);function cOt(r){let e=0;for(;r;)e+=r&1,r>>=1;return e}class O6 extends ns{constructor(e){super(_o,_o,t=>new Io(cOt(t.value)),O6.ClassName,e)}}O6.ClassName="FGCountOneBitsBlock";xe(O6.ClassName,O6);class AD extends vD{_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 AD.ClassName}}AD.ClassName="FGSceneReadyEventBlock";xe("FGSceneReadyEventBlock",AD);class L6 extends vD{constructor(e){super(e),this.config=e;for(let t=0;t{for(let n=0;n{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 N6.ClassName}}N6.ClassName="FGSceneTickEventBlock";xe(N6.ClassName,N6);const uOt=Object.freeze(Object.defineProperty({__proto__:null,AbstractActionManager:Rd,AbstractAssetTask:Kg,AbstractEngine:Qe,AbstractMesh:vr,AbstractScene:vo,AcquireNativeObjectAsync:hUe,Action:ws,ActionEvent:Ca,ActionManager:Fn,AddBlock:FHe,get AddressMode(){return Ehe},AdvancedTimer:jUe,AlignBlock:c$e,AlphaState:DBe,AmmoJSPlugin:ug,AnaglyphArcRotateCamera:E9e,AnaglyphFreeCamera:T9e,AnaglyphGamepadCamera:M9e,AnaglyphPostProcess:I1e,AnaglyphUniversalCamera:R9e,Analyser:Bvt,AndOrNotEvaluator:Yy,Angle:ng,Animatable:m1e,get AnimatedInputBlockTypes(){return J1},Animation:dt,AnimationAssetTask:yDt,AnimationEvent:UJ,AnimationGroup:Qm,AnimationGroupMask:Evt,get AnimationGroupMaskMode(){return Xue},get AnimationKeyInterpolation(){return $ue},AnimationPropertiesOverride:gvt,AnimationRange:QS,AnisotropyBlock:pV,ApplyLut:lHe,ApplyPostProcess:vee,Arc2:jBe,ArcFollowCamera:M1e,ArcRotateCamera:mn,ArcRotateCameraGamepadInput:kz,ArcRotateCameraInputsManager:QJ,ArcRotateCameraKeyboardMoveInput:Z0,ArcRotateCameraMouseWheelInput:nD,ArcRotateCameraPointersInput:nd,ArcRotateCameraVRDeviceOrientationInput:A1e,ArcTan2Block:ije,AssetContainer:Lz,get AssetTaskState(){return lfe},AssetsManager:xDt,AssetsProgressEvent:det,AsyncLock:NDt,AsyncLoop:lp,AttachToBoxBehavior:zvt,AudioEngine:o9e,AudioSceneComponent:Jh,get AutoLayoutMode(){return Fhe},AutoReleaseWorkerPool:cD,AutoRotationBehavior:f9e,AxesViewer:Dv,Axis:go,AxisDragGizmo:hp,AxisScaleGizmo:dp,BRDFTextureTools:xxt,BabylonFileLoaderConfiguration:ek,BackEase:XBe,BackgroundMaterial:Qr,BakedVertexAnimationManager:nT,BallAndSocketConstraint:R8t,BaseCameraMouseWheelInput:Fz,BaseCameraPointersInput:YJ,BaseError:ZS,BaseParticleSystem:El,BaseSixDofDragBehavior:Z1,BaseTexture:Cn,BasisFileInfo:iMt,BasisTools:Bee,BasisToolsOptions:a3,BasisTranscodeConfiguration:rMt,BezierCurve:HBe,BezierCurveEase:Avt,BiPlanarBlock:bje,BinaryFileAssetTask:get,BindBonesParameters:rc,BindFogParameters:ic,BindLight:Pz,BindLightProperties:r9e,BindLights:$u,BindLogDepth:Xo,BindMorphTargetParameters:Np,BindSceneUniformBuffer:tD,BindTextureMatrix:Ps,BlackAndWhitePostProcess:xV,get BlendFactor(){return Vhe},get BlendOperation(){return Ghe},BloomEffect:tfe,BloomMergePostProcess:ete,BlurPostProcess:Dl,Bone:ys,BoneAxesViewer:a4t,BoneIKController:af,BoneLookController:Tc,BonesBlock:_He,BooleanGeometryBlock:$ee,get BooleanGeometryOperations(){return ag},BounceEase:_vt,BouncingBehavior:vx,BoundingBlock:x$e,BoundingBox:Id,BoundingBoxGizmo:x_e,BoundingBoxRenderer:Eqe,BoundingInfo:vu,BoundingInfoHelper:Q3t,BoundingSphere:gg,BoxBlock:Vee,BoxBuilder:o4t,BoxParticleEmitter:Xv,Buffer:fl,get BufferBindingType(){return Phe},get BufferMapState(){return vhe},get BufferUsage(){return ts},CSG:Zm,Camera:di,CameraGizmo:o5,CameraInputTypes:eu,CameraInputsManager:Bz,CannonJSPlugin:MZ,get CanvasAlphaMode(){return qhe},CapsuleBlock:f2e,CapsuleBuilder:d4t,CascadedShadowGenerator:dc,ChromaticAberrationPostProcess:Gg,CircleEase:$Be,CircleOfConfusionPostProcess:fT,ClampBlock:Uee,ClearCoatBlock:lE,ClipPlanesBlock:DHe,ClipboardEventTypes:Mp,ClipboardInfo:eQ,CloudBlock:t2e,CloudPoint:UXe,Collider:Yz,Color3:Pe,Color3Gradient:RXe,Color4:at,ColorCorrectionPostProcess:bV,ColorCurves:aa,ColorGradient:D2e,ColorGradingTexture:bx,ColorMergerBlock:GHe,ColorSplitterBlock:L_e,get ColorWrite(){return zhe},CombineAction:cBe,get CompareFunction(){return Rhe},CompatibilityOptions:Mvt,get CompilationMessageType(){return Lhe},CompleteGreasedLineColorTable:Qje,CompleteGreasedLineWidthTable:Yje,get CompressionCodes(){return $1},get ComputeBindingType(){return fhe},ComputeEffect:iE,ComputeNormalsBlock:i$e,get ComputePassTimestampLocation(){return $he},ComputeShader:cg,ComputeShaderBoundingHelper:Kke,ComputeShaderParticleSystem:MXe,Condition:rw,ConditionBlock:x2e,get ConditionBlockTests(){return Hl},ConditionalBlock:vje,get ConditionalBlockConditions(){return nf},ConeDirectedParticleEmitter:mV,ConeParticleEmitter:fD,Constants:Fe,ContainerAssetTask:fet,get ConversionMode(){return ofe},ConvolutionPostProcess:Wg,get Coordinate(){return Que},CopyFloatData:e9e,CopyTextureToTexture:Oqe,CopyTools:kvt,CreateBox:jh,CreateBoxVertexData:lee,CreateCapsule:Qz,CreateCapsuleVertexData:uee,CreateCylinder:zu,CreateCylinderVertexData:oee,CreateDashedLines:fee,CreateDashedLinesVertexData:i_e,CreateDecal:_ee,CreateDecoderAsync:fHe,CreateDisc:lD,CreateDiscVertexData:hee,CreateEnvTextureAsync:oUe,CreateGeodesic:Xke,CreateGoldberg:Qke,CreateGoldbergVertexData:Yke,CreateGreasedLine:GRt,CreateGreasedLineMaterial:$je,CreateGround:aT,CreateGroundFromHeightMap:nee,CreateGroundFromHeightMapVertexData:H1e,CreateGroundVertexData:q1,CreateHemisphere:Jk,CreateIcoSphere:tV,CreateIcoSphereVertexData:gee,CreateImageBitmapFromSource:L1e,CreateImageDataArrayBufferViews:bee,CreateLathe:pee,CreateLineSystem:NS,CreateLineSystemVertexData:t_e,CreateLines:zs,CreatePlane:U_,CreatePlaneVertexData:Nz,CreatePolygon:Zz,CreatePolygonVertexData:r_e,CreatePolyhedron:sE,CreatePolyhedronVertexData:n_e,CreateResizedCopy:nUe,CreateRibbon:R_,CreateRibbonVertexData:Y1e,CreateScreenshot:EV,CreateScreenshotAsync:H2e,CreateScreenshotUsingRenderTarget:TV,CreateScreenshotUsingRenderTargetAsync:j2e,CreateScreenshotWithResizeAsync:Eet,CreateSegmentedBoxVertexData:Hke,CreateSphere:bu,CreateSphereVertexData:cee,CreateText:Zke,CreateTextShapePaths:a_e,CreateTiledBox:q1e,CreateTiledBoxVertexData:Z1e,CreateTiledGround:ree,CreateTiledGroundVertexData:K1e,CreateTiledPlane:Q1e,CreateTiledPlaneVertexData:s5,CreateTorus:Pg,CreateTorusKnot:dee,CreateTorusKnotVertexData:J1e,CreateTorusVertexData:see,CreateTube:mee,CrossBlock:kHe,CubeMapToSphericalPolynomialTools:oT,CubeTexture:Za,CubeTextureAssetTask:yet,CubicEase:vvt,get CullMode(){return Uhe},CurrentScreenBlock:P_e,Curve3:A0,CurveBlock:Sje,get CurveBlockTypes(){return Qs},CustomBlock:UHe,CustomOptimization:Cet,CustomParticleEmitter:Yv,CustomProceduralTexture:gHe,CylinderBlock:d2e,CylinderBuilder:s4t,CylinderDirectedParticleEmitter:gV,CylinderParticleEmitter:pD,DDSTools:_s,DataBuffer:mg,DataReader:E9,DataStorage:ffe,Database:uh,DebugBlock:m$e,DebugLayer:nE,get DebugLayerTab(){return dhe},DecalBuilder:O4t,DecalMapConfiguration:dD,DecalMapDefines:Eje,Decode:i1e,DecodeBase64ToBinary:Ez,DecodeBase64ToString:OJ,DecodeBase64UrlToBinary:Jw,DecodeBase64UrlToString:d1e,DecodeFloat32:JKe,DecodeRunLength:cHe,DeepCopier:bc,DefaultCollisionCoordinator:Y9e,DefaultKTX2DecoderOptions:PUe,DefaultLoadingScreen:Lv,DefaultRenderingPipeline:Cc,Deferred:yS,DepthCullingState:o1e,DepthOfFieldBlurPostProcess:oU,DepthOfFieldEffect:rfe,get DepthOfFieldEffectBlurLevel(){return ife},DepthOfFieldMergePostProcess:iYe,DepthPeelingRenderer:p_,DepthPeelingSceneComponent:Mqe,DepthReducer:VVe,DepthRenderer:I_,DepthRendererSceneComponent:Tqe,DepthSortedParticle:BXe,DerivativeBlock:CHe,DesaturateBlock:mje,DetailMapConfiguration:z_,get DeviceInputEventType(){return Wue},get DeviceLostReason(){return Jhe},DeviceOrientationCamera:ZJ,DeviceSource:Kue,DeviceSourceManager:KBe,get DeviceType(){return ji},DirectionalLight:qc,DirectionalLightFrustumViewer:B4t,DiscBlock:p2e,DiscBuilder:p4t,DiscardBlock:xHe,DisplayPassPostProcess:tte,DistanceBlock:ZHe,DistanceConstraint:I8t,DistanceJoint:c4t,DivideBlock:HHe,DoNothingAction:$ge,DomManagement:I2t,DotBlock:zHe,DracoCompression:Ic,DrawWrapper:pl,get DualSenseInput(){return zue},get DualShockButton(){return nhe},get DualShockDpad(){return she},get DualShockInput(){return Uue},DualShockPad:y9e,DumpTools:a3t,DynamicFloat32Array:hv,DynamicTexture:Ep,get EXROutputType(){return e_},EasingFunction:Ja,EdgesRenderer:AV,Effect:Sr,EffectFallbacks:ha,EffectLayer:ed,EffectLayerSceneComponent:YUe,EffectRenderer:aD,EffectWrapper:_g,ElasticEase:yvt,ElbowBlock:xje,EncodeArrayBufferToBase64:Sz,EndsWith:yBe,Engine:Vt,EngineFactory:pxt,get EngineFormat(){return nde},EngineInstrumentation:$Ue,EngineStore:ei,EngineView:k4t,EnvironmentHelper:Vx,EnvironmentTextureTools:ayt,Epsilon:Ki,EquiRectangularCubeTexture:hw,EquiRectangularCubeTextureAssetTask:bet,ErrorCodes:B_,get ErrorFilter(){return ede},EventConstants:rT,EventState:jge,ExecuteCodeAction:uBe,ExitFullscreen:B1e,ExitPointerlock:k1e,ExponentialEase:YBe,ExrLoaderGlobalConfiguration:BS,ExternalTexture:d_e,ExtractHighlightsPostProcess:Jee,ExtrudePolygon:qz,ExtrudeShape:Jz,ExtrudeShapeCustom:eV,FactorGradient:O2e,FadeInOutBehavior:Vvt,get FeatureName(){return _he},get FileTools(){return _P},FileToolsOptions:ho,FilesInput:V2e,FilesInputStore:LS,get FilterMode(){return The},FilterPostProcess:CV,FlowGraph:dE,FlowGraphAbsBlock:PE,FlowGraphAcosBlock:e6,FlowGraphAcoshBlock:o6,FlowGraphAddBlock:xE,FlowGraphAsinBlock:JE,FlowGraphAsinhBlock:a6,FlowGraphAtan2Block:i6,FlowGraphAtanBlock:t6,FlowGraphAtanhBlock:l6,FlowGraphBitwiseAndBlock:T6,FlowGraphBitwiseLeftShiftBlock:I6,FlowGraphBitwiseNotBlock:E6,FlowGraphBitwiseOrBlock:M6,FlowGraphBitwiseRightShiftBlock:P6,FlowGraphBitwiseXorBlock:R6,FlowGraphBlock:E3,FlowGraphBranchBlock:ott,FlowGraphCeilBlock:LE,FlowGraphClampBlock:zE,FlowGraphConditionalDataBlock:vtt,FlowGraphConnection:NZ,get FlowGraphConnectionType(){return gfe},FlowGraphConsoleLogBlock:fE,FlowGraphConstantBlock:xtt,FlowGraphContext:UZ,FlowGraphContextLogger:aOt,FlowGraphCoordinateTransformBlock:ytt,FlowGraphCoordinator:zS,FlowGraphCosBlock:ZE,FlowGraphCoshBlock:n6,FlowGraphCountLeadingZerosBlock:w6,FlowGraphCountOneBitsBlock:O6,FlowGraphCountTrailingZerosBlock:D6,FlowGraphCounterBlock:ftt,FlowGraphCrossBlock:v6,FlowGraphCubeRootBlock:p6,FlowGraphDataConnection:BZ,FlowGraphDebounceBlock:ptt,FlowGraphDegToRadBlock:XE,FlowGraphDeterminantBlock:C6,FlowGraphDivideBlock:AE,FlowGraphDoNBlock:mE,FlowGraphDotBlock:EE,FlowGraphEBlock:TE,FlowGraphEqBlock:WE,FlowGraphEventBlock:vD,FlowGraphExecutionBlock:Ag,FlowGraphExpBlock:c6,FlowGraphFlipFlopBlock:mtt,FlowGraphFloorBlock:OE,FlowGraphForLoopBlock:ltt,FlowGraphFractBlock:NE,FlowGraphGetPropertyBlock:yE,FlowGraphGetVariableBlock:vE,FlowGraphGreaterThanBlock:HE,FlowGraphGreaterThanOrEqualBlock:jE,FlowGraphInfBlock:RE,FlowGraphInterpolateBlock:GE,FlowGraphInvertMatrixBlock:A6,FlowGraphIsInfBlock:OV,FlowGraphIsNanBlock:$E,FlowGraphLengthBlock:g6,FlowGraphLessThanBlock:KE,FlowGraphLessThanOrEqualBlock:DV,FlowGraphLog10Block:d6,FlowGraphLog2Block:h6,FlowGraphLogBlock:u6,FlowGraphLogicAndBlock:Stt,FlowGraphLogicNotBlock:Ttt,FlowGraphLogicOrBlock:Ett,FlowGraphMatMulBlock:S6,FlowGraphMaxBlock:UE,FlowGraphMeshPickEventBlock:hE,FlowGraphMinBlock:kE,FlowGraphMultiGateBlock:utt,FlowGraphMultiplyBlock:CE,FlowGraphNaNBlock:IE,FlowGraphNegBlock:FE,FlowGraphNormalizeBlock:_6,FlowGraphPauseAnimationBlock:_tt,FlowGraphPiBlock:ME,FlowGraphPlayAnimationBlock:bw,FlowGraphPowBlock:m6,FlowGraphRadToDegBlock:YE,FlowGraphRandomBlock:SE,FlowGraphReceiveCustomEventBlock:L6,FlowGraphRemainderBlock:BE,FlowGraphRotate2DBlock:y6,FlowGraphRotate3DBlock:x6,FlowGraphSaturateBlock:VE,FlowGraphSceneReadyEventBlock:AD,FlowGraphSceneTickEventBlock:N6,FlowGraphSendCustomEventBlock:xD,FlowGraphSequenceBlock:_E,FlowGraphSetPropertyBlock:yD,FlowGraphSetVariableBlock:pE,FlowGraphSignBlock:wE,FlowGraphSignalConnection:kZ,FlowGraphSinBlock:QE,FlowGraphSinhBlock:r6,FlowGraphSqrtBlock:f6,get FlowGraphState(){return _fe},FlowGraphStopAnimationBlock:gtt,FlowGraphSubtractBlock:bE,FlowGraphSwitchBlock:htt,FlowGraphTanBlock:qE,FlowGraphTanhBlock:s6,FlowGraphThrottleBlock:ctt,FlowGraphTimerBlock:bD,FlowGraphTransposeBlock:b6,FlowGraphTruncBlock:DE,FlowGraphWaitAllBlock:dtt,FlowGraphWhileLoopBlock:gE,FluidRenderer:rte,FluidRendererSceneComponent:Lqe,get FluidRenderingDebug(){return sfe},FluidRenderingObject:z2e,FluidRenderingObjectCustomParticles:Dqe,FluidRenderingObjectParticleSystem:wqe,FluidRenderingTargetRenderer:afe,FlyCamera:sD,FlyCameraInputsManager:g9e,FlyCameraKeyboardInput:b3,FlyCameraMouseInput:Uz,FogBlock:PHe,FollowBehavior:Hvt,FollowCamera:Uu,FollowCameraInputsManager:_9e,FollowCameraKeyboardMoveInput:kc,FollowCameraMouseWheelInput:ib,FollowCameraPointersInput:sd,FragCoordBlock:AHe,FragDepthBlock:MHe,FragmentOutputBlock:Ov,FramingBehavior:Vh,FreeCamera:ql,FreeCameraDeviceOrientationInput:S1e,FreeCameraGamepadInput:Wz,FreeCameraInputsManager:Gz,FreeCameraKeyboardMoveInput:Pf,FreeCameraMouseInput:zz,FreeCameraMouseWheelInput:q0,FreeCameraTouchInput:Vz,FreeCameraVirtualJoystickInput:E1e,FresnelBlock:XHe,FresnelParameters:eU,FromHalfFloat:jm,get FrontFace(){return khe},FrontFacingBlock:bHe,Frustum:lf,FxaaPostProcess:pT,GIRSM:Mwt,GIRSMManager:nte,GIRSMRenderPluginMaterial:yp,GPUParticleSystem:vf,GPUPicker:_3t,GUID:ovt,Gamepad:Zl,GamepadCamera:qJ,GamepadManager:x9e,GamepadSystemSceneComponent:b9e,GaussianSplattingMaterial:pw,GaussianSplattingMesh:$v,GenerateBase64StringFromPixelData:XJ,GenerateBase64StringFromTexture:b1e,GenerateBase64StringFromTextureAsync:C1e,GenericPad:m9e,GeodesicData:iV,Geometry:ul,GeometryArcTan2Block:b$e,GeometryBufferRenderer:dn,GeometryBufferRendererSceneComponent:uYe,GeometryClampBlock:Xee,GeometryCollectionBlock:A2e,GeometryCrossBlock:R$e,GeometryCurveBlock:w2e,get GeometryCurveBlockTypes(){return jr},GeometryDesaturateBlock:I$e,GeometryDistanceBlock:D$e,GeometryDotBlock:O$e,GeometryElbowBlock:t$e,GeometryInfoBlock:g$e,GeometryInputBlock:jo,GeometryLengthBlock:L$e,GeometryLerpBlock:C$e,GeometryModBlock:T$e,GeometryNLerpBlock:A$e,GeometryOptimizeBlock:Gee,GeometryOutputBlock:s2e,GeometryPosterizeBlock:P$e,GeometryPowBlock:M$e,GeometryReplaceColorBlock:w$e,GeometryRotate2dBlock:N$e,GeometrySmoothStepBlock:E$e,GeometryStepBlock:S$e,GeometryTextureBlock:I2e,GeometryTextureFetchBlock:P2e,GeometryTransformBlock:T2e,GeometryTrigonometryBlock:E2e,get GeometryTrigonometryBlockOperations(){return xn},GetClass:Sa,GetClassName:b2t,GetDOMTextContent:Az,GetEnvInfo:xee,GetEnvironmentBRDFTexture:oV,GetExrHeader:tHe,GetFogState:WJ,GetFontOffset:O1e,GetInternalFormatFromBasisFormat:jKe,GetPointsCount:Xje,GetTGAHeader:uV,GetTextureDataAsync:sUe,Gizmo:Aa,get GizmoAnchorPoint(){return uhe},get GizmoCoordinatesMode(){return hhe},GizmoManager:mxt,GlowLayer:Wo,GoldbergMesh:rV,GradientBlock:lje,GradientBlockColorStep:tQ,GradientHelper:xd,GrainPostProcess:mT,GreasedLineBaseMesh:n2e,GreasedLineMaterialDefaults:_c,GreasedLineMesh:uc,get GreasedLineMeshColorDistribution(){return Nde},get GreasedLineMeshColorDistributionType(){return Rde},get GreasedLineMeshColorMode(){return Mde},get GreasedLineMeshMaterialType(){return Tde},get GreasedLineMeshWidthDistribution(){return Fde},GreasedLinePluginMaterial:D_,get GreasedLineRibbonAutoDirectionMode(){return Lde},get GreasedLineRibbonFacesMode(){return Ode},GreasedLineRibbonMesh:uo,get GreasedLineRibbonPointsMode(){return Dde},GreasedLineSimpleMaterial:r2e,GreasedLineTools:Xn,GridBlock:u2e,GroundBuilder:f3t,GroundMesh:oD,HDRCubeTexture:Cg,HDRCubeTextureAssetTask:xet,HDRFiltering:z_e,HDRTools:mCt,Halton2DSequence:zje,HandConstraintBehavior:jvt,get HandConstraintOrientation(){return Jue},get HandConstraintVisibility(){return ehe},get HandConstraintZone(){return que},get HandPart(){return ude},HandleFallbacksForShadows:Bl,HardwareScalingOptimization:cfe,HavokPlugin:k8t,HeightToNormalBlock:dV,HemisphereBuilder:gxt,HemisphericLight:Tp,HemisphericParticleEmitter:_V,HighlightLayer:_u,HighlightsPostProcess:K8t,Hinge2Joint:h4t,HingeConstraint:P8t,HingeJoint:u4t,HtmlElementTexture:Fee,HufUncompress:aHe,IWebXRControllerPhysicsOptions:GDt,IblShadowsRenderPipeline:Q5t,IcoSphereBlock:l2e,IcoSphereBuilder:T4t,ImageAssetTask:_et,ImageProcessingBlock:Z_e,ImageProcessingConfiguration:Gr,ImageProcessingPostProcess:ite,ImageSourceBlock:U0,IncrementValueAction:aBe,get IndexFormat(){return Khe},InputBlock:Br,get InspectableType(){return dfe},InstancedLinesMesh:e_e,InstancedMesh:W0,InstancesBlock:vHe,InstantiateBlock:h$e,InstantiateLinearBlock:d$e,InstantiateOnFacesBlock:M2e,InstantiateOnVerticesBlock:Kee,InstantiateOnVolumeBlock:Hee,InstantiateRadialBlock:f$e,InstantiatedEntries:a9e,IntFloatConverterBlock:p$e,InterleaveScalar:$_e,InternalTexture:_n,get InternalTextureSource(){return Lue},InterpolateValueAction:gBe,IntersectionInfo:mZ,IsBase64DataUrl:Mz,IsDocumentAvailable:OS,IsFileURL:h1e,IsNavigatorAvailable:ex,IsWindowObjectExist:dl,IsWrapper:kJ,get JoystickAxis(){return the},KeepAssets:s9e,KeyboardEventTypes:Rg,KeyboardInfo:pZ,KeyboardInfoPre:Bue,KhronosTextureContainer:fh,KhronosTextureContainer2:As,LatheBuilder:A4t,Layer:wee,LayerSceneComponent:QUe,LengthBlock:qHe,LensFlare:Dee,LensFlareSystem:jv,LensFlareSystemSceneComponent:vVe,LensFlaresOptimization:oQ,LensRenderingPipeline:lIt,LerpBlock:KHe,Light:Dr,LightBlock:OZ,LightGizmo:b0,LightInformationBlock:yHe,LineEdgesRenderer:Rqe,LinesBuilder:v4t,LinesMesh:vg,LoadFile:s3,LoadFileError:sw,LoadImage:qw,LoadImageConfiguration:Nue,get LoadOp(){return Yhe},LoadTextureFromTranscodeResult:PZ,LockConstraint:D8t,Logger:ge,get MapMode(){return yhe},MapRangeBlock:Jje,MappingBlock:R2e,get MappingTypes(){return sg},Material:tt,MaterialAnisotropicDefines:SUe,MaterialClearCoatDefines:CUe,MaterialDefines:Kn,MaterialDetailMapDefines:W9e,MaterialFlags:lt,MaterialGreasedLineDefines:Tje,MaterialHelper:ia,MaterialIridescenceDefines:AUe,MaterialPluginBase:Yu,get MaterialPluginEvent(){return Ede},MaterialPluginManager:Pv,MaterialSheenDefines:EUe,MaterialSubSurfaceDefines:TUe,MathBlock:y2e,get MathBlockOperations(){return dh},Matrix:pe,MatrixBuilderBlock:_je,MatrixComposeBlock:_$e,MatrixDeterminantBlock:Cje,MatrixTransposeBlock:Aje,MaxBlock:YHe,MergeGeometryBlock:C2e,MergeMeshesOptimization:Zv,Mesh:Re,MeshAssetTask:pet,MeshAttributeExistsBlock:i2e,get MeshAttributeExistsBlockTypes(){return Sde},MeshBlock:o2e,MeshBuilder:Cd,get MeshDebugMode(){return Ide},MeshDebugPluginMaterial:Jl,MeshExploder:bDt,MeshLODLevel:n9e,MeshParticleEmitter:Yee,MeshUVSpaceRenderer:z1,MeshoptCompression:n_,MinBlock:QHe,MinMaxReducer:zVe,get MipmapFilterMode(){return Mhe},MirrorTexture:Hv,ModBlock:gje,ModelShape:Gde,MorphTarget:xx,MorphTargetManager:L0,MorphTargetsBlock:Q_e,MotionBlurPostProcess:ob,MotorEnabledJoint:X1e,MultiMaterial:Tf,MultiObserver:G2e,MultiPointerScaleBehavior:Wvt,MultiRenderTarget:r_,MultiplyBlock:TZ,NLerpBlock:cje,NativeDataStream:zx,NativeEngine:aE,get NativePointerInput(){return kue},NativeXRFrame:qet,NativeXRLayerRenderTargetTextureProvider:$9e,NativeXRLayerWrapper:j9e,NativeXRRenderTarget:X9e,NegateBlock:JHe,Node:Dn,NodeGeometry:Sd,NodeGeometryBlock:ur,get NodeGeometryBlockConnectionPointTypes(){return _e},NodeGeometryBuildState:Zje,NodeGeometryConnectionPoint:Ude,get NodeGeometryConnectionPointCompatibilityStates(){return Bde},get NodeGeometryConnectionPointDirection(){return kde},get NodeGeometryContextualSources(){return On},NodeMaterial:Yn,NodeMaterialBlock:Li,get NodeMaterialBlockConnectionPointMode(){return Cde},get NodeMaterialBlockConnectionPointTypes(){return re},get NodeMaterialBlockTargets(){return Ee},NodeMaterialConnectionPoint:oE,get NodeMaterialConnectionPointCompatibilityStates(){return ade},NodeMaterialConnectionPointCustomObject:ka,get NodeMaterialConnectionPointDirection(){return ode},NodeMaterialDefines:A9,get NodeMaterialModes(){return ah},NodeMaterialOptimizer:zMt,get NodeMaterialSystemValues(){return Hr},NodeMaterialTeleportInBlock:LHe,NodeMaterialTeleportOutBlock:NHe,NoiseBlock:e$e,NoiseProceduralTexture:iU,NormalBlendBlock:hje,NormalizeBlock:VHe,NormalizeVectorBlock:n$e,NullBlock:qje,NullEngine:Jke,NullEngineOptions:qke,Observable:Ce,Observer:qFe,OcclusionMaterial:BAt,Octree:rE,OctreeBlock:Qk,OctreeSceneComponent:$1e,OimoJSPlugin:fde,OnAfterEnteringVRObservableEvent:m3t,OneMinusBlock:q_e,get Orientation(){return jue},OutlineRenderer:vw,PBRAnisotropicConfiguration:sb,PBRBaseMaterial:an,PBRBaseSimpleMaterial:Ah,PBRClearCoatConfiguration:Ll,PBRIridescenceConfiguration:Cu,PBRMaterial:ui,PBRMaterialDefines:ide,PBRMetallicRoughnessBlock:Fl,PBRMetallicRoughnessMaterial:P_,PBRSheenConfiguration:em,PBRSpecularGlossinessMaterial:w_,PBRSubSurfaceConfiguration:da,PHI:cl,PadNumber:bBe,PanoramaToCubeMapTools:C3,ParseFloat16:qKe,ParseFloat32:hh,ParseInt32:dg,ParseInt64:ZKe,ParseNullTerminatedString:DZ,ParseUint16:tU,ParseUint32:y_,ParseUint8:hV,ParseUint8Array:H_e,ParseValue:eHe,Particle:gw,ParticleBlendMultiplyBlock:O_e,ParticleHelper:cE,ParticleRampGradientBlock:D_e,ParticleSystem:$n,ParticleSystemSet:o3,ParticleTextureBlock:w_e,ParticlesOptimization:lQ,PassCubePostProcess:R1e,PassPostProcess:J0,Path2:eD,Path3D:qS,PathCursor:Svt,PerfCollectionStrategy:PDt,PerfCounter:zo,PerformanceConfigurator:jl,PerformanceMonitor:P1e,PerformanceViewerCollector:_0,PerturbNormalBlock:hD,PhotoDome:lw,Physics6DoFConstraint:eYe,Physics6DoFLimit:M8t,get PhysicsActivationControl(){return Zde},PhysicsAggregate:tYe,PhysicsBody:Zee,PhysicsConstraint:A3,get PhysicsConstraintAxis(){return Hde},get PhysicsConstraintAxisLimitMode(){return Kde},get PhysicsConstraintMotorType(){return Xde},get PhysicsConstraintType(){return jde},PhysicsEngine:G_e,PhysicsEngineV2:Qee,get PhysicsEventType(){return Yde},PhysicsHelper:z8t,PhysicsImpostor:Gi,PhysicsJoint:cs,get PhysicsMaterialCombineMode(){return qde},get PhysicsMotionType(){return Qde},get PhysicsPrestepType(){return f_},PhysicsRadialExplosionEventOptions:d5,get PhysicsRadialImpulseFalloff(){return Jde},PhysicsRaycastResult:cV,PhysicsShape:tm,PhysicsShapeBox:B2e,PhysicsShapeCapsule:N2e,PhysicsShapeContainer:S8t,PhysicsShapeConvexHull:C8t,PhysicsShapeCylinder:F2e,PhysicsShapeGroundMesh:T8t,PhysicsShapeHeightField:E8t,PhysicsShapeMesh:A8t,PhysicsShapeSphere:L2e,get PhysicsShapeType(){return $de},PhysicsUpdraftEventOptions:k2e,get PhysicsUpdraftMode(){return efe},PhysicsViewer:F4t,PhysicsVortexEventOptions:U2e,PickingInfo:wl,get PipelineErrorReason(){return Nhe},PivotTools:Bn,Plane:Dc,PlaneBlock:a2e,PlaneBuilder:Gvt,PlaneDragGizmo:a5,PlaneRotationGizmo:O0,PlayAnimationAction:oBe,PlaySoundAction:hBe,get PointColor(){return Wde},PointLight:bg,PointParticleEmitter:vV,PointerDragBehavior:Kl,PointerEventTypes:Wt,PointerInfo:ap,PointerInfoBase:p1e,PointerInfoPre:WBe,get PointerInput(){return dr},PointsCloudSystem:y8t,PointsGroup:rQ,Polar:m0,Polygon:x4t,PolygonBuilder:b4t,PolygonMeshBuilder:jke,PolyhedronBuilder:E4t,PolyhedronData:xZ,PositionGizmo:Eee,PositionNormalTextureVertex:c_e,PositionNormalVertex:l_e,PostProcess:ii,PostProcessManager:Xk,PostProcessRenderEffect:sn,PostProcessRenderPipeline:V_,PostProcessRenderPipelineManager:pYe,PostProcessRenderPipelineManagerSceneComponent:mYe,PostProcessesOptimization:aQ,PosterizeBlock:aje,PowBlock:eje,PowerEase:xvt,get PowerPreference(){return ghe},PrePassOutputBlock:IHe,PrePassRenderer:hc,PrePassRendererSceneComponent:Iqe,PrePassTextureBlock:OHe,PrecisionDate:hn,PredicateCondition:tBe,Predictor:j_e,PrepareAttributesForBakedVertexAnimation:iD,PrepareAttributesForBones:Ch,PrepareAttributesForInstances:Do,PrepareAttributesForMorphTargets:Iz,PrepareAttributesForMorphTargetsInfluencers:tb,PrepareDefinesForAttributes:xo,PrepareDefinesForBakedVertexAnimation:y1e,PrepareDefinesForBones:KJ,PrepareDefinesForCamera:$J,PrepareDefinesForFrameBoundValues:Mu,PrepareDefinesForLight:wz,PrepareDefinesForLights:Xu,PrepareDefinesForMergedUV:Is,PrepareDefinesForMisc:Tu,PrepareDefinesForMorphTargets:HJ,PrepareDefinesForMultiview:rD,PrepareDefinesForOIT:jJ,PrepareDefinesForPrePass:Dz,PrepareUniformsAndSamplersForLight:Oz,PrepareUniformsAndSamplersList:Qo,PressureObserverWrapper:ste,get PrimitiveTopology(){return Bhe},PrismaticConstraint:O8t,ProceduralTexture:Bu,ProceduralTextureSceneComponent:WUe,get PropertyTypeForEdition(){return lde},ProximityCastResult:G8t,PushAttributesForInstances:k_,PushMaterial:Va,QuadraticEase:g1e,QuadraticErrorSimplification:Hje,QuarticEase:bvt,Quaternion:Oe,get QueryType(){return Zhe},QueueNewFrame:u1e,QuinticEase:Cvt,RGBDTextureTools:Zk,RSMCreatePluginMaterial:cb,Ragdoll:F8t,RagdollBoneProperties:N8t,RandomBlock:b2e,get RandomBlockLocks(){return cf},RandomGUID:Xh,RandomNumberBlock:tje,RawCubeTexture:kee,RawTexture:Vs,RawTexture2DArray:Oee,RawTexture3D:NMt,Ray:wr,RayHelper:o_e,ReadFile:aw,ReadFileError:NJ,RecastJSCrowd:SXe,RecastJSPlugin:r8t,ReciprocalBlock:nje,ReflectBlock:fje,ReflectionBlock:dT,ReflectionProbe:cT,ReflectionTextureBaseBlock:dw,ReflectionTextureBlock:wHe,ReflectiveShadowMap:Ewt,Reflector:uU,RefractBlock:pje,RefractionBlock:ab,RefractionPostProcess:lb,RefractionTexture:Y_e,RegisterClass:xe,RegisterMaterialPlugin:u3t,RegisterNativeTypeAsync:dUe,RemapBlock:lV,get RenderPassTimestampLocation(){return Xhe},RenderTargetTexture:vn,RenderTargetWrapper:Kz,RenderTargetsOptimization:ufe,RenderingGroup:x0,RenderingGroupInfo:GBe,RenderingManager:Rc,ReplaceColorBlock:sje,RequestFile:BJ,RequestFileError:jk,RequestFullscreen:F1e,RequestPointerlock:JJ,ResizeImageBitmap:N1e,RetryStrategy:vBe,ReverseLutFromBitmap:rHe,RibbonBuilder:f4t,RichType:ad,RichTypeAny:hi,RichTypeBoolean:xc,RichTypeColor3:ttt,RichTypeColor4:itt,RichTypeFlowGraphInteger:_o,RichTypeMatrix:t3,RichTypeNumber:Es,RichTypeQuaternion:rtt,RichTypeString:Jet,RichTypeVector2:FZ,RichTypeVector3:x_,RichTypeVector4:ett,RollingAverage:N9e,Rotate2dBlock:dje,RotationGizmo:b_e,RotationXBlock:s$e,RotationYBlock:a$e,RotationZBlock:o$e,RuntimeAnimation:_Be,RuntimeError:Q0,SSAO2RenderingPipeline:Nl,SSAORenderingPipeline:gD,SSRRenderingPipeline:Ns,get SamplerBindingType(){return whe},Scalar:Xt,ScaleBlock:BHe,ScaleGizmo:C_e,ScalingBlock:l$e,ScanData:pHe,Scene:Ut,SceneComponentConstants:bt,SceneDepthBlock:fV,SceneInstrumentation:XUe,SceneLoader:bs,get SceneLoaderAnimationGroupLoadingMode(){return sde},SceneLoaderFlags:hl,SceneOptimization:G_,SceneOptimizer:W2e,SceneOptimizerOptions:US,get ScenePerformancePriority(){return Hue},SceneRecorder:EDt,SceneSerializer:m_,ScreenSizeBlock:SHe,ScreenSpaceBlock:EHe,ScreenSpaceCurvaturePostProcess:_D,ScreenSpaceReflectionPostProcess:Fp,ScreenshotTools:ADt,SerializationHelper:ot,SetBasisTranscoderWorker:oMt,SetColorsBlock:_2e,SetCorsBehavior:FJ,SetMaterialIDBlock:S2e,SetNormalsBlock:g2e,SetParentAction:Xge,SetPositionsBlock:m2e,SetStateAction:nBe,SetTangentsBlock:v2e,SetUVsBlock:Wee,SetValueAction:sBe,ShaderCodeInliner:Kv,get ShaderLanguage(){return pde},ShaderMaterial:ua,get ShaderStage(){return Ihe},ShaderStore:me,ShadowDepthWrapper:GMt,ShadowGenerator:Qi,ShadowGeneratorSceneComponent:GVe,ShadowLight:nb,ShadowMapBlock:RHe,ShadowsOptimization:sQ,ShapeBuilder:C4t,ShapeCastResult:W8t,SharpenPostProcess:gT,SheenBlock:hT,SimplexPerlin3DBlock:uje,SimplicationQueueSceneComponent:jje,SimplificationQueue:Kje,SimplificationSettings:BRt,get SimplificationType(){return wde},SineEase:_1e,SixDofDragBehavior:p9e,Size:Fu,Skeleton:Ig,SkeletonViewer:zh,SliderConstraint:w8t,SmartArray:Go,SmartArrayNoDuplicate:yv,SmoothStepBlock:rje,SolidParticle:Vde,SolidParticleSystem:v8t,SolidParticleVertex:kXe,Sound:vp,SoundTrack:l9e,get SourceTextureFormat(){return rde},get Space(){return Yue},SphereBlock:c2e,SphereBuilder:l4t,SphereDirectedParticleEmitter:yV,SphereParticleEmitter:mD,Spherical:g0,SphericalHarmonics:Ux,SphericalPolynomial:wg,SpotLight:Nc,SpringConstraint:L8t,Sprite:Lee,SpriteManager:hg,SpriteMap:cDt,SpritePackedManager:uDt,SpriteSceneComponent:wGe,Stage:Mo,StandardMaterial:ct,StandardMaterialDefines:K9e,StandardRenderingPipeline:Ln,StartsWith:xBe,StateCondition:iBe,get StencilOperation(){return Whe},StencilState:d_,StencilStateComposer:l1e,StepBlock:$He,StereoscopicArcRotateCamera:P9e,StereoscopicFreeCamera:w9e,StereoscopicGamepadCamera:D9e,StereoscopicInterlacePostProcess:Jvt,StereoscopicInterlacePostProcessI:I9e,StereoscopicScreenUniversalCamera:e3t,StereoscopicUniversalCamera:O9e,StickValues:$vt,StopAnimationAction:lBe,StopSoundAction:dBe,StorageBuffer:Q9,get StorageTextureAccess(){return Ohe},get StoreOp(){return Qhe},StringDictionary:fZ,StringTools:P2t,SubEmitter:Qv,get SubEmitterType(){return zde},SubMesh:yc,SubSurfaceBlock:fw,SubSurfaceSceneComponent:Pqe,SubtractBlock:jHe,SurfaceMagnetismBehavior:Kvt,SwitchBooleanAction:rBe,get SwitchInput(){return Gue},TAARenderingPipeline:S3,TBNBlock:uT,TGATools:WKe,Tags:fn,TargetCamera:$a,TargetedAnimation:QBe,TeleportInBlock:v$e,TeleportOutBlock:y$e,TestBase64DataUrl:LBe,TextFileAssetTask:met,Texture:be,get TextureAspect(){return Ahe},TextureAssetTask:vet,TextureBlock:rU,get TextureDimension(){return xhe},get TextureFormat(){return She},TextureOptimization:nQ,TexturePacker:N0,TexturePackerFrame:bde,get TextureSampleType(){return Dhe},TextureSampler:c1e,TextureTools:aUe,get TextureUsage(){return bhe},get TextureViewDimension(){return Che},ThinEngine:ir,ThinRenderTargetTexture:FMt,ThinTexture:Iv,TiledBoxBuilder:g4t,TiledPlaneBuilder:m4t,get TimerState(){return dde},TmpColors:En,TmpVectors:oe,ToGammaSpace:e5,ToHalfFloat:tg,ToLinearSpace:$9,TonemapPostProcess:LIt,get TonemappingOperator(){return nfe},Tools:Ie,TorusBlock:h2e,TorusBuilder:p3t,TorusKnotBuilder:_4t,TouchCamera:T1e,TrailMesh:aU,Trajectory:gs,TrajectoryClassifier:LZ,TranscodeAsync:IZ,get TranscodeTarget(){return l5},TransformBlock:EZ,TransformFeedbackBoundingHelper:wv,TransformNode:Yt,TranslationBlock:u$e,TriPlanarBlock:zee,TrigonometryBlock:N_e,get TrigonometryBlockOperations(){return ol},TubeBuilder:S4t,TwirlBlock:THe,UncompressPIZ:dHe,UncompressPXR:hHe,UncompressRAW:X_e,UncompressRLE:uHe,UncompressZIP:xde,UniformBuffer:Ci,UniversalCamera:rb,UnregisterAllMaterialPlugins:V1e,UnregisterMaterialPlugin:h3t,UploadContent:W_e,UploadEnvLevelsAsync:h_e,UploadEnvSpherical:Cee,UploadLevelsAsync:qk,UtilityLayerRenderer:Tn,VRCameraMetrics:sT,VRDeviceOrientationArcRotateCamera:V9e,VRDeviceOrientationFreeCamera:tee,VRDeviceOrientationGamepadCamera:G9e,VRDistortionCorrectionPostProcess:ahe,VRExperienceHelper:tE,VRMultiviewToSingleviewPostProcess:z9e,ValidatedNativeDataStream:fUe,ValueCondition:Gl,Vector2:Ne,Vector2ToFixed:Vje,Vector3:O,Vector3ToFixed:Gje,Vector4:It,Vector4ToFixed:Wje,VectorConverterBlock:r$e,VectorMergerBlock:J9,VectorSplitterBlock:WHe,VertexAnimationBaker:Uvt,VertexBuffer:ee,VertexData:vt,VertexDataMaterialInfo:Y9,get VertexFormat(){return Hhe},VertexOutputBlock:q9,get VertexStepMode(){return jhe},VideoDome:Pee,VideoRecorder:lU,VideoTexture:Zh,ViewDirectionBlock:J_e,Viewport:Yc,VirtualJoystick:Ui,VirtualJoysticksCamera:L9e,VolumetricLightScatteringPostProcess:wf,VoronoiNoiseBlock:yje,Wav2Decode:oHe,WaveBlock:oje,get WaveBlockKind(){return Ade},WebGL2ParticleSystem:TXe,WebGL2ShaderProcessor:VBe,WebGLDataBuffer:ow,WebGLHardwareTexture:iT,WebGLPipelineContext:RBe,WebGPUCacheBindGroups:vs,WebGPUCacheRenderPipeline:xa,WebGPUCacheRenderPipelineTree:S0,WebGPUCacheSampler:ix,WebGPUDataBuffer:yUe,WebGPUDrawContext:sV,WebGPUEngine:gr,WebGPURenderTargetWrapper:bUe,WebGPUTintWASM:Ad,WebRequest:oa,WebXRAbstractFeature:nc,WebXRAbstractMotionController:lT,WebXRAnchorSystem:f5,WebXRBackgroundRemover:m5,WebXRCamera:cw,WebXRControllerComponent:wd,WebXRControllerMovement:Jv,WebXRControllerPhysics:g5,WebXRControllerPointerSelection:yg,WebXRDefaultExperience:Iee,WebXRDefaultExperienceOptions:$xt,WebXRDepthSensing:E5,WebXRDomOverlay:b5,WebXREnterExitUI:Ree,WebXREnterExitUIButton:KUe,WebXREnterExitUIOptions:Hxt,WebXRExperienceHelper:Tee,WebXREyeTracking:A5,WebXRFeatureName:ln,WebXRFeaturePointSystem:v5,WebXRFeaturesManager:Ea,WebXRGenericHandController:Zet,WebXRGenericTriggerMotionController:uw,WebXRHTCViveMotionController:uE,WebXRHand:HUe,get WebXRHandJoint(){return hde},WebXRHandTracking:ls,WebXRHitTest:_5,WebXRHitTestLegacy:qv,WebXRImageTracking:x5,WebXRInput:GUe,WebXRInputSource:VUe,WebXRLayerRenderTargetTextureProvider:iee,WebXRLayers:S5,WebXRLightEstimation:C5,WebXRManagedOutputCanvas:H9e,WebXRManagedOutputCanvasOptions:$z,WebXRMeshDetector:y5,WebXRMicrosoftMixedRealityController:e3,WebXRMotionControllerManager:Xl,WebXRMotionControllerTeleportation:FS,get WebXRNearControllerMode(){return cde},WebXRNearInteraction:xg,WebXROculusTouchMotionController:F0,WebXRPlaneDetector:p5,WebXRProfiledMotionController:zUe,WebXRRawCameraAccess:M5,WebXRSessionManager:Xz,WebXRSpaceWarp:T5,WebXRSpaceWarpRenderTargetTextureProvider:Qet,get WebXRState(){return pfe},get WebXRTrackingState(){return mfe},WebXRWalkingLocomotion:cQ,WeightedSound:c9e,WorkerPool:IUe,WorleyNoise3DBlock:e2e,XRSpaceWarpRenderTarget:Yet,get Xbox360Button(){return ihe},get Xbox360Dpad(){return rhe},Xbox360Pad:v9e,get XboxInput(){return Vue},_BabylonLoaderRegistered:MCt,_BasisTextureLoader:$Ke,_CommonDispose:D1e,_CommonInit:w1e,_CreationDataStorage:x1e,_DDSTextureLoader:MUe,_ENVTextureLoader:RUe,_ExrTextureLoader:mHe,_GetCompatibleTextureLoader:LJ,_HDRTextureLoader:HKe,_InstancesBatch:Zue,_KTXTextureLoader:wUe,_MeshCollisionData:t9e,_OcclusionDataStorage:eUe,_PrimaryIsoTriangle:s_e,_TGATextureLoader:KKe,_TimeToken:rUe,_UpdateRGBDAsync:lUe,_forceSceneHelpersToBundle:Xxt,_forceTransformFeedbackToBundle:U4t,_injectLTSFileTools:NBe,_staticOffsetValueColor3:e1e,_staticOffsetValueColor4:t1e,_staticOffsetValueQuaternion:Qge,_staticOffsetValueSize:Jge,_staticOffsetValueVector2:qge,_staticOffsetValueVector3:Zge,addClipPlaneUniforms:Yo,allocateAndCopyTypedBuffer:gZ,anaglyphPixelShader:OZe,anaglyphPixelShaderWGSL:FZe,appendSceneAsync:Nxt,backgroundPixelShader:iKe,backgroundPixelShaderWGSL:pWe,backgroundVertexShader:TWe,backgroundVertexShaderWGSL:VGe,bilateralBlurPixelShader:Bqe,bilateralBlurPixelShaderWGSL:Yqe,bilateralBlurQualityPixelShader:zqe,bilateralBlurQualityPixelShaderWGSL:qqe,bindClipPlane:wo,blackAndWhitePixelShader:MZe,blackAndWhitePixelShaderWGSL:PZe,bloomMergePixelShader:rZe,bloomMergePixelShaderWGSL:aZe,bonesDeclaration:tke,bonesDeclarationWGSL:Eke,bonesVertex:gke,bonesVertexWGSL:zke,boundingBoxRendererPixelShader:yJe,boundingBoxRendererPixelShaderWGSL:EJe,boundingBoxRendererVertexShader:CJe,boundingBoxRendererVertexShaderWGSL:RJe,bumpFragment:kKe,bumpFragmentFunctions:NKe,bumpFragmentFunctionsWGSL:vKe,bumpFragmentMainFunctions:DKe,bumpFragmentMainFunctionsWGSL:mKe,bumpFragmentWGSL:bKe,captureEquirectangularFromScene:LDt,chromaticAberrationPixelShader:vYe,chromaticAberrationPixelShaderWGSL:GQe,circleOfConfusionPixelShader:ZQe,circleOfConfusionPixelShaderWGSL:eZe,className:lvt,clipPlaneFragment:oze,clipPlaneFragmentDeclaration:nze,clipPlaneFragmentDeclarationWGSL:Cze,clipPlaneFragmentWGSL:Eze,clipPlaneVertex:gze,clipPlaneVertexDeclaration:fze,clipPlaneVertexDeclarationWGSL:wze,clipPlaneVertexWGSL:Lze,colorCorrectionPixelShader:HZe,colorCorrectionPixelShaderWGSL:XZe,colorPixelShader:sKe,colorPixelShaderWGSL:k$e,colorVertexShader:lKe,colorVertexShaderWGSL:V$e,computeMaxExtents:VRt,convolutionPixelShader:UZe,convolutionPixelShaderWGSL:GZe,copyTextureToTexturePixelShader:Wet,copyTextureToTexturePixelShaderWGSL:jet,createDetailMapPlugin:YMt,createPBRAnisotropicPlugin:WMt,createPBRBRDFPlugin:KMt,createPBRClearCoatPlugin:HMt,createPBRIridescencePlugin:jMt,createPBRSheenPlugin:$Mt,createPBRSubSurfacePlugin:XMt,createYieldingScheduler:ZBe,defaultPixelShader:Pje,defaultPixelShaderWGSL:Fje,defaultVertexShader:Oje,defaultVertexShaderWGSL:Uje,depthBoxBlurPixelShader:SGe,depthBoxBlurPixelShaderWGSL:aGe,depthOfFieldMergePixelShader:HQe,depthOfFieldMergePixelShaderWGSL:XQe,depthPixelShader:FVe,depthPixelShaderWGSL:oJe,depthVertexShader:UVe,depthVertexShaderWGSL:uJe,displayPassPixelShader:mqe,displayPassPixelShaderWGSL:vqe,editableInPropertyPage:Fi,expandToProperty:Ke,extractHighlightsPixelShader:cZe,extractHighlightsPixelShaderWGSL:dZe,extractMinAndMax:JS,extractMinAndMaxIndexed:JBe,filterPixelShader:rqe,filterPixelShaderWGSL:aqe,fogFragmentDeclaration:QWe,fogFragmentDeclarationWGSL:lWe,fxaaPixelShader:mZe,fxaaPixelShaderWGSL:bZe,fxaaVertexShader:vZe,fxaaVertexShaderWGSL:SZe,geometryPixelShader:sYe,geometryPixelShaderWGSL:fJe,geometryVertexShader:lYe,geometryVertexShaderWGSL:gJe,getRichTypeFromValue:ntt,glowBlurPostProcessPixelShader:Xze,glowBlurPostProcessPixelShaderWGSL:sVe,glowMapGenerationPixelShader:uze,glowMapGenerationPixelShaderWGSL:Rze,glowMapGenerationVertexShader:yze,glowMapGenerationVertexShaderWGSL:Bze,glowMapMergePixelShader:zze,glowMapMergePixelShaderWGSL:Zze,glowMapMergeVertexShader:Kze,glowMapMergeVertexShaderWGSL:tVe,grainPixelShader:FQe,grainPixelShaderWGSL:UQe,helperFunctions:eze,helperFunctionsWGSL:gUe,highlightsPixelShader:cqe,highlightsPixelShaderWGSL:dqe,imageProcessingDeclaration:DWe,imageProcessingDeclarationWGSL:$Ge,imageProcessingFunctions:$We,imageProcessingFunctionsWGSL:sWe,imageProcessingPixelShader:PQe,imageProcessingPixelShaderWGSL:MQe,importAnimationsAsync:Bxt,inlineScheduler:Yk,kernelBlurPixelShader:eQe,kernelBlurPixelShaderWGSL:aQe,kernelBlurVertexShader:rQe,kernelBlurVertexShaderWGSL:cQe,layerPixelShader:lVe,layerPixelShaderWGSL:pVe,layerVertexShader:hVe,layerVertexShaderWGSL:_Ve,lensFlarePixelShader:bVe,lensFlarePixelShaderWGSL:MVe,lensFlareVertexShader:SVe,lensFlareVertexShaderWGSL:PVe,lightFragment:JWe,lightFragmentDeclaration:NWe,lightFragmentWGSL:hWe,lightUboDeclaration:kWe,lightUboDeclarationWGSL:QGe,lightVxFragmentDeclaration:_We,lightVxUboDeclaration:xWe,lightVxUboDeclarationWGSL:NGe,lightsFragmentFunctions:VWe,lightsFragmentFunctionsWGSL:JGe,linePixelShader:wJe,linePixelShaderWGSL:BJe,lineVertexShader:LJe,lineVertexShaderWGSL:zJe,loadAssetContainerAsync:Fxt,loadSceneAsync:Lxt,makeAsyncFunction:Tvt,makeSyncFunction:qBe,meshUVSpaceRendererFinaliserPixelShader:iXe,meshUVSpaceRendererFinaliserPixelShaderWGSL:xXe,meshUVSpaceRendererFinaliserVertexShader:sXe,meshUVSpaceRendererFinaliserVertexShaderWGSL:AXe,meshUVSpaceRendererMaskerPixelShader:J$e,meshUVSpaceRendererMaskerPixelShaderWGSL:_Xe,meshUVSpaceRendererMaskerVertexShader:Q$e,meshUVSpaceRendererMaskerVertexShaderWGSL:pXe,meshUVSpaceRendererPixelShader:$$e,meshUVSpaceRendererPixelShaderWGSL:hXe,meshUVSpaceRendererVertexShader:K$e,meshUVSpaceRendererVertexShaderWGSL:lXe,morphTargetsVertex:fke,morphTargetsVertexDeclaration:oke,morphTargetsVertexDeclarationWGSL:wke,morphTargetsVertexGlobal:uke,morphTargetsVertexGlobalDeclaration:nke,morphTargetsVertexGlobalDeclarationWGSL:Rke,morphTargetsVertexGlobalWGSL:Lke,morphTargetsVertexWGSL:Bke,motionBlurPixelShader:ZZe,motionBlurPixelShaderWGSL:eqe,nativeOverride:M_,normalizeEnvInfo:nV,outlinePixelShader:WJe,outlinePixelShaderWGSL:YJe,outlineVertexShader:jJe,outlineVertexShaderWGSL:qJe,packingFunctions:OVe,packingFunctionsWGSL:HVe,particlesPixelShader:GXe,particlesPixelShaderWGSL:YXe,particlesVertexShader:HXe,particlesVertexShaderWGSL:qXe,passCubePixelShader:dQe,passCubePixelShaderWGSL:vQe,passPixelShader:_Z,passPixelShaderWGSL:mQe,pbrPixelShader:VKe,pbrPixelShaderWGSL:SKe,pbrVertexShader:RKe,pbrVertexShaderWGSL:hKe,pickingPixelShader:q9e,pickingPixelShaderWGSL:Cke,pickingVertexShader:yke,pickingVertexShaderWGSL:Wke,postprocessVertexShader:S9e,postprocessVertexShaderWGSL:ZYe,prepareDefinesForClipPlanes:i9e,prepareStringDefinesForClipPlanes:x3,reflectionFunction:IWe,reflectionFunctionWGSL:KGe,registerSceneLoaderPlugin:uD,rgbdDecodePixelShader:Iet,rgbdDecodePixelShaderWGSL:Fet,rgbdEncodePixelShader:Oet,rgbdEncodePixelShaderWGSL:zet,rsmFullGlobalIlluminationPixelShader:jqe,rsmFullGlobalIlluminationPixelShaderWGSL:nJe,rsmGlobalIlluminationPixelShader:Wqe,rsmGlobalIlluminationPixelShaderWGSL:tJe,runCoroutine:v1e,runCoroutineAsync:VJ,runCoroutineSync:zJ,screenSpaceReflection2BlurCombinerPixelShader:UYe,screenSpaceReflection2BlurCombinerPixelShaderWGSL:XYe,screenSpaceReflection2BlurPixelShader:FYe,screenSpaceReflection2BlurPixelShaderWGSL:HYe,screenSpaceReflection2PixelShader:OYe,screenSpaceReflection2PixelShaderWGSL:GYe,serialize:Q,serializeAsCameraReference:mBe,serializeAsColor3:qr,serializeAsColor4:Zw,serializeAsColorCurves:fBe,serializeAsFresnelParameters:Yw,serializeAsImageProcessingConfiguration:Yge,serializeAsMatrix:DJ,serializeAsMeshReference:Qw,serializeAsQuaternion:pBe,serializeAsTexture:ki,serializeAsVector2:Cz,serializeAsVector3:ta,setAndStartTimer:S9,setStereoscopicAnaglyphRigMode:Hz,setStereoscopicRigMode:jz,setVRRigMode:eee,shadowMapFragment:dGe,shadowMapFragmentSoftTransparentShadow:MGe,shadowMapFragmentSoftTransparentShadowWGSL:cGe,shadowMapFragmentWGSL:XVe,shadowMapPixelShader:mGe,shadowMapPixelShaderWGSL:ZVe,shadowMapVertexMetric:vGe,shadowMapVertexMetricWGSL:eGe,shadowMapVertexShader:bGe,shadowMapVertexShaderWGSL:rGe,shadowsFragmentFunctions:KWe,shadowsFragmentFunctionsWGSL:iWe,shadowsVertex:AWe,shadowsVertexWGSL:kGe,sharpenPixelShader:fYe,sharpenPixelShaderWGSL:OQe,spritesPixelShader:tet,spritesPixelShaderWGSL:oet,spritesVertexShader:net,spritesVertexShaderWGSL:het,ssao2PixelShader:SYe,ssao2PixelShaderWGSL:MYe,ssaoCombinePixelShader:bYe,ssaoCombinePixelShaderWGSL:PYe,tonemapPixelShader:bqe,tonemapPixelShaderWGSL:Sqe,vrDistortionCorrectionPixelShader:bQe,vrDistortionCorrectionPixelShaderWGSL:SQe},Symbol.toStringTag,{value:"Module"}));function hOt(r){return{all:r=r||new Map,on:function(e,t){var i=r.get(e);i?i.push(t):r.set(e,[t])},off:function(e,t){var i=r.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var i=r.get(e);i&&i.slice().map(function(n){n(t)}),(i=r.get("*"))&&i.slice().map(function(n){n(e,t)})}}}var ut=(r=>(r[r.String=0]="String",r[r.Number=1]="Number",r[r.Boolean=2]="Boolean",r[r.Array=3]="Array",r[r.Object=4]="Object",r))(ut||{}),SD=(r=>(r[r.Value=0]="Value",r[r.DynamicData=1]="DynamicData",r))(SD||{}),b_=(r=>(r.None="None",r.PX_PY_PZ="PX_PY_PZ",r.PX_CY_PZ="PX_CY_PZ",r.PX_NY_PZ="PX_NY_PZ",r.PX_PY_CZ="PX_PY_CZ",r.PX_PY_NZ="PX_PY_NZ",r.PX_CY_CZ="PX_CY_CZ",r.PX_CY_NZ="PX_CY_NZ",r.PX_NY_CZ="PX_NY_CZ",r.PX_NY_NZ="PX_NY_NZ",r.CX_PY_PZ="CX_PY_PZ",r.CX_CY_PZ="CX_CY_PZ",r.CX_NY_PZ="CX_NY_PZ",r.CX_PY_CZ="CX_PY_CZ",r.CX_PY_NZ="CX_PY_NZ",r.CX_CY_CZ="CX_CY_CZ",r.CX_CY_NZ="CX_CY_NZ",r.CX_NY_CZ="CX_NY_CZ",r.CX_NY_NZ="CX_NY_NZ",r.NX_PY_PZ="NX_PY_PZ",r.NX_CY_PZ="NX_CY_PZ",r.NX_NY_PZ="NX_NY_PZ",r.NX_PY_CZ="NX_PY_CZ",r.NX_PY_NZ="NX_PY_NZ",r.NX_CY_CZ="NX_CY_CZ",r.NX_CY_NZ="NX_CY_NZ",r.NX_NY_CZ="NX_NY_CZ",r.NX_NY_NZ="NX_NY_NZ",r))(b_||{});const W_="le5le",dOt=W_+"_arcRotateCamera",fOt=W_+"_arcRotateCamera",pOt=W_+"_gisCamera",mOt=W_+"_highlight",Dae=W_+"_skybox",gOt=W_+"_ground",_Ot=W_+"_placeholder",vOt=W_+"_selectorMesh";var ie=(r=>(r[r.Number=0]="Number",r[r.Vector3=1]="Vector3",r[r.Quaternion=2]="Quaternion",r[r.Matrix=3]="Matrix",r[r.Color3=4]="Color3",r[r.Vector2=5]="Vector2",r[r.Size=6]="Size",r[r.Color4=7]="Color4",r[r.String=8]="String",r[r.Boolean=9]="Boolean",r[r.Null=10]="Null",r[r.Void=11]="Void",r[r.Unknown=12]="Unknown",r[r.Texture=13]="Texture",r[r.VideoTexture=14]="VideoTexture",r[r.CubeTexture=15]="CubeTexture",r[r.StandardMaterial=16]="StandardMaterial",r[r.PBRMaterial=17]="PBRMaterial",r[r.GradientMaterial=18]="GradientMaterial",r[r.Object=19]="Object",r[r.Array=20]="Array",r[r.GridMaterial=21]="GridMaterial",r[r.Vector4=23]="Vector4",r[r.ShaderMaterial=24]="ShaderMaterial",r[r.NodeMaterial=25]="NodeMaterial",r[r.MirrorTexture=26]="MirrorTexture",r[r.WaterMaterial=27]="WaterMaterial",r[r.CityMaterial=28]="CityMaterial",r[r.PBRFreshnelMaterial=29]="PBRFreshnelMaterial",r[r.PBRDissolveMaterial=30]="PBRDissolveMaterial",r[r.VideoMaterial=31]="VideoMaterial",r[r.Scene=1e3]="Scene",r[r.TransformNode=1001]="TransformNode",r[r.AbstractMesh=1002]="AbstractMesh",r[r.Mesh=1003]="Mesh",r[r.InstancedMesh=1004]="InstancedMesh",r[r.PointLight=1005]="PointLight",r[r.SpotLight=1006]="SpotLight",r[r.HemisphericLight=1007]="HemisphericLight",r[r.DirectionalLight=1008]="DirectionalLight",r[r.ArcRotateCamera=1009]="ArcRotateCamera",r[r.FollowCamera=1010]="FollowCamera",r[r.FreeCamera=1011]="FreeCamera",r[r.OrthographicCamera=1012]="OrthographicCamera",r))(ie||{});function Nv(r,e=t=>{}){try{r&&r()}catch(t){console.error(t),e(t)}}function nr(r){return`${Ie.RandomId()}`}const T9=r=>Object.prototype.toString.call(r)==="[object Array]",yf=r=>Object.prototype.toString.call(r)==="[object Object]",zm=(r,e)=>{const t={[ut.Boolean]:"boolean",[ut.Number]:"number",[ut.String]:"string",[ut.Array]:"array",[ut.Object]:"object"}[e];if(t==="boolean"){if(typeof r=="boolean")return r;if(typeof r=="string"){if(r.toLocaleLowerCase()==="true")return!0;if(r.toLocaleLowerCase()==="false")return!1}return!!r}if(t==="number"){if(typeof r=="number")return r;let i=Number(r);return!isNaN(i)||(i=parseFloat(r),!isNaN(i))?i:0}if(t==="string")return typeof r=="string"?r:r==null?"":String(r);if(t==="array")return T9(r)?r:[];if(t==="object")return yf(r)?r:{}},yOt=r=>({string:ut.String,integer:ut.Number,float:ut.Number,bool:ut.Boolean,array:ut.Array,object:ut.Object})[r]??ut.String,xOt=r=>({[ie.String]:ut.String,[ie.Number]:ut.Number,[ie.Boolean]:ut.Boolean,[ie.Color3]:ut.String,[ie.Color4]:ut.String,[ie.Array]:ut.Array,[ie.Object]:ut.Object})[r]??ut.String,Oae=r=>({[ut.String]:ie.String,[ut.Number]:ie.Number,[ut.Boolean]:ie.Boolean,[ut.Array]:ie.Array,[ut.Object]:ie.Object})[r]??ie.Unknown;function bOt(r){switch(r){case ie.Number:return 0;case ie.String:return"";case ie.Boolean:return!1;case ie.Null:return null;case ie.Void:return;case ie.Array:return[];case ie.Object:return{}}}var Rtt=typeof global=="object"&&global&&global.Object===Object&&global,COt=typeof self=="object"&&self&&self.Object===Object&&self,Hg=Rtt||COt||Function("return this")(),Gx=Hg.Symbol,Itt=Object.prototype,AOt=Itt.hasOwnProperty,SOt=Itt.toString,DB=Gx?Gx.toStringTag:void 0;function EOt(r){var e=AOt.call(r,DB),t=r[DB];try{r[DB]=void 0;var i=!0}catch{}var n=SOt.call(r);return i&&(e?r[DB]=t:delete r[DB]),n}var TOt=Object.prototype,MOt=TOt.toString;function ROt(r){return MOt.call(r)}var IOt="[object Null]",POt="[object Undefined]",wRe=Gx?Gx.toStringTag:void 0;function ED(r){return r==null?r===void 0?POt:IOt:wRe&&wRe in Object(r)?EOt(r):ROt(r)}function TD(r){return r!=null&&typeof r=="object"}var wOt="[object Symbol]";function Ptt(r){return typeof r=="symbol"||TD(r)&&ED(r)==wOt}function DOt(r,e){for(var t=-1,i=r==null?0:r.length,n=Array(i);++t-1&&r%1==0&&r-1&&r%1==0&&r<=mLt}function ktt(r){return r!=null&&Btt(r.length)&&!Ott(r)}var gLt=Object.prototype;function Z2e(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||gLt;return r===t}function _Lt(r,e){for(var t=-1,i=Array(r);++t-1}function E7t(r,e){var t=this.__data__,i=hte(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function T3(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e(r.Grad="Grad",r.OutLine="OutLine",r))(sh||{});function mFt(r,e){Sr.ShadersStore[r+"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 `,Sr.ShadersStore[r+"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 ua("effectGlShader"+r,e,{vertex:r,fragment:r},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0});return t.onBind=i=>{const n=i.getBoundingInfo().boundingBox,s=O.Normalize(n.centerWorld),a=O.Distance(n.centerWorld,n.maximumWorld);t.setFloat("distance",a),t.setVector3("center",s),t.setVector3("viewPoint",O.Normalize(i.getScene().activeCamera.position)),t.onBind=null},t.setFloat("distance",20),t.setVector3("center",new O(10,10*Math.random(),10)),t.setVector3("viewPoint",new O(10,10*Math.random(),10)),t}function gFt(r,e){return Sr.ShadersStore["gradient"+r+"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 `,Sr.ShadersStore["gradient"+r+"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 ua("effectGradAlpha"+r,e,{vertex:"gradient"+r,fragment:"gradient"+r},{attributes:["normal","position","uv"],uniforms:["world","worldView","worldViewProjection","view","projection"],needAlphaBlending:!0,needAlphaTesting:!0})}var eit={exports:{}};const _Ft=LNe(uOt);(function(r,e){(function(i,n){r.exports=n(_Ft)})(typeof self<"u"?self:Ri,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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=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:()=>g});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 g=p},"../../../../node_modules/@fortawesome/react-fontawesome/index.es.js":(o,l,c)=>{c.r(l),c.d(l,{FontAwesomeIcon:()=>G});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(Z,te){var le=Object.keys(Z);if(Object.getOwnPropertySymbols){var ce=Object.getOwnPropertySymbols(Z);te&&(ce=ce.filter(function(ue){return Object.getOwnPropertyDescriptor(Z,ue).enumerable})),le.push.apply(le,ce)}return le}function g(Z){for(var te=1;te=0)&&(le[ue]=Z[ue]);return le}function v(Z,te){if(Z==null)return{};var le=y(Z,te),ce,ue;if(Object.getOwnPropertySymbols){var N=Object.getOwnPropertySymbols(Z);for(ue=0;ue=0)&&Object.prototype.propertyIsEnumerable.call(Z,ce)&&(le[ce]=Z[ce])}return le}function x(Z){return b(Z)||C(Z)||A(Z)||P()}function b(Z){if(Array.isArray(Z))return E(Z)}function C(Z){if(typeof Symbol<"u"&&Z[Symbol.iterator]!=null||Z["@@iterator"]!=null)return Array.from(Z)}function A(Z,te){if(Z){if(typeof Z=="string")return E(Z,te);var le=Object.prototype.toString.call(Z).slice(8,-1);if(le==="Object"&&Z.constructor&&(le=Z.constructor.name),le==="Map"||le==="Set")return Array.from(Z);if(le==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(le))return E(Z,te)}}function E(Z,te){(te==null||te>Z.length)&&(te=Z.length);for(var le=0,ce=new Array(te);le2&&arguments[2]!==void 0?arguments[2]:{};if(typeof te=="string")return te;var ce=(te.children||[]).map(function(J){return z(Z,J)}),ue=Object.keys(te.attributes||{}).reduce(function(J,ae){var ne=te.attributes[ae];switch(ae){case"class":J.attrs.className=ne,delete te.attributes.class;break;case"style":J.attrs.style=k(ne);break;default:ae.indexOf("aria-")===0||ae.indexOf("data-")===0?J.attrs[ae.toLowerCase()]=ne:J.attrs[R(ae)]=ne}return J},{attrs:{}}),N=le.style,F=N===void 0?{}:N,X=v(le,I);return ue.attrs.style=g(g({},ue.attrs.style),F),Z.apply(void 0,[te.tag,g(g({},ue.attrs),X)].concat(x(ce)))}var W=!1;try{W=!1}catch{}function K(){if(!W&&console&&typeof console.error=="function"){var Z;(Z=console).error.apply(Z,arguments)}}function U(Z){if(Z&&m(Z)==="object"&&Z.prefix&&Z.iconName&&Z.icon)return Z;if(u.parse.icon)return u.parse.icon(Z);if(Z===null)return null;if(Z&&m(Z)==="object"&&Z.prefix&&Z.iconName)return Z;if(Array.isArray(Z)&&Z.length===2)return{prefix:Z[0],iconName:Z[1]};if(typeof Z=="string")return{prefix:"fas",iconName:Z}}function j(Z,te){return Array.isArray(te)&&te.length>0||!Array.isArray(te)&&te?_({},Z,te):{}}var B={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},G=f.forwardRef(function(Z,te){var le=g(g({},B),Z),ce=le.icon,ue=le.mask,N=le.symbol,F=le.className,X=le.title,J=le.titleId,ae=le.maskId,ne=U(ce),he=j("classes",[].concat(x(w(le)),x((F||"").split(" ")))),fe=j("transform",typeof le.transform=="string"?u.parse.transform(le.transform):le.transform),ye=j("mask",U(ue)),Se=(0,u.icon)(ne,g(g(g(g({},he),fe),ye),{},{symbol:N,title:X,titleId:J,maskId:ae}));if(!Se)return K("Could not find icon",ne),null;var De=Se.abstract,ze={ref:te};return Object.keys(le).forEach(function(Le){B.hasOwnProperty(Le)||(ze[Le]=le[Le])}),Y(De[0],ze)});G.displayName="FontAwesomeIcon",G.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 Y=z.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,g){typeof h=="string"&&(h=[[null,h,void 0]]);var m={};if(f)for(var _=0;_"u"||(x[1]="@layer".concat(x[5].length>0?" ".concat(x[5]):""," {").concat(x[1],"}")),x[5]=g),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(g){var m=g.graph().acyclicer==="greedy"?h(g,_(g)):f(g);u.forEach(m,function(y){var v=g.edge(y);g.removeEdge(y),v.forwardName=y.name,v.reversed=!0,g.setEdge(y.w,y.v,v,u.uniqueId("rev"))});function _(y){return function(v){return y.edge(v).weight}}}function f(g){var m=[],_={},y={};function v(x){u.has(y,x)||(y[x]=!0,_[x]=!0,u.forEach(g.outEdges(x),function(b){u.has(_,b.w)?m.push(b):v(b.w)}),delete _[x])}return u.forEach(g.nodes(),v),m}function p(g){u.forEach(g.edges(),function(m){var _=g.edge(m);if(_.reversed){g.removeEdge(m);var y=_.forwardName;delete _.reversed,delete _.forwardName,g.setEdge(m.w,m.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 g(m){var _=p.children(m),y=p.node(m);if(_.length&&u.forEach(_,g),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")&&g(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 g(v){u.forEach(v.nodes(),function(x){m(v.node(x))}),u.forEach(v.edges(),function(x){var b=v.edge(x);u.forEach(b.points,m),u.has(b,"y")&&m(b)})}function m(v){v.y=-v.y}function _(v){u.forEach(v.nodes(),function(x){y(v.node(x))}),u.forEach(v.edges(),function(x){var b=v.edge(x);u.forEach(b.points,y),u.has(b,"x")&&y(b)})}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 g=h.buildLayerMatrix(p),m=new d({compound:!0,multigraph:!0}).setGraph({});return u.forEach(p.nodes(),function(_){m.setNode(_,{label:_}),m.setParent(_,"layer"+p.node(_).rank)}),u.forEach(p.edges(),function(_){m.setEdge(_.v,_.w,{},_.name)}),u.forEach(g,function(_,y){var v="layer"+y;m.setNode(v,{rank:"same"}),u.reduce(_,function(x,b){return m.setEdge(x,b,{style:"invis"}),b})}),m}},"../../../../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 b=_(v,x||f),C=g(b.graph,b.buckets,b.zeroIdx);return u.flatten(u.map(C,function(A){return v.outEdges(A.v,A.w)}),!0)}function g(v,x,b){for(var C=[],A=x[x.length-1],E=x[0],P;v.nodeCount();){for(;P=E.dequeue();)m(v,x,b,P);for(;P=A.dequeue();)m(v,x,b,P);if(v.nodeCount()){for(var w=x.length-2;w>0;--w)if(P=x[w].dequeue(),P){C=C.concat(m(v,x,b,P,!0));break}}}return C}function m(v,x,b,C,A){var E=A?[]:void 0;return u.forEach(v.inEdges(C.v),function(P){var w=v.edge(P),M=v.node(P.v);A&&E.push({v:P.v,w:P.w}),M.out-=w,y(x,b,M)}),u.forEach(v.outEdges(C.v),function(P){var w=v.edge(P),M=P.w,R=v.node(M);R.in-=w,y(x,b,R)}),v.removeNode(C.v),E}function _(v,x){var b=new h,C=0,A=0;u.forEach(v.nodes(),function(w){b.setNode(w,{v:w,in:0,out:0})}),u.forEach(v.edges(),function(w){var M=b.edge(w.v,w.w)||0,R=x(w),I=M+R;b.setEdge(w.v,w.w,I),A=Math.max(A,b.node(w.v).out+=R),C=Math.max(C,b.node(w.w).in+=R)});var E=u.range(A+C+3).map(function(){return new d}),P=C+1;return u.forEach(b.nodes(),function(w){y(E,P,b.node(w))}),{graph:b,buckets:E,zeroIdx:P}}function y(v,x,b){b.out?b.in?v[b.out-b.in+x].enqueue(b):v[v.length-1].enqueue(b):v[0].enqueue(b)}},"../../../../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,g=c("../../../../node_modules/dagre/lib/parent-dummy-chains.js"),m=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"),b=c("../../../../node_modules/dagre/lib/position/index.js"),C=c("../../../../node_modules/dagre/lib/util.js"),A=c("../../../../node_modules/dagre/lib/graphlib.js").Graph;o.exports=E;function E(ne,he){var fe=he&&he.debugTiming?C.time:C.notime;fe("layout",function(){var ye=fe(" buildLayoutGraph",function(){return U(ne)});fe(" runLayout",function(){P(ye,fe)}),fe(" updateInputGraph",function(){w(ne,ye)})})}function P(ne,he){he(" makeSpaceForEdgeLabels",function(){j(ne)}),he(" removeSelfEdges",function(){N(ne)}),he(" acyclic",function(){h.run(ne)}),he(" nestingGraph.run",function(){_.run(ne)}),he(" rank",function(){f(C.asNonCompoundGraph(ne))}),he(" injectEdgeLabelProxies",function(){B(ne)}),he(" removeEmptyRanks",function(){m(ne)}),he(" nestingGraph.cleanup",function(){_.cleanup(ne)}),he(" normalizeRanks",function(){p(ne)}),he(" assignRankMinMax",function(){G(ne)}),he(" removeEdgeLabelProxies",function(){Y(ne)}),he(" normalize.run",function(){d.run(ne)}),he(" parentDummyChains",function(){g(ne)}),he(" addBorderSegments",function(){y(ne)}),he(" order",function(){x(ne)}),he(" insertSelfEdges",function(){F(ne)}),he(" adjustCoordinateSystem",function(){v.adjust(ne)}),he(" position",function(){b(ne)}),he(" positionSelfEdges",function(){X(ne)}),he(" removeBorderNodes",function(){ue(ne)}),he(" normalize.undo",function(){d.undo(ne)}),he(" fixupEdgeLabelCoords",function(){le(ne)}),he(" undoCoordinateSystem",function(){v.undo(ne)}),he(" translateGraph",function(){Z(ne)}),he(" assignNodeIntersects",function(){te(ne)}),he(" reversePoints",function(){ce(ne)}),he(" acyclic.undo",function(){h.undo(ne)})}function w(ne,he){u.forEach(ne.nodes(),function(fe){var ye=ne.node(fe),Se=he.node(fe);ye&&(ye.x=Se.x,ye.y=Se.y,he.children(fe).length&&(ye.width=Se.width,ye.height=Se.height))}),u.forEach(ne.edges(),function(fe){var ye=ne.edge(fe),Se=he.edge(fe);ye.points=Se.points,u.has(Se,"x")&&(ye.x=Se.x,ye.y=Se.y)}),ne.graph().width=he.graph().width,ne.graph().height=he.graph().height}var M=["nodesep","edgesep","ranksep","marginx","marginy"],R={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},I=["acyclicer","ranker","rankdir","align"],D=["width","height"],k={width:0,height:0},z=["minlen","weight","width","height","labeloffset"],W={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},K=["labelpos"];function U(ne){var he=new A({multigraph:!0,compound:!0}),fe=ae(ne.graph());return he.setGraph(u.merge({},R,J(fe,M),u.pick(fe,I))),u.forEach(ne.nodes(),function(ye){var Se=ae(ne.node(ye));he.setNode(ye,u.defaults(J(Se,D),k)),he.setParent(ye,ne.parent(ye))}),u.forEach(ne.edges(),function(ye){var Se=ae(ne.edge(ye));he.setEdge(ye,u.merge({},W,J(Se,z),u.pick(Se,K)))}),he}function j(ne){var he=ne.graph();he.ranksep/=2,u.forEach(ne.edges(),function(fe){var ye=ne.edge(fe);ye.minlen*=2,ye.labelpos.toLowerCase()!=="c"&&(he.rankdir==="TB"||he.rankdir==="BT"?ye.width+=ye.labeloffset:ye.height+=ye.labeloffset)})}function B(ne){u.forEach(ne.edges(),function(he){var fe=ne.edge(he);if(fe.width&&fe.height){var ye=ne.node(he.v),Se=ne.node(he.w),De={rank:(Se.rank-ye.rank)/2+ye.rank,e:he};C.addDummyNode(ne,"edge-proxy",De,"_ep")}})}function G(ne){var he=0;u.forEach(ne.nodes(),function(fe){var ye=ne.node(fe);ye.borderTop&&(ye.minRank=ne.node(ye.borderTop).rank,ye.maxRank=ne.node(ye.borderBottom).rank,he=u.max(he,ye.maxRank))}),ne.graph().maxRank=he}function Y(ne){u.forEach(ne.nodes(),function(he){var fe=ne.node(he);fe.dummy==="edge-proxy"&&(ne.edge(fe.e).labelRank=fe.rank,ne.removeNode(he))})}function Z(ne){var he=Number.POSITIVE_INFINITY,fe=0,ye=Number.POSITIVE_INFINITY,Se=0,De=ne.graph(),ze=De.marginx||0,Le=De.marginy||0;function Je(ke){var We=ke.x,it=ke.y,_t=ke.width,Dt=ke.height;he=Math.min(he,We-_t/2),fe=Math.max(fe,We+_t/2),ye=Math.min(ye,it-Dt/2),Se=Math.max(Se,it+Dt/2)}u.forEach(ne.nodes(),function(ke){Je(ne.node(ke))}),u.forEach(ne.edges(),function(ke){var We=ne.edge(ke);u.has(We,"x")&&Je(We)}),he-=ze,ye-=Le,u.forEach(ne.nodes(),function(ke){var We=ne.node(ke);We.x-=he,We.y-=ye}),u.forEach(ne.edges(),function(ke){var We=ne.edge(ke);u.forEach(We.points,function(it){it.x-=he,it.y-=ye}),u.has(We,"x")&&(We.x-=he),u.has(We,"y")&&(We.y-=ye)}),De.width=fe-he+ze,De.height=Se-ye+Le}function te(ne){u.forEach(ne.edges(),function(he){var fe=ne.edge(he),ye=ne.node(he.v),Se=ne.node(he.w),De,ze;fe.points?(De=fe.points[0],ze=fe.points[fe.points.length-1]):(fe.points=[],De=Se,ze=ye),fe.points.unshift(C.intersectRect(ye,De)),fe.points.push(C.intersectRect(Se,ze))})}function le(ne){u.forEach(ne.edges(),function(he){var fe=ne.edge(he);if(u.has(fe,"x"))switch((fe.labelpos==="l"||fe.labelpos==="r")&&(fe.width-=fe.labeloffset),fe.labelpos){case"l":fe.x-=fe.width/2+fe.labeloffset;break;case"r":fe.x+=fe.width/2+fe.labeloffset;break}})}function ce(ne){u.forEach(ne.edges(),function(he){var fe=ne.edge(he);fe.reversed&&fe.points.reverse()})}function ue(ne){u.forEach(ne.nodes(),function(he){if(ne.children(he).length){var fe=ne.node(he),ye=ne.node(fe.borderTop),Se=ne.node(fe.borderBottom),De=ne.node(u.last(fe.borderLeft)),ze=ne.node(u.last(fe.borderRight));fe.width=Math.abs(ze.x-De.x),fe.height=Math.abs(Se.y-ye.y),fe.x=De.x+fe.width/2,fe.y=ye.y+fe.height/2}}),u.forEach(ne.nodes(),function(he){ne.node(he).dummy==="border"&&ne.removeNode(he)})}function N(ne){u.forEach(ne.edges(),function(he){if(he.v===he.w){var fe=ne.node(he.v);fe.selfEdges||(fe.selfEdges=[]),fe.selfEdges.push({e:he,label:ne.edge(he)}),ne.removeEdge(he)}})}function F(ne){var he=C.buildLayerMatrix(ne);u.forEach(he,function(fe){var ye=0;u.forEach(fe,function(Se,De){var ze=ne.node(Se);ze.order=De+ye,u.forEach(ze.selfEdges,function(Le){C.addDummyNode(ne,"selfedge",{width:Le.label.width,height:Le.label.height,rank:ze.rank,order:De+ ++ye,e:Le.e,label:Le.label},"_se")}),delete ze.selfEdges})})}function X(ne){u.forEach(ne.nodes(),function(he){var fe=ne.node(he);if(fe.dummy==="selfedge"){var ye=ne.node(fe.e.v),Se=ye.x+ye.width/2,De=ye.y,ze=fe.x-Se,Le=ye.height/2;ne.setEdge(fe.e,fe.label),ne.removeNode(he),fe.label.points=[{x:Se+2*ze/3,y:De-Le},{x:Se+5*ze/6,y:De-Le},{x:Se+ze,y:De},{x:Se+5*ze/6,y:De+Le},{x:Se+2*ze/3,y:De+Le}],fe.label.x=fe.x,fe.label.y=fe.y}})}function J(ne,he){return u.mapValues(u.pick(ne,he),Number)}function ae(ne){var he={};return u.forEach(ne,function(fe,ye){he[ye.toLowerCase()]=fe}),he}},"../../../../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:m};function d(_){var y=h.addDummyNode(_,"root",{},"_root"),v=p(_),x=u.max(u.values(v))-1,b=2*x+1;_.graph().nestingRoot=y,u.forEach(_.edges(),function(A){_.edge(A).minlen*=b});var C=g(_)+1;u.forEach(_.children(),function(A){f(_,y,b,C,x,v,A)}),_.graph().nodeRankFactor=b}function f(_,y,v,x,b,C,A){var E=_.children(A);if(!E.length){A!==y&&_.setEdge(y,A,{weight:0,minlen:v});return}var P=h.addBorderNode(_,"_bt"),w=h.addBorderNode(_,"_bb"),M=_.node(A);_.setParent(P,A),M.borderTop=P,_.setParent(w,A),M.borderBottom=w,u.forEach(E,function(R){f(_,y,v,x,b,C,R);var I=_.node(R),D=I.borderTop?I.borderTop:R,k=I.borderBottom?I.borderBottom:R,z=I.borderTop?x:2*x,W=D!==k?1:b-C[A]+1;_.setEdge(P,D,{weight:z,minlen:W,nestingEdge:!0}),_.setEdge(k,w,{weight:z,minlen:W,nestingEdge:!0})}),_.parent(A)||_.setEdge(y,P,{weight:0,minlen:b+C[A]})}function p(_){var y={};function v(x,b){var C=_.children(x);C&&C.length&&u.forEach(C,function(A){v(A,b+1)}),y[x]=b}return u.forEach(_.children(),function(x){v(x,1)}),y}function g(_){return u.reduce(_.edges(),function(y,v){return y+_.edge(v).weight},0)}function m(_){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(g){g.graph().dummyChains=[],u.forEach(g.edges(),function(m){f(g,m)})}function f(g,m){var _=m.v,y=g.node(_).rank,v=m.w,x=g.node(v).rank,b=m.name,C=g.edge(m),A=C.labelRank;if(x!==y+1){g.removeEdge(m);var E,P,w;for(w=0,++y;y{var u=c("../../../../node_modules/dagre/lib/lodash.js");o.exports=h;function h(d,f,p){var g={},m;u.forEach(p,function(_){for(var y=d.parent(_),v,x;y;){if(v=d.parent(y),v?(x=g[v],g[v]=y):(x=m,m=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 g=d.inEdges(p);if(g.length){var m=u.reduce(g,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:m.sum/m.weight,weight:m.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,g,m){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),b=p.parent(v);(x.rank===g||x.minRank<=g&&g<=x.maxRank)&&(y.setNode(v),y.setParent(v,b||_),u.forEach(p[m](v),function(C){var A=C.v===v?C.w:C.v,E=y.edge(A,v),P=u.isUndefined(E)?0:E.weight;y.setEdge(A,v,{weight:p.edge(C).weight+P})}),u.has(x,"minRank")&&y.setNode(v,{borderLeft:x.borderLeft[g],borderRight:x.borderRight[g]}))}),y}function f(p){for(var g;p.hasNode(g=u.uniqueId("_root")););return g}},"../../../../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 g=0,m=1;m0;)A%2&&(E+=x[A+1]),A=A-1>>1,x[A]+=C.weight;b+=C.weight*E})),b}},"../../../../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"),g=c("../../../../node_modules/dagre/lib/order/add-subgraph-constraints.js"),m=c("../../../../node_modules/dagre/lib/graphlib.js").Graph,_=c("../../../../node_modules/dagre/lib/util.js");o.exports=y;function y(C){var A=_.maxRank(C),E=v(C,u.range(1,A+1),"inEdges"),P=v(C,u.range(A-1,-1,-1),"outEdges"),w=h(C);b(C,w);for(var M=Number.POSITIVE_INFINITY,R,I=0,D=0;D<4;++I,++D){x(I%2?E:P,I%4>=2),w=_.buildLayerMatrix(C);var k=d(C,w);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}),g=u.max(u.map(p,function(v){return d.node(v).rank})),m=u.map(u.range(g+1),function(){return[]});function _(v){if(!u.has(f,v)){f[v]=!0;var x=d.node(v);m[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,_),m}},"../../../../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,g){var m={};u.forEach(p,function(y,v){var x=m[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(g.edges(),function(y){var v=m[y.v],x=m[y.w];!u.isUndefined(v)&&!u.isUndefined(x)&&(x.indegree++,v.out.push(m[y.w]))});var _=u.filter(m,function(y){return!y.indegree});return d(_)}function d(p){var g=[];function m(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();g.push(y),u.forEach(y.in.reverse(),m(y)),u.forEach(y.out,_(y))}return u.map(u.filter(g,function(v){return!v.merged}),function(v){return u.pick(v,["vs","i","barycenter","weight"])})}function f(p,g){var m=0,_=0;p.weight&&(m+=p.barycenter*p.weight,_+=p.weight),g.weight&&(m+=g.barycenter*g.weight,_+=g.weight),p.vs=g.vs.concat(p.vs),p.barycenter=m/_,p.weight=_,p.i=Math.min(g.i,p.i),g.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 b=_.children(y),C=_.node(y),A=C?C.borderLeft:void 0,E=C?C.borderRight:void 0,P={};A&&(b=u.filter(b,function(k){return k!==A&&k!==E}));var w=h(_,b);u.forEach(w,function(k){if(_.children(k.v).length){var z=p(_,k.v,v,x);P[k.v]=z,u.has(z,"barycenter")&&m(k,z)}});var M=d(w,v);g(M,P);var R=f(M,x);if(A&&(R.vs=u.flatten([A,R.vs,E],!0),_.predecessors(A).length)){var I=_.node(_.predecessors(A)[0]),D=_.node(_.predecessors(E)[0]);u.has(R,"barycenter")||(R.barycenter=0,R.weight=0),R.barycenter=(R.barycenter*R.weight+I.order+D.order)/(R.weight+2),R.weight+=2}return R}function g(_,y){u.forEach(_,function(v){v.vs=u.flatten(v.vs.map(function(x){return y[x]?y[x].vs:x}),!0)})}function m(_,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(g,m){var _=h.partition(g,function(P){return u.has(P,"barycenter")}),y=_.lhs,v=u.sortBy(_.rhs,function(P){return-P.i}),x=[],b=0,C=0,A=0;y.sort(p(!!m)),A=f(x,v,A),u.forEach(y,function(P){A+=P.vs.length,x.push(P.vs),b+=P.barycenter*P.weight,C+=P.weight,A=f(x,v,A)});var E={vs:u.flatten(x,!0)};return C&&(E.barycenter=b/C,E.weight=C),E}function f(g,m,_){for(var y;m.length&&(y=u.last(m)).i<=_;)m.pop(),g.push(y.vs),_++;return _}function p(g){return function(m,_){return m.barycenter<_.barycenter?-1:m.barycenter>_.barycenter?1:g?_.i-m.i:m.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 g=f(p);u.forEach(p.graph().dummyChains,function(m){for(var _=p.node(m),y=_.edgeObj,v=d(p,g,y.v,y.w),x=v.path,b=v.lca,C=0,A=x[C],E=!0;m!==y.w;){if(_=p.node(m),E){for(;(A=x[C])!==b&&p.node(A).maxRank<_.rank;)C++;A===b&&(E=!1)}if(!E){for(;Cx||b>g[C].lim));for(A=C,C=_;(C=p.parent(C))!==A;)v.push(C);return{path:y.concat(v.reverse()),lca:A}}function f(p){var g={},m=0;function _(y){var v=m;u.forEach(p.children(y),_),g[y]={low:v,lim:m++}}return u.forEach(p.children(),_),g}},"../../../../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:E,findType1Conflicts:f,findType2Conflicts:p,addConflict:m,hasConflict:_,verticalAlignment:y,horizontalCompaction:v,alignCoordinates:C,findSmallestWidthAlignment:b,balance:A};function f(M,R){var I={};function D(k,z){var W=0,K=0,U=k.length,j=u.last(z);return u.forEach(z,function(B,G){var Y=g(M,B),Z=Y?M.node(Y).order:U;(Y||B===j)&&(u.forEach(z.slice(K,G+1),function(te){u.forEach(M.predecessors(te),function(le){var ce=M.node(le),ue=ce.order;(uej)&&m(I,Y,B)})})}function k(z,W){var K=-1,U,j=0;return u.forEach(W,function(B,G){if(M.node(B).dummy==="border"){var Y=M.predecessors(B);Y.length&&(U=M.node(Y[0]).order,D(W,j,G,K,U),j=G,K=U)}D(W,j,W.length,U,z.length)}),W}return u.reduce(R,k),I}function g(M,R){if(M.node(R).dummy)return u.find(M.predecessors(R),function(I){return M.node(I).dummy})}function m(M,R,I){if(R>I){var D=R;R=I,I=D}var k=M[R];k||(M[R]=k={}),k[I]=!0}function _(M,R,I){if(R>I){var D=R;R=I,I=D}return u.has(M[R],I)}function y(M,R,I,D){var k={},z={},W={};return u.forEach(R,function(K){u.forEach(K,function(U,j){k[U]=U,z[U]=U,W[U]=j})}),u.forEach(R,function(K){var U=-1;u.forEach(K,function(j){var B=D(j);if(B.length){B=u.sortBy(B,function(le){return W[le]});for(var G=(B.length-1)/2,Y=Math.floor(G),Z=Math.ceil(G);Y<=Z;++Y){var te=B[Y];z[j]===j&&U{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(g){g=h.asNonCompoundGraph(g),p(g),u.forEach(d(g),function(m,_){g.node(_).x=m})}function p(g){var m=h.buildLayerMatrix(g),_=g.graph().ranksep,y=0;u.forEach(m,function(v){var x=u.max(u.map(v,function(b){return g.node(b).height}));u.forEach(v,function(b){g.node(b).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 b,C;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":m(y);break;case"longest-path":g(y);break;default:_(y)}}var g=h;function m(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,g=c("../../../../node_modules/dagre/lib/graphlib.js").alg.postorder,m=c("../../../../node_modules/dagre/lib/util.js").simplify;o.exports=_,_.initLowLimValues=b,_.initCutValues=y,_.calcCutValue=x,_.leaveEdge=A,_.enterEdge=E,_.exchangeEdges=P;function _(I){I=m(I),f(I);var D=h(I);b(D),y(D,I);for(var k,z;k=A(D);)z=E(D,I,k),P(D,I,k,z)}function y(I,D){var k=g(I,I.nodes());k=k.slice(0,k.length-1),u.forEach(k,function(z){v(I,D,z)})}function v(I,D,k){var z=I.node(k),W=z.parent;I.edge(k,W).cutvalue=x(I,D,k)}function x(I,D,k){var z=I.node(k),W=z.parent,K=!0,U=D.edge(k,W),j=0;return U||(K=!1,U=D.edge(W,k)),j=U.weight,u.forEach(D.nodeEdges(k),function(B){var G=B.v===k,Y=G?B.w:B.v;if(Y!==W){var Z=G===K,te=D.edge(B).weight;if(j+=Z?te:-te,M(I,k,Y)){var le=I.edge(k,Y).cutvalue;j+=Z?-le:le}}}),j}function b(I,D){arguments.length<2&&(D=I.nodes()[0]),C(I,{},1,D)}function C(I,D,k,z,W){var K=k,U=I.node(z);return D[z]=!0,u.forEach(I.neighbors(z),function(j){u.has(D,j)||(k=C(I,D,k,j,z))}),U.low=K,U.lim=k++,W?U.parent=W:delete U.parent,k}function A(I){return u.find(I.edges(),function(D){return I.edge(D).cutvalue<0})}function E(I,D,k){var z=k.v,W=k.w;D.hasEdge(z,W)||(z=k.w,W=k.v);var K=I.node(z),U=I.node(W),j=K,B=!1;K.lim>U.lim&&(j=U,B=!0);var G=u.filter(D.edges(),function(Y){return B===R(I,I.node(Y.v),j)&&B!==R(I,I.node(Y.w),j)});return u.minBy(G,function(Y){return d(D,Y)})}function P(I,D,k,z){var W=k.v,K=k.w;I.removeEdge(W,K),I.setEdge(z.v,z.w,{}),b(I),y(I,D),w(I,D)}function w(I,D){var k=u.find(I.nodes(),function(W){return!D.node(W).parent}),z=p(I,k);z=z.slice(1),u.forEach(z,function(W){var K=I.node(W).parent,U=D.edge(W,K),j=!1;U||(U=D.edge(K,W),j=!0),D.node(W).rank=D.node(K).rank+(j?U.minlen:-U.minlen)})}function M(I,D,k){return I.hasEdge(D,k)}function R(I,D,k){return k.low<=D.lim&&D.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 g(m){var _=f.node(m);if(u.has(p,m))return _.rank;p[m]=!0;var y=u.min(u.map(f.outEdges(m),function(v){return g(v.w)-f.edge(v).minlen}));return(y===Number.POSITIVE_INFINITY||y===void 0||y===null)&&(y=0),_.rank=y}u.forEach(f.sources(),g)}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:g,predecessorWeights:m,intersectRect:_,buildLayerMatrix:y,normalizeRanks:v,removeEmptyRanks:x,addBorderNode:b,maxRank:C,partition:A,time:E,notime:P};function d(w,M,R,I){var D;do D=u.uniqueId(I);while(w.hasNode(D));return R.dummy=M,w.setNode(D,R),D}function f(w){var M=new h().setGraph(w.graph());return u.forEach(w.nodes(),function(R){M.setNode(R,w.node(R))}),u.forEach(w.edges(),function(R){var I=M.edge(R.v,R.w)||{weight:0,minlen:1},D=w.edge(R);M.setEdge(R.v,R.w,{weight:I.weight+D.weight,minlen:Math.max(I.minlen,D.minlen)})}),M}function p(w){var M=new h({multigraph:w.isMultigraph()}).setGraph(w.graph());return u.forEach(w.nodes(),function(R){w.children(R).length||M.setNode(R,w.node(R))}),u.forEach(w.edges(),function(R){M.setEdge(R,w.edge(R))}),M}function g(w){var M=u.map(w.nodes(),function(R){var I={};return u.forEach(w.outEdges(R),function(D){I[D.w]=(I[D.w]||0)+w.edge(D).weight}),I});return u.zipObject(w.nodes(),M)}function m(w){var M=u.map(w.nodes(),function(R){var I={};return u.forEach(w.inEdges(R),function(D){I[D.v]=(I[D.v]||0)+w.edge(D).weight}),I});return u.zipObject(w.nodes(),M)}function _(w,M){var R=w.x,I=w.y,D=M.x-R,k=M.y-I,z=w.width/2,W=w.height/2;if(!D&&!k)throw new Error("Not possible to find intersection inside of the rectangle");var K,U;return Math.abs(k)*z>Math.abs(D)*W?(k<0&&(W=-W),K=W*D/k,U=W):(D<0&&(z=-z),K=z,U=z*k/D),{x:R+K,y:I+U}}function y(w){var M=u.map(u.range(C(w)+1),function(){return[]});return u.forEach(w.nodes(),function(R){var I=w.node(R),D=I.rank;u.isUndefined(D)||(M[D][I.order]=R)}),M}function v(w){var M=u.min(u.map(w.nodes(),function(R){return w.node(R).rank}));u.forEach(w.nodes(),function(R){var I=w.node(R);u.has(I,"rank")&&(I.rank-=M)})}function x(w){var M=u.min(u.map(w.nodes(),function(k){return w.node(k).rank})),R=[];u.forEach(w.nodes(),function(k){var z=w.node(k).rank-M;R[z]||(R[z]=[]),R[z].push(k)});var I=0,D=w.graph().nodeRankFactor;u.forEach(R,function(k,z){u.isUndefined(k)&&z%D!==0?--I:I&&u.forEach(k,function(W){w.node(W).rank+=I})})}function b(w,M,R,I){var D={width:0,height:0};return arguments.length>=4&&(D.rank=R,D.order=I),d(w,"border",D,M)}function C(w){return u.max(u.map(w.nodes(),function(M){var R=w.node(M).rank;if(!u.isUndefined(R))return R}))}function A(w,M){var R={lhs:[],rhs:[]};return u.forEach(w,function(I){M(I)?R.lhs.push(I):R.rhs.push(I)}),R}function E(w,M){var R=u.now();try{return M()}finally{console.log(w+" time: "+(u.now()-R)+"ms")}}function P(w,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=[],g;function m(_){u.has(f,_)||(f[_]=!0,g.push(_),u.each(d.successors(_),m),u.each(d.predecessors(_),m))}return u.each(d.nodes(),function(_){g=[],m(_),g.length&&p.push(g)}),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,g){u.isArray(p)||(p=[p]);var m=(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,g==="post",y,m,_)}),_}function d(f,p,g,m,_,y){u.has(m,p)||(m[p]=!0,g||y.push(p),u.each(_(p),function(v){d(f,v,g,m,_,y)}),g&&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,g){return h.transform(f.nodes(),function(m,_){m[_]=u(f,_,p,g)},{})}},"../../../../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(g,m,_,y){return p(g,String(m),_||d,y||function(v){return g.outEdges(v)})}function p(g,m,_,y){var v={},x=new h,b,C,A=function(E){var P=E.v!==b?E.v:E.w,w=v[P],M=_(E),R=C.distance+M;if(M<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+E+" Weight: "+M);R0&&(b=x.removeMin(),C=v[b],C.distance!==Number.POSITIVE_INFINITY);)y(b).forEach(A);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,g,m){return f(p,g||h,m||function(_){return p.outEdges(_)})}function f(p,g,m){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})}),m(v).forEach(function(x){var b=x.v===v?x.w:x.v,C=g(x);_[v][b]={distance:C,predecessor:v}})}),y.forEach(function(v){var x=_[v];y.forEach(function(b){var C=_[b];y.forEach(function(A){var E=C[v],P=x[A],w=C[A],M=E.distance+P.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,g){var m=new h,_={},y=new d,v;function x(C){var A=C.v===v?C.w:C.v,E=y.priority(A);if(E!==void 0){var P=g(C);P0;){if(v=y.removeMin(),u.has(_,v))m.setEdge(v,_[v]);else{if(b)throw new Error("Input graph is not connected: "+p);b=!0}p.nodeEdges(v).forEach(x)}return m}},"../../../../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=[],g={},m=[];function _(y){var v=g[y]={onStack:!0,lowlink:f,index:f++};if(p.push(y),d.successors(y).forEach(function(C){u.has(g,C)?g[C].onStack&&(v.lowlink=Math.min(v.lowlink,g[C].index)):(_(C),v.lowlink=Math.min(v.lowlink,g[C].lowlink))}),v.lowlink===v.index){var x=[],b;do b=p.pop(),g[b].onStack=!1,x.push(b);while(y!==b);m.push(x)}}return d.nodes().forEach(function(y){u.has(g,y)||_(y)}),m}},"../../../../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={},g={},m=[];function _(y){if(u.has(g,y))throw new d;u.has(p,y)||(g[y]=!0,p[y]=!0,u.each(f.predecessors(y),_),delete g[y],m.push(y))}if(u.each(f.sinks(),_),u.size(p)!==f.nodeCount())throw new d;return m}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 g=this._arr,m=g.length;return p[d]=m,g.push({key:d,priority:f}),this._decrease(m),!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,g=p+1,m=d;p>1,!(f[g].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(b){return u.isEmpty(x._in[b])})},p.prototype.sinks=function(){var x=this;return u.filter(this.nodes(),function(b){return u.isEmpty(x._out[b])})},p.prototype.setNodes=function(x,b){var C=arguments,A=this;return u.each(x,function(E){C.length>1?A.setNode(E,b):A.setNode(E)}),this},p.prototype.setNode=function(x,b){return u.has(this._nodes,x)?(arguments.length>1&&(this._nodes[x]=b),this):(this._nodes[x]=arguments.length>1?b: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 b=this;if(u.has(this._nodes,x)){var C=function(A){b.removeEdge(b._edgeObjs[A])};delete this._nodes[x],this._isCompound&&(this._removeFromParentsChildList(x),delete this._parent[x],u.each(this.children(x),function(A){b.setParent(A)}),delete this._children[x]),u.each(u.keys(this._in[x]),C),delete this._in[x],delete this._preds[x],u.each(u.keys(this._out[x]),C),delete this._out[x],delete this._sucs[x],--this._nodeCount}return this},p.prototype.setParent=function(x,b){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(u.isUndefined(b))b=d;else{b+="";for(var C=b;!u.isUndefined(C);C=this.parent(C))if(C===x)throw new Error("Setting "+b+" as parent of "+x+" would create a cycle");this.setNode(b)}return this.setNode(x),this._removeFromParentsChildList(x),this._parent[x]=b,this._children[b][x]=!0,this},p.prototype._removeFromParentsChildList=function(x){delete this._children[this._parent[x]][x]},p.prototype.parent=function(x){if(this._isCompound){var b=this._parent[x];if(b!==d)return b}},p.prototype.children=function(x){if(u.isUndefined(x)&&(x=d),this._isCompound){var b=this._children[x];if(b)return u.keys(b)}else{if(x===d)return this.nodes();if(this.hasNode(x))return[]}},p.prototype.predecessors=function(x){var b=this._preds[x];if(b)return u.keys(b)},p.prototype.successors=function(x){var b=this._sucs[x];if(b)return u.keys(b)},p.prototype.neighbors=function(x){var b=this.predecessors(x);if(b)return u.union(b,this.successors(x))},p.prototype.isLeaf=function(x){var b;return this.isDirected()?b=this.successors(x):b=this.neighbors(x),b.length===0},p.prototype.filterNodes=function(x){var b=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});b.setGraph(this.graph());var C=this;u.each(this._nodes,function(P,w){x(w)&&b.setNode(w,P)}),u.each(this._edgeObjs,function(P){b.hasNode(P.v)&&b.hasNode(P.w)&&b.setEdge(P,C.edge(P))});var A={};function E(P){var w=C.parent(P);return w===void 0||b.hasNode(w)?(A[P]=w,w):w in A?A[w]:E(w)}return this._isCompound&&u.each(b.nodes(),function(P){b.setParent(P,E(P))}),b},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,b){var C=this,A=arguments;return u.reduce(x,function(E,P){return A.length>1?C.setEdge(E,P,b):C.setEdge(E,P),P}),this},p.prototype.setEdge=function(){var x,b,C,A,E=!1,P=arguments[0];typeof P=="object"&&P!==null&&"v"in P?(x=P.v,b=P.w,C=P.name,arguments.length===2&&(A=arguments[1],E=!0)):(x=P,b=arguments[1],C=arguments[3],arguments.length>2&&(A=arguments[2],E=!0)),x=""+x,b=""+b,u.isUndefined(C)||(C=""+C);var w=_(this._isDirected,x,b,C);if(u.has(this._edgeLabels,w))return E&&(this._edgeLabels[w]=A),this;if(!u.isUndefined(C)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(x),this.setNode(b),this._edgeLabels[w]=E?A:this._defaultEdgeLabelFn(x,b,C);var M=y(this._isDirected,x,b,C);return x=M.v,b=M.w,Object.freeze(M),this._edgeObjs[w]=M,g(this._preds[b],x),g(this._sucs[x],b),this._in[b][w]=M,this._out[x][w]=M,this._edgeCount++,this},p.prototype.edge=function(x,b,C){var A=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,b,C);return this._edgeLabels[A]},p.prototype.hasEdge=function(x,b,C){var A=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,b,C);return u.has(this._edgeLabels,A)},p.prototype.removeEdge=function(x,b,C){var A=arguments.length===1?v(this._isDirected,arguments[0]):_(this._isDirected,x,b,C),E=this._edgeObjs[A];return E&&(x=E.v,b=E.w,delete this._edgeLabels[A],delete this._edgeObjs[A],m(this._preds[b],x),m(this._sucs[x],b),delete this._in[b][A],delete this._out[x][A],this._edgeCount--),this},p.prototype.inEdges=function(x,b){var C=this._in[x];if(C){var A=u.values(C);return b?u.filter(A,function(E){return E.v===b}):A}},p.prototype.outEdges=function(x,b){var C=this._out[x];if(C){var A=u.values(C);return b?u.filter(A,function(E){return E.w===b}):A}},p.prototype.nodeEdges=function(x,b){var C=this.inEdges(x,b);if(C)return C.concat(this.outEdges(x,b))};function g(x,b){x[b]?x[b]++:x[b]=1}function m(x,b){--x[b]||delete x[b]}function _(x,b,C,A){var E=""+b,P=""+C;if(!x&&E>P){var w=E;E=P,P=w}return E+f+P+f+(u.isUndefined(A)?h:A)}function y(x,b,C,A){var E=""+b,P=""+C;if(!x&&E>P){var w=E;E=P,P=w}var M={v:E,w:P};return A&&(M.name=A),M}function v(x,b){return _(x,b.v,b.w,b.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:g};function d(m){var _={options:{directed:m.isDirected(),multigraph:m.isMultigraph(),compound:m.isCompound()},nodes:f(m),edges:p(m)};return u.isUndefined(m.graph())||(_.value=u.clone(m.graph())),_}function f(m){return u.map(m.nodes(),function(_){var y=m.node(_),v=m.parent(_),x={v:_};return u.isUndefined(y)||(x.value=y),u.isUndefined(v)||(x.parent=v),x})}function p(m){return u.map(m.edges(),function(_){var y=m.edge(_),v={v:_.v,w:_.w};return u.isUndefined(_.name)||(v.name=_.name),u.isUndefined(y)||(v.value=y),v})}function g(m){var _=new h(m.options).setGraph(m.value);return u.each(m.nodes,function(y){_.setNode(y.v,y.value),y.parent&&_.setParent(y.v,y.parent)}),u.each(m.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 g(m){var _=-1,y=m==null?0:m.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 g(m){var _=-1,y=m==null?0:m.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 g(m){var _=-1,y=m==null?0:m.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 g=-1,m=p==null?0:p.length;for(this.__data__=new u;++g{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"),g=c("../../../../node_modules/lodash/_stackSet.js");function m(_){var y=this.__data__=new u(_);this.size=y.size}m.prototype.clear=h,m.prototype.delete=d,m.prototype.get=f,m.prototype.has=p,m.prototype.set=g,o.exports=m},"../../../../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"),g=c("../../../../node_modules/lodash/isTypedArray.js"),m=Object.prototype,_=m.hasOwnProperty;function y(v,x){var b=d(v),C=!b&&h(v),A=!b&&!C&&f(v),E=!b&&!C&&!A&&g(v),P=b||C||A||E,w=P?u(v.length,String):[],M=w.length;for(var R in v)(x||_.call(v,R))&&!(P&&(R=="length"||A&&(R=="offset"||R=="parent")||E&&(R=="buffer"||R=="byteLength"||R=="byteOffset")||p(R,M)))&&w.push(R);return w}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,g){(g!==void 0&&!h(f[p],g)||g===void 0&&!(p in f))&&u(f,p,g)}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(g,m,_){var y=g[m];(!(f.call(g,m)&&h(y,_))||_===void 0&&!(m in g))&&u(g,m,_)}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"),g=c("../../../../node_modules/lodash/_cloneBuffer.js"),m=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"),b=c("../../../../node_modules/lodash/_getTag.js"),C=c("../../../../node_modules/lodash/_initCloneArray.js"),A=c("../../../../node_modules/lodash/_initCloneByTag.js"),E=c("../../../../node_modules/lodash/_initCloneObject.js"),P=c("../../../../node_modules/lodash/isArray.js"),w=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"),D=c("../../../../node_modules/lodash/keys.js"),k=c("../../../../node_modules/lodash/keysIn.js"),z=1,W=2,K=4,U="[object Arguments]",j="[object Array]",B="[object Boolean]",G="[object Date]",Y="[object Error]",Z="[object Function]",te="[object GeneratorFunction]",le="[object Map]",ce="[object Number]",ue="[object Object]",N="[object RegExp]",F="[object Set]",X="[object String]",J="[object Symbol]",ae="[object WeakMap]",ne="[object ArrayBuffer]",he="[object DataView]",fe="[object Float32Array]",ye="[object Float64Array]",Se="[object Int8Array]",De="[object Int16Array]",ze="[object Int32Array]",Le="[object Uint8Array]",Je="[object Uint8ClampedArray]",ke="[object Uint16Array]",We="[object Uint32Array]",it={};it[U]=it[j]=it[ne]=it[he]=it[B]=it[G]=it[fe]=it[ye]=it[Se]=it[De]=it[ze]=it[le]=it[ce]=it[ue]=it[N]=it[F]=it[X]=it[J]=it[Le]=it[Je]=it[ke]=it[We]=!0,it[Y]=it[Z]=it[ae]=!1;function _t(Dt,Qt,qt,wt,zt,Ot){var St,Lt=Qt&z,Bt=Qt&W,Kt=Qt&K;if(qt&&(St=zt?qt(Dt,wt,zt,Ot):qt(Dt)),St!==void 0)return St;if(!R(Dt))return Dt;var ai=P(Dt);if(ai){if(St=C(Dt),!Lt)return m(Dt,St)}else{var fi=b(Dt),kt=fi==Z||fi==te;if(w(Dt))return g(Dt,Lt);if(fi==ue||fi==U||kt&&!zt){if(St=Bt||kt?{}:E(Dt),!Lt)return Bt?y(Dt,p(St,Dt)):_(Dt,f(St,Dt))}else{if(!it[fi])return zt?Dt:{};St=A(Dt,fi,Lt)}}Ot||(Ot=new u);var Ft=Ot.get(Dt);if(Ft)return Ft;Ot.set(Dt,St),I(Dt)?Dt.forEach(function(Di){St.add(_t(Di,Qt,qt,Di,Dt,Ot))}):M(Dt)&&Dt.forEach(function(Di,mi){St.set(mi,_t(Di,Qt,qt,mi,Dt,Ot))});var Ht=Kt?Bt?x:v:Bt?k:D,ni=ai?void 0:Ht(Dt);return h(ni||Dt,function(Di,mi){ni&&(mi=Di,Di=Dt[mi]),d(St,mi,_t(Di,Qt,qt,mi,Dt,Ot))}),St}o.exports=_t},"../../../../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 g=new f;return f.prototype=void 0,g}}();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 g=-1,m=d.length;++g{var u=c("../../../../node_modules/lodash/_baseEach.js");function h(d,f){var p=[];return u(d,function(g,m,_){f(g,m,_)&&p.push(g)}),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,g,m,_){var y=-1,v=f.length;for(g||(g=h),_||(_=[]);++y0&&g(x)?p>1?d(x,p-1,g,m,_):u(_,x):m||(_[_.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 g=0,m=p.length;f!=null&&g{var u=c("../../../../node_modules/lodash/_arrayPush.js"),h=c("../../../../node_modules/lodash/isArray.js");function d(f,p,g){var m=p(f);return h(f)?m:u(m,g(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]",g=u?u.toStringTag:void 0;function m(_){return _==null?_===void 0?p:f:g&&g in Object(_)?h(_):d(_)}o.exports=m},"../../../../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,g,m){return g===g?d(p,g,m):u(p,h,m)}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,g,m,_){return f===p?!0:f==null||p==null||!h(f)&&!h(p)?f!==f&&p!==p:u(f,p,g,m,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"),g=c("../../../../node_modules/lodash/isArray.js"),m=c("../../../../node_modules/lodash/isBuffer.js"),_=c("../../../../node_modules/lodash/isTypedArray.js"),y=1,v="[object Arguments]",x="[object Array]",b="[object Object]",C=Object.prototype,A=C.hasOwnProperty;function E(P,w,M,R,I,D){var k=g(P),z=g(w),W=k?x:p(P),K=z?x:p(w);W=W==v?b:W,K=K==v?b:K;var U=W==b,j=K==b,B=W==K;if(B&&m(P)){if(!m(w))return!1;k=!0,U=!1}if(B&&!U)return D||(D=new u),k||_(P)?h(P,w,M,R,I,D):d(P,w,W,M,R,I,D);if(!(M&y)){var G=U&&A.call(P,"__wrapped__"),Y=j&&A.call(w,"__wrapped__");if(G||Y){var Z=G?P.value():P,te=Y?w.value():w;return D||(D=new u),I(Z,te,M,R,D)}}return B?(D||(D=new u),f(P,w,M,R,I,D)):!1}o.exports=E},"../../../../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(g,m,_,y){var v=_.length,x=v,b=!y;if(g==null)return!x;for(g=Object(g);v--;){var C=_[v];if(b&&C[2]?C[1]!==g[C[0]]:!(C[0]in g))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,g=/^\[object .+?Constructor\]$/,m=Function.prototype,_=Object.prototype,y=m.toString,v=_.hasOwnProperty,x=RegExp("^"+y.call(v).replace(p,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function b(C){if(!d(C)||h(C))return!1;var A=u(C)?x:g;return A.test(f(C))}o.exports=b},"../../../../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]",g="[object Boolean]",m="[object Date]",_="[object Error]",y="[object Function]",v="[object Map]",x="[object Number]",b="[object Object]",C="[object RegExp]",A="[object Set]",E="[object String]",P="[object WeakMap]",w="[object ArrayBuffer]",M="[object DataView]",R="[object Float32Array]",I="[object Float64Array]",D="[object Int8Array]",k="[object Int16Array]",z="[object Int32Array]",W="[object Uint8Array]",K="[object Uint8ClampedArray]",U="[object Uint16Array]",j="[object Uint32Array]",B={};B[R]=B[I]=B[D]=B[k]=B[z]=B[W]=B[K]=B[U]=B[j]=!0,B[f]=B[p]=B[w]=B[g]=B[M]=B[m]=B[_]=B[y]=B[v]=B[x]=B[b]=B[C]=B[A]=B[E]=B[P]=!1;function G(Y){return d(Y)&&h(Y.length)&&!!B[u(Y)]}o.exports=G},"../../../../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 g(m){return typeof m=="function"?m:m==null?d:typeof m=="object"?f(m)?h(m[0],m[1]):u(m):p(m)}o.exports=g},"../../../../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(g){if(!u(g))return h(g);var m=[];for(var _ in Object(g))f.call(g,_)&&_!="constructor"&&m.push(_);return m}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 g(m){if(!u(m))return d(m);var _=h(m),y=[];for(var v in m)v=="constructor"&&(_||!p.call(m,v))||y.push(v);return y}o.exports=g},"../../../../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 g=-1,m=h(f)?Array(f.length):[];return u(f,function(_,y,v){m[++g]=p(_,y,v)}),m}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 g=h(p);return g.length==1&&g[0][2]?d(g[0][0],g[0][1]):function(m){return m===p||u(m,p,g)}}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"),g=c("../../../../node_modules/lodash/_matchesStrictComparable.js"),m=c("../../../../node_modules/lodash/_toKey.js"),_=1,y=2;function v(x,b){return f(x)&&p(b)?g(m(x),b):function(C){var A=h(C,x);return A===void 0&&A===b?d(C,x):u(b,A,_|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"),g=c("../../../../node_modules/lodash/keysIn.js"),m=c("../../../../node_modules/lodash/_safeGet.js");function _(y,v,x,b,C){y!==v&&d(v,function(A,E){if(C||(C=new u),p(A))f(y,v,E,x,_,b,C);else{var P=b?b(m(y,E),A,E+"",y,v,C):void 0;P===void 0&&(P=A),h(y,E,P)}},g)}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"),g=c("../../../../node_modules/lodash/isArguments.js"),m=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"),b=c("../../../../node_modules/lodash/isPlainObject.js"),C=c("../../../../node_modules/lodash/isTypedArray.js"),A=c("../../../../node_modules/lodash/_safeGet.js"),E=c("../../../../node_modules/lodash/toPlainObject.js");function P(w,M,R,I,D,k,z){var W=A(w,R),K=A(M,R),U=z.get(K);if(U){u(w,R,U);return}var j=k?k(W,K,R+"",w,M,z):void 0,B=j===void 0;if(B){var G=m(K),Y=!G&&y(K),Z=!G&&!Y&&C(K);j=K,G||Y||Z?m(W)?j=W:_(W)?j=f(W):Y?(B=!1,j=h(K,!0)):Z?(B=!1,j=d(K,!0)):j=[]:b(K)||g(K)?(j=W,g(W)?j=E(W):(!x(W)||v(W))&&(j=p(K))):B=!1}B&&(z.set(K,j),D(j,K,I,k,z),z.delete(K)),u(w,R,j)}o.exports=P},"../../../../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"),g=c("../../../../node_modules/lodash/_baseUnary.js"),m=c("../../../../node_modules/lodash/_compareMultiple.js"),_=c("../../../../node_modules/lodash/identity.js"),y=c("../../../../node_modules/lodash/isArray.js");function v(x,b,C){b.length?b=u(b,function(P){return y(P)?function(w){return h(w,P.length===1?P[0]:P)}:P}):b=[_];var A=-1;b=u(b,g(d));var E=f(x,function(P,w,M){var R=u(b,function(I){return I(P)});return{criteria:R,index:++A,value:P}});return p(E,function(P,w){return m(P,w,C)})}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(g,m){return h(f,m)})}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,g,m){for(var _=-1,y=g.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 g=-1,m=c(l((d-h)/(f||1)),0),_=Array(m);m--;)_[p?m:++g]=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,g,m){h=d?(d=!1,p):u(h,p,g,m)}),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,g){return d(h(p,g,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 g(m,_,y,v){if(!f(m))return m;_=h(_,m);for(var x=-1,b=_.length,C=b-1,A=m;A!=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,g){return h(p,"toString",{configurable:!0,enumerable:!1,value:u(g),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,g=u?u.prototype:void 0,m=g?g.toString:void 0;function _(y){if(typeof y=="string")return y;if(d(y))return h(y,_)+"";if(f(y))return m?m.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"),g=c("../../../../node_modules/lodash/_setToArray.js"),m=200;function _(y,v,x){var b=-1,C=h,A=y.length,E=!0,P=[],w=P;if(x)E=!1,C=d;else if(A>=m){var M=v?null:p(y);if(M)return g(M);E=!1,C=f,w=new u}else w=v?[]:P;e:for(;++b{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,g={};++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(g,m){return u(g)?g:h(g,m)?[g]:d(f(g))}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,g=p?p.allocUnsafe:void 0;function m(_,y){if(y)return _.slice();var v=_.length,x=g?g(v):new _.constructor(v);return _.copy(x),x}o.exports=m},"../../../../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,g=d===null,m=d===d,_=u(d),y=f!==void 0,v=f===null,x=f===f,b=u(f);if(!v&&!b&&!_&&d>f||_&&y&&x&&!v&&!b||g&&y&&x||!p&&x||!m)return 1;if(!g&&!_&&!b&&d{var u=c("../../../../node_modules/lodash/_compareAscending.js");function h(d,f,p){for(var g=-1,m=d.criteria,_=f.criteria,y=m.length,v=p.length;++g=v)return x;var b=p[g];return x*(b=="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,g,m){var _=!g;g||(g={});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,g){var m=-1,_=g.length,y=_>1?g[_-1]:void 0,v=_>2?g[2]:void 0;for(y=f.length>3&&typeof y=="function"?(_--,y):void 0,v&&h(g[0],g[1],v)&&(y=_<3?void 0:y,_=1),p=Object(p);++m<_;){var x=g[m];x&&f(p,x,m,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,g){if(p==null)return p;if(!u(p))return d(p,g);for(var m=p.length,_=f?m:-1,y=Object(p);(f?_--:++_{function l(c){return function(u,h,d){for(var f=-1,p=Object(u),g=d(u),m=g.length;m--;){var _=g[c?m:++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(g,m,_){var y=Object(g);if(!h(g)){var v=u(m,3);g=d(g),m=function(b){return v(y[b],b,y)}}var x=p(g,m,_);return x>-1?y[v?g[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(g,m,_){return _&&typeof _!="number"&&h(g,m,_)&&(m=_=void 0),g=d(g),m===void 0?(m=g,g=0):m=d(m),_=_===void 0?g{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(g){return new u(g)}: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 g(m,_,y,v,x,b){var C=y&f,A=m.length,E=_.length;if(A!=E&&!(C&&E>A))return!1;var P=b.get(m),w=b.get(_);if(P&&w)return P==_&&w==m;var M=-1,R=!0,I=y&p?new u:void 0;for(b.set(m,_),b.set(_,m);++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"),g=c("../../../../node_modules/lodash/_setToArray.js"),m=1,_=2,y="[object Boolean]",v="[object Date]",x="[object Error]",b="[object Map]",C="[object Number]",A="[object RegExp]",E="[object Set]",P="[object String]",w="[object Symbol]",M="[object ArrayBuffer]",R="[object DataView]",I=u?u.prototype:void 0,D=I?I.valueOf:void 0;function k(z,W,K,U,j,B,G){switch(K){case R:if(z.byteLength!=W.byteLength||z.byteOffset!=W.byteOffset)return!1;z=z.buffer,W=W.buffer;case M:return!(z.byteLength!=W.byteLength||!B(new h(z),new h(W)));case y:case v:case C:return d(+z,+W);case x:return z.name==W.name&&z.message==W.message;case A:case P:return z==W+"";case b:var Y=p;case E:var Z=U&m;if(Y||(Y=g),z.size!=W.size&&!Z)return!1;var te=G.get(z);if(te)return te==W;U|=_,G.set(z,W);var le=f(Y(z),Y(W),U,j,B,G);return G.delete(z),le;case w:if(D)return D.call(z)==D.call(W)}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(g,m,_,y,v,x){var b=_&h,C=u(g),A=C.length,E=u(m),P=E.length;if(A!=P&&!b)return!1;for(var w=A;w--;){var M=C[w];if(!(b?M in m:f.call(m,M)))return!1}var R=x.get(g),I=x.get(m);if(R&&I)return R==m&&I==g;var D=!0;x.set(g,m),x.set(m,g);for(var k=b;++w{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),g=p.length;g--;){var m=p[g],_=f[m];p[g]=[m,_,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 g=h(f,p);return u(g)?g: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 g(m){var _=d.call(m,p),y=m[p];try{m[p]=void 0;var v=!0}catch{}var x=f.call(m);return v&&(_?m[p]=y:delete m[p]),x}o.exports=g},"../../../../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,g=p?function(m){return m==null?[]:(m=Object(m),u(p(m),function(_){return f.call(m,_)}))}:h;o.exports=g},"../../../../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,g=p?function(m){for(var _=[];m;)u(_,d(m)),m=h(m);return _}:f;o.exports=g},"../../../../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"),g=c("../../../../node_modules/lodash/_baseGetTag.js"),m=c("../../../../node_modules/lodash/_toSource.js"),_="[object Map]",y="[object Object]",v="[object Promise]",x="[object Set]",b="[object WeakMap]",C="[object DataView]",A=m(u),E=m(h),P=m(d),w=m(f),M=m(p),R=g;(u&&R(new u(new ArrayBuffer(1)))!=C||h&&R(new h)!=_||d&&R(d.resolve())!=v||f&&R(new f)!=x||p&&R(new p)!=b)&&(R=function(I){var D=g(I),k=D==y?I.constructor:void 0,z=k?m(k):"";if(z)switch(z){case A:return C;case E:return _;case P:return v;case w:return x;case M:return b}return D}),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"),g=c("../../../../node_modules/lodash/_toKey.js");function m(_,y,v){y=u(y,_);for(var x=-1,b=y.length,C=!1;++x{var l="\\ud800-\\udfff",c="\\u0300-\\u036f",u="\\ufe20-\\ufe2f",h="\\u20d0-\\u20ff",d=c+u+h,f="\\ufe0e\\ufe0f",p="\\u200d",g=RegExp("["+p+l+d+f+"]");function m(_){return g.test(_)}o.exports=m},"../../../../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(g){var m=this.__data__;if(u){var _=m[g];return _===h?void 0:_}return f.call(m,g)?m[g]: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 g=this.__data__;return u?g[p]!==void 0:d.call(g,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 g=this.__data__;return this.size+=this.has(f)?0:1,g[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"),g="[object Boolean]",m="[object Date]",_="[object Map]",y="[object Number]",v="[object RegExp]",x="[object Set]",b="[object String]",C="[object Symbol]",A="[object ArrayBuffer]",E="[object DataView]",P="[object Float32Array]",w="[object Float64Array]",M="[object Int8Array]",R="[object Int16Array]",I="[object Int32Array]",D="[object Uint8Array]",k="[object Uint8ClampedArray]",z="[object Uint16Array]",W="[object Uint32Array]";function K(U,j,B){var G=U.constructor;switch(j){case A:return u(U);case g:case m:return new G(+U);case E:return h(U,B);case P:case w:case M:case R:case I:case D:case k:case z:case W:return p(U,B);case _:return new G;case y:case b:return new G(U);case v:return d(U);case x:return new G;case C:return f(U)}}o.exports=K},"../../../../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(g){return d(g)||h(g)||!!(f&&g&&g[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(g,m,_){if(!f(_))return!1;var y=typeof m;return(y=="number"?h(_)&&d(m,_.length):y=="string"&&m in _)?u(_[m],g):!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(g,m){if(u(g))return!1;var _=typeof g;return _=="number"||_=="symbol"||_=="boolean"||g==null||h(g)?!0:f.test(g)||!d.test(g)||m!=null&&g in Object(m)}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 g=this.__data__,m=u(g,p);if(m<0)return!1;var _=g.length-1;return m==_?g.pop():d.call(g,m,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__,g=u(p,d);return g<0?(++this.size,p.push([d,f])):p[g][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),g=p.size;return p.set(d,f),this.size+=p.size==g?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(m){return g.size===h&&g.clear(),m}),g=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,g=function(){try{var m=d&&d.require&&d.require("util").types;return m||p&&p.binding&&p.binding("util")}catch{}}();o.exports=g},"../../../../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,g){return p=h(p===void 0?f.length-1:p,0),function(){for(var m=arguments,_=-1,y=h(m.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 g=u(),m=c-(g-p);if(p=g,m>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(g,m){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 g=[];return p.charCodeAt(0)===46&&g.push(""),p.replace(h,function(m,_,y,v){g.push(y?v.replace(d,"$1"):_||m)}),g});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+"]",g="["+d+"]",m="\\ud83c[\\udffb-\\udfff]",_="(?:"+g+"|"+m+")",y="[^"+l+"]",v="(?:\\ud83c[\\udde6-\\uddff]){2}",x="[\\ud800-\\udbff][\\udc00-\\udfff]",b="\\u200d",C=_+"?",A="["+f+"]?",E="(?:"+b+"(?:"+[y,v,x].join("|")+")"+A+C+")*",P=A+C+E,w="(?:"+[y+g+"?",g,v,x,p].join("|")+")",M=RegExp(m+"(?="+m+")|"+w+P,"g");function R(I){for(var D=M.lastIndex=0;M.test(I);)++D;return D}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,g=p.hasOwnProperty,m=u(function(_,y){_=Object(_);var v=-1,x=y.length,b=x>2?y[2]:void 0;for(b&&d(y[0],y[1],b)&&(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(g,m){var _=f(g)?u:h;return _(g,d(m,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(g,m,_){var y=g==null?0:g.length;if(!y)return-1;var v=_==null?0:d(_);return v<0&&(v=f(y+v,0)),u(g,h(m,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(g,m){var _=f(g)?u:h;return _(g,d(m))}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,g){return p==null?p:u(p,h(g),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 g=d==null?void 0:u(d,f);return g===void 0?p:g}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,g=u(function(){return arguments}())?u:function(m){return h(m)&&f.call(m,"callee")&&!p.call(m,"callee")};o.exports=g},"../../../../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,g=p?u.Buffer:void 0,m=g?g.isBuffer:void 0,_=m||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"),g=c("../../../../node_modules/lodash/isBuffer.js"),m=c("../../../../node_modules/lodash/_isPrototype.js"),_=c("../../../../node_modules/lodash/isTypedArray.js"),y="[object Map]",v="[object Set]",x=Object.prototype,b=x.hasOwnProperty;function C(A){if(A==null)return!0;if(p(A)&&(f(A)||typeof A=="string"||typeof A.splice=="function"||g(A)||_(A)||d(A)))return!A.length;var E=h(A);if(E==y||E==v)return!A.size;if(m(A))return!u(A).length;for(var P in A)if(b.call(A,P))return!1;return!0}o.exports=C},"../../../../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]",g="[object Proxy]";function m(_){if(!h(_))return!1;var y=u(_);return y==f||y==p||y==d||y==g}o.exports=m},"../../../../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,g=Object.prototype,m=p.toString,_=g.hasOwnProperty,y=m.call(Object);function v(x){if(!d(x)||u(x)!=f)return!1;var b=h(x);if(b===null)return!0;var C=_.call(b,"constructor")&&b.constructor;return typeof C=="function"&&C instanceof C&&m.call(C)==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(g){return typeof g=="string"||!h(g)&&d(g)&&u(g)==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(g,m){var _=f(g)?u:d;return _(g,h(m,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,g){var m={};return g=d(g,3),h(p,function(_,y,v){u(m,y,g(_,y,v))}),m}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 g=function(){var m=arguments,_=p?p.apply(this,m):m[0],y=g.cache;if(y.has(_))return y.get(_);var v=f.apply(this,m);return g.cache=y.set(_,v)||y,v};return g.cache=new(d.Cache||u),g}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,g){u(f,p,g)});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,g){return p&&p.length?u(p,h(g,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(g){return d(g)?u(f(g)):h(g)}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 g(m,_,y){var v=p(m)?u:f,x=arguments.length<3;return v(m,d(_,4),y,x,h)}o.exports=g},"../../../../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"),g="[object Map]",m="[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==g||v==m?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(g,m){if(g==null)return[];var _=m.length;return _>1&&f(g,m[0],m[1])?m=[]:_>2&&f(m[0],m[1],m[2])&&(m=[m[0]]),h(g,u(m,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 g=p<0?-1:1;return g*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,g=/^0b[01]+$/i,m=/^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 b=g.test(v);return b||m.test(v)?_(v.slice(2),b?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"),g=c("../../../../node_modules/lodash/isArray.js"),m=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(b,C,A){var E=g(b),P=E||m(b)||v(b);if(C=f(C,4),A==null){var w=b&&b.constructor;P?A=E?new w:[]:y(b)?A=_(w)?h(p(b)):{}:A={}}return(P?u:d)(b,function(M,R,I){return C(A,M,R,I)}),A}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(g){return d(u(g,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={},g=0;g<10;g++)p["_"+String.fromCharCode(g)]=g;var m=Object.getOwnPropertyNames(p).map(function(y){return p[y]});if(m.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 g,m=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(g){var m="Warning: "+g;typeof console<"u"&&console.error(m);try{throw new Error(m)}catch{}}}function p(g,m,_,y,v){for(var x in g)if(f(g,x)){var b;try{if(typeof g[x]!="function"){var C=Error((y||"React class")+": "+_+" type `"+x+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof g[x]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw C.name="Invariant Violation",C}b=g[x](m,x,y,_,null,h)}catch(E){b=E}if(b&&!(b 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 b+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),b instanceof Error&&!(b.message in d)){d[b.message]=!0;var A=v?v():"";u("Failed "+_+" type: "+b.message+(A??""))}}}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"),g=function(){};g=function(_){var y="Warning: "+_;typeof console<"u"&&console.error(y);try{throw new Error(y)}catch{}};function m(){return null}o.exports=function(_,y){var v=typeof Symbol=="function"&&Symbol.iterator,x="@@iterator";function b(F){var X=F&&(v&&F[v]||F[x]);if(typeof X=="function")return X}var C="<>",A={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:D(),elementType:k(),instanceOf:z,node:j(),objectOf:K,oneOf:W,oneOfType:U,shape:G,exact:Y};function E(F,X){return F===X?F!==0||1/F===1/X:F!==F&&X!==X}function P(F,X){this.message=F,this.data=X&&typeof X=="object"?X:{},this.stack=""}P.prototype=Error.prototype;function w(F){var X={},J=0;function ae(he,fe,ye,Se,De,ze,Le){if(Se=Se||C,ze=ze||ye,Le!==d){if(y){var Je=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 Je.name="Invariant Violation",Je}else if(typeof console<"u"){var ke=Se+":"+ye;!X[ke]&&J<3&&(g("You are manually calling a React.PropTypes validation function for the `"+ze+"` prop on `"+Se+"`. 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."),X[ke]=!0,J++)}}return fe[ye]==null?he?fe[ye]===null?new P("The "+De+" `"+ze+"` is marked as required "+("in `"+Se+"`, but its value is `null`.")):new P("The "+De+" `"+ze+"` is marked as required in "+("`"+Se+"`, but its value is `undefined`.")):null:F(fe,ye,Se,De,ze)}var ne=ae.bind(null,!1);return ne.isRequired=ae.bind(null,!0),ne}function M(F){function X(J,ae,ne,he,fe,ye){var Se=J[ae],De=le(Se);if(De!==F){var ze=ce(Se);return new P("Invalid "+he+" `"+fe+"` of type "+("`"+ze+"` supplied to `"+ne+"`, expected ")+("`"+F+"`."),{expectedType:F})}return null}return w(X)}function R(){return w(m)}function I(F){function X(J,ae,ne,he,fe){if(typeof F!="function")return new P("Property `"+fe+"` of component `"+ne+"` has invalid PropType notation inside arrayOf.");var ye=J[ae];if(!Array.isArray(ye)){var Se=le(ye);return new P("Invalid "+he+" `"+fe+"` of type "+("`"+Se+"` supplied to `"+ne+"`, expected an array."))}for(var De=0;De1?g("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])."):g("Invalid argument supplied to oneOf, expected an array."),m;function X(J,ae,ne,he,fe){for(var ye=J[ae],Se=0;Se0?", expected one of type ["+De.join(", ")+"]":"";return new P("Invalid "+ye+" `"+Se+"` supplied to "+("`"+fe+"`"+ke+"."))}return w(ae)}function j(){function F(X,J,ae,ne,he){return Z(X[J])?null:new P("Invalid "+ne+" `"+he+"` supplied to "+("`"+ae+"`, expected a ReactNode."))}return w(F)}function B(F,X,J,ae,ne){return new P((F||"React class")+": "+X+" type `"+J+"."+ae+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+ne+"`.")}function G(F){function X(J,ae,ne,he,fe){var ye=J[ae],Se=le(ye);if(Se!=="object")return new P("Invalid "+he+" `"+fe+"` of type `"+Se+"` "+("supplied to `"+ne+"`, expected `object`."));for(var De in F){var ze=F[De];if(typeof ze!="function")return B(ne,he,fe,De,ce(ze));var Le=ze(ye,De,ne,he,fe+"."+De,d);if(Le)return Le}return null}return w(X)}function Y(F){function X(J,ae,ne,he,fe){var ye=J[ae],Se=le(ye);if(Se!=="object")return new P("Invalid "+he+" `"+fe+"` of type `"+Se+"` "+("supplied to `"+ne+"`, expected `object`."));var De=h({},J[ae],F);for(var ze in De){var Le=F[ze];if(f(F,ze)&&typeof Le!="function")return B(ne,he,fe,ze,ce(Le));if(!Le)return new P("Invalid "+he+" `"+fe+"` key `"+ze+"` supplied to `"+ne+"`.\nBad object: "+JSON.stringify(J[ae],null," ")+` Valid keys: `+JSON.stringify(Object.keys(F),null," "));var Je=Le(ye,ze,ne,he,fe+"."+ze,d);if(Je)return Je}return null}return w(X)}function Z(F){switch(typeof F){case"number":case"string":case"undefined":return!0;case"boolean":return!F;case"object":if(Array.isArray(F))return F.every(Z);if(F===null||_(F))return!0;var X=b(F);if(X){var J=X.call(F),ae;if(X!==F.entries){for(;!(ae=J.next()).done;)if(!Z(ae.value))return!1}else for(;!(ae=J.next()).done;){var ne=ae.value;if(ne&&!Z(ne[1]))return!1}}else return!1;return!0;default:return!1}}function te(F,X){return F==="symbol"?!0:X?X["@@toStringTag"]==="Symbol"||typeof Symbol=="function"&&X instanceof Symbol:!1}function le(F){var X=typeof F;return Array.isArray(F)?"array":F instanceof RegExp?"object":te(X,F)?"symbol":X}function ce(F){if(typeof F>"u"||F===null)return""+F;var X=le(F);if(X==="object"){if(F instanceof Date)return"date";if(F instanceof RegExp)return"regexp"}return X}function ue(F){var X=ce(F);switch(X){case"array":case"object":return"an "+X;case"boolean":case"date":case"regexp":return"a "+X;default:return X}}function N(F){return!F.constructor||!F.constructor.name?C:F.constructor.name}return A.checkPropTypes=p,A.resetWarningCache=p.resetWarningCache,A.PropTypes=A,A}},"../../../../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,g=c?Symbol.for("react.provider"):60109,m=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,b=c?Symbol.for("react.suspense_list"):60120,C=c?Symbol.for("react.memo"):60115,A=c?Symbol.for("react.lazy"):60116,E=c?Symbol.for("react.block"):60121,P=c?Symbol.for("react.fundamental"):60117,w=c?Symbol.for("react.responder"):60118,M=c?Symbol.for("react.scope"):60119;function R(Le){return typeof Le=="string"||typeof Le=="function"||Le===d||Le===y||Le===p||Le===f||Le===x||Le===b||typeof Le=="object"&&Le!==null&&(Le.$$typeof===A||Le.$$typeof===C||Le.$$typeof===g||Le.$$typeof===m||Le.$$typeof===v||Le.$$typeof===P||Le.$$typeof===w||Le.$$typeof===M||Le.$$typeof===E)}function I(Le){if(typeof Le=="object"&&Le!==null){var Je=Le.$$typeof;switch(Je){case u:var ke=Le.type;switch(ke){case _:case y:case d:case p:case f:case x:return ke;default:var We=ke&&ke.$$typeof;switch(We){case m:case v:case A:case C:case g:return We;default:return Je}}case h:return Je}}}var D=_,k=y,z=m,W=g,K=u,U=v,j=d,B=A,G=C,Y=h,Z=p,te=f,le=x,ce=!1;function ue(Le){return ce||(ce=!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(Le)||I(Le)===_}function N(Le){return I(Le)===y}function F(Le){return I(Le)===m}function X(Le){return I(Le)===g}function J(Le){return typeof Le=="object"&&Le!==null&&Le.$$typeof===u}function ae(Le){return I(Le)===v}function ne(Le){return I(Le)===d}function he(Le){return I(Le)===A}function fe(Le){return I(Le)===C}function ye(Le){return I(Le)===h}function Se(Le){return I(Le)===p}function De(Le){return I(Le)===f}function ze(Le){return I(Le)===x}l.AsyncMode=D,l.ConcurrentMode=k,l.ContextConsumer=z,l.ContextProvider=W,l.Element=K,l.ForwardRef=U,l.Fragment=j,l.Lazy=B,l.Memo=G,l.Portal=Y,l.Profiler=Z,l.StrictMode=te,l.Suspense=le,l.isAsyncMode=ue,l.isConcurrentMode=N,l.isContextConsumer=F,l.isContextProvider=X,l.isElement=J,l.isForwardRef=ae,l.isFragment=ne,l.isLazy=he,l.isMemo=fe,l.isPortal=ye,l.isProfiler=Se,l.isStrictMode=De,l.isSuspense=ze,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 g(S){{for(var T=arguments.length,L=new Array(T>1?T-1:0),$=1;$1?T-1:0),$=1;$2&&(S[0]==="o"||S[0]==="O")&&(S[1]==="n"||S[1]==="N")}function St(S,T,L,$){if(L!==null&&L.type===ye)return!1;switch(typeof T){case"function":case"symbol":return!0;case"boolean":{if($)return!1;if(L!==null)return!L.acceptsBooleans;var q=S.toLowerCase().slice(0,5);return q!=="data-"&&q!=="aria-"}default:return!1}}function Lt(S,T,L,$){if(T===null||typeof T>"u"||St(S,T,L,$))return!0;if($)return!1;if(L!==null)switch(L.type){case ze:return!T;case Le:return T===!1;case Je:return isNaN(T);case ke:return isNaN(T)||T<1}return!1}function Bt(S){return ai.hasOwnProperty(S)?ai[S]:null}function Kt(S,T,L,$,q,se,de){this.acceptsBooleans=T===De||T===ze||T===Le,this.attributeName=$,this.attributeNamespace=q,this.mustUseProperty=L,this.propertyName=S,this.type=T,this.sanitizeURL=se,this.removeEmptyString=de}var ai={},fi=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];fi.forEach(function(S){ai[S]=new Kt(S,ye,!1,S,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(S){var T=S[0],L=S[1];ai[T]=new Kt(T,Se,!1,L,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(S){ai[S]=new Kt(S,De,!1,S.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(S){ai[S]=new Kt(S,De,!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){ai[S]=new Kt(S,ze,!1,S.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(S){ai[S]=new Kt(S,ze,!0,S,null,!1,!1)}),["capture","download"].forEach(function(S){ai[S]=new Kt(S,Le,!1,S,null,!1,!1)}),["cols","rows","size","span"].forEach(function(S){ai[S]=new Kt(S,ke,!1,S,null,!1,!1)}),["rowSpan","start"].forEach(function(S){ai[S]=new Kt(S,Je,!1,S.toLowerCase(),null,!1,!1)});var kt=/[\-\:]([a-z])/g,Ft=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 T=S.replace(kt,Ft);ai[T]=new Kt(T,Se,!1,S,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(function(S){var T=S.replace(kt,Ft);ai[T]=new Kt(T,Se,!1,S,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(S){var T=S.replace(kt,Ft);ai[T]=new Kt(T,Se,!1,S,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(S){ai[S]=new Kt(S,Se,!1,S.toLowerCase(),null,!1,!1)});var Ht="xlinkHref";ai[Ht]=new Kt("xlinkHref",Se,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(S){ai[S]=new Kt(S,Se,!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,Di=!1;function mi(S){!Di&&ni.test(S)&&(Di=!0,m("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 Ai(S,T,L,$){if($.mustUseProperty){var q=$.propertyName;return S[q]}else{$.sanitizeURL&&mi(""+L);var se=$.attributeName,de=null;if($.type===Le){if(S.hasAttribute(se)){var ve=S.getAttribute(se);return ve===""?!0:Lt(T,L,$,!1)?ve:ve===""+L?L:ve}}else if(S.hasAttribute(se)){if(Lt(T,L,$,!1))return S.getAttribute(se);if($.type===ze)return L;de=S.getAttribute(se)}return Lt(T,L,$,!1)?de===null?L:de:de===""+L?L:de}}function Ni(S,T,L){{if(!zt(T))return;if(oH(L))return L;if(!S.hasAttribute(T))return L===void 0?void 0:null;var $=S.getAttribute(T);return $===""+L?L:$}}function gi(S,T,L,$){var q=Bt(T);if(!Ot(T,q,$)){if(Lt(T,L,q,$)&&(L=null),$||q===null){if(zt(T)){var se=T;L===null?S.removeAttribute(se):S.setAttribute(se,""+L)}return}var de=q.mustUseProperty;if(de){var ve=q.propertyName;if(L===null){var Me=q.type;S[ve]=Me===ze?!1:""}else S[ve]=L;return}var Ve=q.attributeName,He=q.attributeNamespace;if(L===null)S.removeAttribute(Ve);else{var Ct=q.type,et;Ct===ze||Ct===Le&&L===!0?et="":(et=""+L,q.sanitizeURL&&mi(et.toString())),He?S.setAttributeNS(He,Ve,et):S.setAttribute(Ve,et)}}}var rt=60103,Ei=60106,Wi=60107,Gt=60108,At=60114,Ze=60109,Et=60110,Mt=60112,Xi=60113,or=60120,yi=60115,Yi=60116,Ue=60121,xt=60119,ri=60128,Ti=60129,_r=60130,tr=60131;if(typeof Symbol=="function"&&Symbol.for){var jt=Symbol.for;rt=jt("react.element"),Ei=jt("react.portal"),Wi=jt("react.fragment"),Gt=jt("react.strict_mode"),At=jt("react.profiler"),Ze=jt("react.provider"),Et=jt("react.context"),Mt=jt("react.forward_ref"),Xi=jt("react.suspense"),or=jt("react.suspense_list"),yi=jt("react.memo"),Yi=jt("react.lazy"),Ue=jt("react.block"),jt("react.server.block"),jt("react.fundamental"),xt=jt("react.scope"),ri=jt("react.opaque.id"),Ti=jt("react.debug_trace_mode"),_r=jt("react.offscreen"),tr=jt("react.legacy_hidden")}var si=typeof Symbol=="function"&&Symbol.iterator,Zi="@@iterator";function Vi(S){if(S===null||typeof S!="object")return null;var T=si&&S[si]||S[Zi];return typeof T=="function"?T:null}var yr=0,Rn,In,ss,Zn,fs,no,hr;function Lr(){}Lr.__reactDisabledLog=!0;function Wr(){{if(yr===0){Rn=console.log,In=console.info,ss=console.warn,Zn=console.error,fs=console.group,no=console.groupCollapsed,hr=console.groupEnd;var S={configurable:!0,enumerable:!0,value:Lr,writable:!0};Object.defineProperties(console,{info:S,log:S,warn:S,error:S,group:S,groupCollapsed:S,groupEnd:S})}yr++}}function jn(){{if(yr--,yr===0){var S={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:h({},S,{value:Rn}),info:h({},S,{value:In}),warn:h({},S,{value:ss}),error:h({},S,{value:Zn}),group:h({},S,{value:fs}),groupCollapsed:h({},S,{value:no}),groupEnd:h({},S,{value:hr})})}yr<0&&m("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Pa=p.ReactCurrentDispatcher,fa;function as(S,T,L){{if(fa===void 0)try{throw Error()}catch(q){var $=q.stack.trim().match(/\n( *(at )?)/);fa=$&&$[1]||""}return` `+fa+S}}var qo=!1,Jo;{var wa=typeof WeakMap=="function"?WeakMap:Map;Jo=new wa}function Yr(S,T){if(!S||qo)return"";{var L=Jo.get(S);if(L!==void 0)return L}var $;qo=!0;var q=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var se;se=Pa.current,Pa.current=null,Wr();try{if(T){var de=function(){throw Error()};if(Object.defineProperty(de.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(de,[])}catch(_i){$=_i}Reflect.construct(S,[],de)}else{try{de.call()}catch(_i){$=_i}S.call(de.prototype)}}else{try{throw Error()}catch(_i){$=_i}S()}}catch(_i){if(_i&&$&&typeof _i.stack=="string"){for(var ve=_i.stack.split(` `),Me=$.stack.split(` `),Ve=ve.length-1,He=Me.length-1;Ve>=1&&He>=0&&ve[Ve]!==Me[He];)He--;for(;Ve>=1&&He>=0;Ve--,He--)if(ve[Ve]!==Me[He]){if(Ve!==1||He!==1)do if(Ve--,He--,He<0||ve[Ve]!==Me[He]){var Ct=` `+ve[Ve].replace(" at new "," at ");return typeof S=="function"&&Jo.set(S,Ct),Ct}while(Ve>=1&&He>=0);break}}}finally{qo=!1,Pa.current=se,jn(),Error.prepareStackTrace=q}var et=S?S.displayName||S.name:"",Pt=et?as(et):"";return typeof S=="function"&&Jo.set(S,Pt),Pt}function kr(S,T,L){return Yr(S,!0)}function Ur(S,T,L){return Yr(S,!1)}function zr(S){var T=S.prototype;return!!(T&&T.isReactComponent)}function Nr(S,T,L){if(S==null)return"";if(typeof S=="function")return Yr(S,zr(S));if(typeof S=="string")return as(S);switch(S){case Xi:return as("Suspense");case or:return as("SuspenseList")}if(typeof S=="object")switch(S.$$typeof){case Mt:return Ur(S.render);case yi:return Nr(S.type,T,L);case Ue:return Ur(S._render);case Yi:{var $=S,q=$._payload,se=$._init;try{return Nr(se(q),T,L)}catch{}}}return""}function pn(S){switch(S._debugOwner&&S._debugOwner.type,S._debugSource,S.tag){case A:return as(S.type);case K:return as("Lazy");case k:return as("Suspense");case B:return as("SuspenseList");case y:case x:case W:return Ur(S.type);case I:return Ur(S.type.render);case Z:return Ur(S.type._render);case v:return kr(S.type);default:return""}}function qn(S){try{var T="",L=S;do T+=pn(L),L=L.return;while(L);return T}catch($){return` Error generating stack: `+$.message+` `+$.stack}}function Ms(S,T,L){var $=T.displayName||T.name||"";return S.displayName||($!==""?L+"("+$+")":L)}function pa(S){return S.displayName||"Context"}function Ii(S){if(S==null)return null;if(typeof S.tag=="number"&&m("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 Wi:return"Fragment";case Ei:return"Portal";case At:return"Profiler";case Gt:return"StrictMode";case Xi:return"Suspense";case or:return"SuspenseList"}if(typeof S=="object")switch(S.$$typeof){case Et:var T=S;return pa(T)+".Consumer";case Ze:var L=S;return pa(L._context)+".Provider";case Mt:return Ms(S,S.render,"ForwardRef");case yi:return Ii(S.type);case Ue:return Ii(S._render);case Yi:{var $=S,q=$._payload,se=$._init;try{return Ii(se(q))}catch{return null}}}return null}var Da=p.ReactDebugCurrentFrame,Pn=null,ra=!1;function sc(){{if(Pn===null)return null;var S=Pn._debugOwner;if(S!==null&&typeof S<"u")return Ii(S.type)}return null}function rr(){return Pn===null?"":qn(Pn)}function Ir(){Da.getCurrentStack=null,Pn=null,ra=!1}function nn(S){Da.getCurrentStack=rr,Pn=S,ra=!1}function Jn(S){ra=S}function ps(){return ra}function Fs(S){return""+S}function Oa(S){switch(typeof S){case"boolean":case"number":case"object":case"string":case"undefined":return S;default:return""}}var el={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0};function so(S,T){el[T.type]||T.onChange||T.onInput||T.readOnly||T.disabled||T.value==null||m("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`."),T.onChange||T.readOnly||T.disabled||T.checked==null||m("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 Zu(S){var T=S.type,L=S.nodeName;return L&&L.toLowerCase()==="input"&&(T==="checkbox"||T==="radio")}function Lf(S){return S._valueTracker}function sr(S){S._valueTracker=null}function Fr(S){var T="";return S&&(Zu(S)?T=S.checked?"true":"false":T=S.value),T}function Ae(S){var T=Zu(S)?"checked":"value",L=Object.getOwnPropertyDescriptor(S.constructor.prototype,T),$=""+S[T];if(!(S.hasOwnProperty(T)||typeof L>"u"||typeof L.get!="function"||typeof L.set!="function")){var q=L.get,se=L.set;Object.defineProperty(S,T,{configurable:!0,get:function(){return q.call(this)},set:function(ve){$=""+ve,se.call(this,ve)}}),Object.defineProperty(S,T,{enumerable:L.enumerable});var de={getValue:function(){return $},setValue:function(ve){$=""+ve},stopTracking:function(){sr(S),delete S[T]}};return de}}function qe(S){Lf(S)||(S._valueTracker=Ae(S))}function gt(S){if(!S)return!1;var T=Lf(S);if(!T)return!0;var L=T.getValue(),$=Fr(S);return $!==L?(T.setValue($),!0):!1}function ti(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 qi=!1,Jr=!1,lr=!1,$r=!1;function ms(S){var T=S.type==="checkbox"||S.type==="radio";return T?S.checked!=null:S.value!=null}function Xs(S,T){var L=S,$=T.checked,q=h({},T,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:$??L._wrapperState.initialChecked});return q}function La(S,T){so("input",T),T.checked!==void 0&&T.defaultChecked!==void 0&&!Jr&&(m("%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",sc()||"A component",T.type),Jr=!0),T.value!==void 0&&T.defaultValue!==void 0&&!qi&&(m("%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",sc()||"A component",T.type),qi=!0);var L=S,$=T.defaultValue==null?"":T.defaultValue;L._wrapperState={initialChecked:T.checked!=null?T.checked:T.defaultChecked,initialValue:Oa(T.value!=null?T.value:$),controlled:ms(T)}}function Ga(S,T){var L=S,$=T.checked;$!=null&&gi(L,"checked",$,!1)}function bl(S,T){var L=S;{var $=ms(T);!L._wrapperState.controlled&&$&&!$r&&(m("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),L._wrapperState.controlled&&!$&&!lr&&(m("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"),lr=!0)}Ga(S,T);var q=Oa(T.value),se=T.type;if(q!=null)se==="number"?(q===0&&L.value===""||L.value!=q)&&(L.value=Fs(q)):L.value!==Fs(q)&&(L.value=Fs(q));else if(se==="submit"||se==="reset"){L.removeAttribute("value");return}T.hasOwnProperty("value")?Ff(L,T.type,q):T.hasOwnProperty("defaultValue")&&Ff(L,T.type,Oa(T.defaultValue)),T.checked==null&&T.defaultChecked!=null&&(L.defaultChecked=!!T.defaultChecked)}function ac(S,T,L){var $=S;if(T.hasOwnProperty("value")||T.hasOwnProperty("defaultValue")){var q=T.type,se=q==="submit"||q==="reset";if(se&&(T.value===void 0||T.value===null))return;var de=Fs($._wrapperState.initialValue);L||de!==$.value&&($.value=de),$.defaultValue=de}var ve=$.name;ve!==""&&($.name=""),$.defaultChecked=!$.defaultChecked,$.defaultChecked=!!$._wrapperState.initialChecked,ve!==""&&($.name=ve)}function Ac(S,T){var L=S;bl(L,T),Nf(L,T)}function Nf(S,T){var L=T.name;if(T.type==="radio"&&L!=null){for(var $=S;$.parentNode;)$=$.parentNode;for(var q=$.querySelectorAll("input[name="+JSON.stringify(""+L)+'][type="radio"]'),se=0;se children."))))}),T.selected!=null&&!Qg&&(m("Use the `defaultValue` or `value` props on must be a scalar value if `multiple` is false.%s",L,qg())}}}}function cm(S,T,L,$){var q=S.options;if(T){for(var se=L,de={},ve=0;ve.");var $=h({},T,{value:void 0,defaultValue:void 0,children:Fs(L._wrapperState.initialValue)});return $}function L3(S,T){var L=S;so("textarea",T),T.value!==void 0&&T.defaultValue!==void 0&&!vb&&(m("%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",sc()||"A component"),vb=!0);var $=T.value;if($==null){var q=T.children,se=T.defaultValue;if(q!=null){m("Use the `defaultValue` or `value` props instead of setting children on