diff --git "a/static/assets/PlaygroundView-YI_MQmbd.js" "b/static/assets/PlaygroundView-YI_MQmbd.js" new file mode 100644--- /dev/null +++ "b/static/assets/PlaygroundView-YI_MQmbd.js" @@ -0,0 +1,12143 @@ +var a2=Object.defineProperty;var o2=(a,e,t)=>e in a?a2(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var So=(a,e,t)=>(o2(a,typeof e!="symbol"?e+"":e,t),t);import{B as pc,O as Ks,u as l2,m as Yr,o as dr,c as $r,r as zm,a as jR,t as ng,b as ro,R as h2,d as _A,e as c2,w as qR,n as mA,f as ag,g as sc,h as QR,i as ZR,j as Xl,k as u2,l as d2,p as JR,q as f2,v as p2,s as Wm,x as Yf,F as gA,y as xA,z as _2,A as m2,_ as g2,C as tE,D as x2}from"./index-_AMKSAVd.js";var T2={root:function(e){var t=e.props,i=e.instance;return["p-badge p-component",{"p-badge-no-gutter":Ks.isNotEmpty(t.value)&&String(t.value).length===1,"p-badge-dot":Ks.isEmpty(t.value)&&!i.$slots.default,"p-badge-lg":t.size==="large","p-badge-xl":t.size==="xlarge","p-badge-info":t.severity==="info","p-badge-success":t.severity==="success","p-badge-warning":t.severity==="warning","p-badge-danger":t.severity==="danger","p-badge-secondary":t.severity==="secondary","p-badge-contrast":t.severity==="contrast"}]}},E2=pc.extend({name:"badge",classes:T2});function yp(a){"@babel/helpers - typeof";return yp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yp(a)}function TA(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(a);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),t.push.apply(t,i)}return t}function S2(a){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};return l2(e,S2({name:"global"},t))}});function Ap(a){"@babel/helpers - typeof";return Ap=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ap(a)}function y2(a){return iI(a)||A2(a)||tI(a)||eI()}function A2(a){if(typeof Symbol<"u"&&a[Symbol.iterator]!=null||a["@@iterator"]!=null)return Array.from(a)}function Im(a,e){return iI(a)||R2(a,e)||tI(a,e)||eI()}function eI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tI(a,e){if(a){if(typeof a=="string")return EA(a,e);var t=Object.prototype.toString.call(a).slice(8,-1);if(t==="Object"&&a.constructor&&(t=a.constructor.name),t==="Map"||t==="Set")return Array.from(a);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return EA(a,e)}}function EA(a,e){(e==null||e>a.length)&&(e=a.length);for(var t=0,i=new Array(e);t1?t-1:0),s=1;s1&&arguments[1]!==void 0?arguments[1]:"",i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=Ks.toFlatCase(t).split("."),r=s.shift();return r?Ks.isObject(e)?this._getOptionValue(Ks.getItemValue(e[Object.keys(e).find(function(n){return Ks.toFlatCase(n)===r})||""],i),s.join("."),i):void 0:Ks.getItemValue(e,i)},_getPTValue:function(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,n=/./g.test(i)&&!!s[i.split(".")[0]],o=this._getPropValue("ptOptions")||((e=this.$config)===null||e===void 0?void 0:e.ptOptions)||{},l=o.mergeSections,h=l===void 0?!0:l,c=o.mergeProps,u=c===void 0?!1:c,d=r?n?this._useGlobalPT(this._getPTClassValue,i,s):this._useDefaultPT(this._getPTClassValue,i,s):void 0,f=n?void 0:this._getPTSelf(t,this._getPTClassValue,i,Ss(Ss({},s),{},{global:d||{}})),m=this._getPTDatasets(i);return h||!h&&f?u?this._mergeProps(u,d,f,m):Ss(Ss(Ss({},d),f),m):Ss(Ss({},f),m)},_getPTSelf:function(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length,i=new Array(t>1?t-1:0),s=1;s0&&arguments[0]!==void 0?arguments[0]:"",s="data-pc-",r=i==="root"&&Ks.isNotEmpty((e=this.pt)===null||e===void 0?void 0:e["data-pc-section"]);return i!=="transition"&&Ss(Ss({},i==="root"&&Ss(Hm({},"".concat(s,"name"),Ks.toFlatCase(r?(t=this.pt)===null||t===void 0?void 0:t["data-pc-section"]:this.$.type.name)),r&&Hm({},"".concat(s,"extend"),Ks.toFlatCase(this.$.type.name)))),{},Hm({},"".concat(s,"section"),Ks.toFlatCase(i)))},_getPTClassValue:function(){var e=this._getOptionValue.apply(this,arguments);return Ks.isString(e)||Ks.isArray(e)?{class:e}:e},_getPT:function(e){var t=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",s=arguments.length>2?arguments[2]:void 0,r=function(o){var l,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,c=s?s(o):o,u=Ks.toFlatCase(i),d=Ks.toFlatCase(t.$name);return(l=h?u!==d?c==null?void 0:c[u]:void 0:c==null?void 0:c[u])!==null&&l!==void 0?l:c};return e!=null&&e.hasOwnProperty("_usept")?{_usept:e._usept,originalValue:r(e.originalValue),value:r(e.value)}:r(e,!0)},_usePT:function(e,t,i,s){var r=function(_){return t(_,i,s)};if(e!=null&&e.hasOwnProperty("_usept")){var n,o=e._usept||((n=this.$config)===null||n===void 0?void 0:n.ptOptions)||{},l=o.mergeSections,h=l===void 0?!0:l,c=o.mergeProps,u=c===void 0?!1:c,d=r(e.originalValue),f=r(e.value);return d===void 0&&f===void 0?void 0:Ks.isString(f)?f:Ks.isString(d)?d:h||!h&&f?u?this._mergeProps(u,d,f):Ss(Ss({},d),f):f}return r(e)},_useGlobalPT:function(e,t,i){return this._usePT(this.globalPT,e,t,i)},_useDefaultPT:function(e,t,i){return this._usePT(this.defaultPT,e,t,i)},ptm:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this._getPTValue(this.pt,e,Ss(Ss({},this.$params),t))},ptmi:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Yr(this.$_attrsNoPT,this.ptm(e,t))},ptmo:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._getPTValue(e,t,Ss({instance:this},i),!1)},cx:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.isUnstyled?void 0:this._getOptionValue(this.$style.classes,e,Ss(Ss({},this.$params),t))},sx:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(t){var s=this._getOptionValue(this.$style.inlineStyles,e,Ss(Ss({},this.$params),i)),r=this._getOptionValue(iE.inlineStyles,e,Ss(Ss({},this.$params),i));return[r,s]}}},computed:{globalPT:function(){var e,t=this;return this._getPT((e=this.$config)===null||e===void 0?void 0:e.pt,void 0,function(i){return Ks.getItemValue(i,{instance:t})})},defaultPT:function(){var e,t=this;return this._getPT((e=this.$config)===null||e===void 0?void 0:e.pt,void 0,function(i){return t._getOptionValue(i,t.$name,Ss({},t.$params))||Ks.getItemValue(i,Ss({},t.$params))})},isUnstyled:function(){var e;return this.unstyled!==void 0?this.unstyled:(e=this.$config)===null||e===void 0?void 0:e.unstyled},$params:function(){var e=this._getHostInstance(this)||this.$parent;return{instance:this,props:this.$props,state:this.$data,attrs:this.$attrs,parent:{instance:e,props:e==null?void 0:e.$props,state:e==null?void 0:e.$data,attrs:e==null?void 0:e.$attrs},parentInstance:e}},$style:function(){return Ss(Ss({classes:void 0,inlineStyles:void 0,loadStyle:function(){},loadCustomStyle:function(){}},(this._getHostInstance(this)||{}).$style),this.$options.style)},$config:function(){var e;return(e=this.$primevue)===null||e===void 0?void 0:e.config},$name:function(){return this.$options.hostName||this.$.type.name},$_attrsPT:function(){return Object.entries(this.$attrs||{}).filter(function(e){var t=Im(e,1),i=t[0];return i==null?void 0:i.startsWith("pt:")}).reduce(function(e,t){var i=Im(t,2),s=i[0],r=i[1],n=s.split(":"),o=y2(n),l=o.slice(1);return l==null||l.reduce(function(h,c,u,d){return!h[c]&&(h[c]=u===d.length-1?r:{}),h[c]},e),e},{})},$_attrsNoPT:function(){return Object.entries(this.$attrs||{}).filter(function(e){var t=Im(e,1),i=t[0];return!(i!=null&&i.startsWith("pt:"))}).reduce(function(e,t){var i=Im(t,2),s=i[0],r=i[1];return e[s]=r,e},{})}}},M2={name:"BaseBadge",extends:e_,props:{value:{type:[String,Number],default:null},severity:{type:String,default:null},size:{type:String,default:null}},style:E2,provide:function(){return{$parentInstance:this}}},sI={name:"Badge",extends:M2,inheritAttrs:!1};function O2(a,e,t,i,s,r){return dr(),$r("span",Yr({class:a.cx("root")},a.ptmi("root")),[zm(a.$slots,"default",{},function(){return[jR(ng(a.value),1)]})],16)}sI.render=O2;var D2=` +.p-icon { + display: inline-block; +} + +.p-icon-spin { + -webkit-animation: p-icon-spin 2s infinite linear; + animation: p-icon-spin 2s infinite linear; +} + +@-webkit-keyframes p-icon-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} + +@keyframes p-icon-spin { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} +`,N2=pc.extend({name:"baseicon",css:D2});function Rp(a){"@babel/helpers - typeof";return Rp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Rp(a)}function vA(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(a);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),t.push.apply(t,i)}return t}function CA(a){for(var e=1;ee=e.concat(t.bones)),e}}xs._BabylonFileParsers={};xs._IndividualBabylonFileParsers={};class Wn{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in Wn.Triggers)if(Object.prototype.hasOwnProperty.call(Wn.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Wn.Triggers)if(Object.prototype.hasOwnProperty.call(Wn.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Wn.Triggers)if(Object.prototype.hasOwnProperty.call(Wn.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Wn.Triggers={};class aI{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class tU{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 K{static FromPromise(e,t){const i=new K;return e.then(s=>{i.notifyObservers(s)}).catch(s=>{if(t)t.notifyObservers(s);else throw s}),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 aI(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new tU(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}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,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?n.lastReturnValue=o.callback.apply(o.scope,[e,n]):n.lastReturnValue=o.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}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 K;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 ip=1/2.2,Ym=2.2,At=.001;class Os{static BuildArray(e,t){const i=[];for(let s=0;s{const r=s.previous;if(!r)return;const n=s.next;n?(r.next=n,n.previous=r):(r.next=void 0,a[e]=r),s.next=void 0,s.previous=void 0}}const sU=["push","splice","pop","shift","unshift"];function oI(a,e){const t=sU.map(i=>iU(a,i,e));return()=>{t.forEach(i=>{i==null||i()})}}const lI={};function H(a,e){lI[a]=e}function rs(a){return lI[a]}class ur{static SetMatrixPrecision(e){if(ur.MatrixTrackPrecisionChange=!1,e&&!ur.MatrixUse64Bits&&ur.MatrixTrackedMatrices)for(let t=0;tparseInt(a.toString().replace(/\W/g,""));class ce{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=Tn(this.x),t=Tn(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 ce.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 this.constructor(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 this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(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 this.constructor(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.copyFromFloats(this.x-e,this.y-t)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(this.x*-1,this.y*-1)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new this.constructor(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=At){return e&&Or(this.x,e.x,t)&&Or(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new this.constructor(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 this.constructor(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),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,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 this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new ce(0,0)}static One(){return new ce(1,1)}static Random(e=0,t=1){return new ce(ni(e,t),ni(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ni(e,t),ni(e,t))}static get ZeroReadOnly(){return ce._ZeroReadOnly}static FromArray(e,t=0){return new ce(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,s,r){const n=r*r,o=r*n,l=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),h=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new e.constructor(l,h)}static ClampToRef(e,t,i,s){return s.x=ts(e.x,t.x,i.x),s.y=ts(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=ts(e.x,t.x,i.x),r=ts(e.y,t.y,i.y);return new e.constructor(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.x*l+i.x*h+t.x*c+s.x*u,f=e.y*l+i.y*h+t.y*c+s.y*u;return new e.constructor(d,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=(o-r)*6*e.x+(3*o-4*r+1)*t.x+(-o+r)*6*i.x+(3*o-2*r)*s.x,n.y=(o-r)*6*e.y+(3*o-4*r+1)*t.y+(-o+r)*6*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new e.constructor(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){const t=new e.constructor;return ce.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new e.constructor(i,s)}static Transform(e,t){const i=new e.constructor;return ce.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&l>0&&o+l<2*r*n}static Distance(e,t){return Math.sqrt(ce.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){const i=new e.constructor;return ce.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=ce.DistanceSquared(t,i);if(s===0)return ce.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,ce.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return ce.Distance(e,o)}}ce._ZeroReadOnly=ce.Zero();Object.defineProperties(ce.prototype,{dimension:{value:[2]},rank:{value:1}});class T{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=Tn(this._x),t=Tn(this._y),i=Tn(this._z);let s=e;return s=s*397^t,s=s*397^i,s}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 T.FromArrayToRef(e,t,this),this}toQuaternion(){return ae.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 this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(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 this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-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.copyFromFloats(this._x*-1,this._y*-1,this._z*-1)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,l=e._z,h=e._w,c=2*(o*r-l*s),u=2*(l*i-n*r),d=2*(n*s-o*i);return t._x=i+h*c+o*d-l*u,t._y=s+h*u+l*c-n*d,t._z=r+h*d+n*u-o*c,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){const i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=qe.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=T.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const l=-(T.Dot(t,s)+r)/o,h=n.scaleInPlace(l);t.addToRef(h,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=At){return e&&Or(this._x,e._x,t)&&Or(this._y,e._y,t)&&Or(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.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}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(!Or(t,i,e))return!0;const s=Math.abs(this._z);return!Or(t,s,e)||!Or(i,s,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 this.constructor(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 this.constructor(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=qe.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(qe.Matrix[0]),T.TransformCoordinatesToRef(this,qe.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,qe.Vector3[0]),qe.Vector3[0].rotateByQuaternionToRef(e,qe.Vector3[0]),t.addToRef(qe.Vector3[0],i),i}cross(e){const t=new this.constructor;return T.CrossToRef(this,e,t)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new this.constructor(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,s){const r=T.Dot(e,i),n=T.Dot(t,i);return(r-s)/(r-n)}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(qe.Vector3[1]),r=t.normalizeToRef(qe.Vector3[2]);let n=T.Dot(s,r);n=ts(n,-1,1);const o=Math.acos(n),l=qe.Vector3[3];return T.CrossToRef(s,r,l),T.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){qe.Vector3[0].copyFrom(e);const s=qe.Vector3[0];qe.Vector3[1].copyFrom(t);const r=qe.Vector3[1];qe.Vector3[2].copyFrom(i);const n=qe.Vector3[2],o=qe.Vector3[3],l=qe.Vector3[4];s.normalize(),r.normalize(),n.normalize(),T.CrossToRef(n,s,o),T.CrossToRef(o,n,l);const h=Math.atan2(T.Dot(r,o),T.Dot(r,l));return hI(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=W.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=T.Zero();return T.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=ts(i,0,1);const r=qe.Vector3[0],n=qe.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const l=n.length();n.normalizeFromLength(l);const h=T.Dot(r,n);let c,u;if(h<1-At){const d=Math.acos(h),f=1/Math.sin(d);c=Math.sin((1-i)*d)*f,u=Math.sin(i*d)*f}else c=1-i,u=i;return r.scaleInPlace(c),n.scaleInPlace(u),s.copyFrom(r).addInPlace(n),s.scaleInPlace(wn(o,l,i)),s}static SmoothToRef(e,t,i,s,r){return T.SlerpToRef(e,t,s===0?1:i/s,r),r}static FromArray(e,t=0){return new T(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return T.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 T.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new T(0,0,0)}static One(){return new T(1,1,1)}static Up(){return new T(0,1,0)}static get UpReadOnly(){return T._UpReadOnly}static get DownReadOnly(){return T._DownReadOnly}static get RightReadOnly(){return T._RightReadOnly}static get LeftReadOnly(){return T._LeftReadOnly}static get LeftHandedForwardReadOnly(){return T._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return T._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return T._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return T._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return T._ZeroReadOnly}static get OneReadOnly(){return T._OneReadOnly}static Down(){return new T(0,-1,0)}static Forward(e=!1){return new T(0,0,e?-1:1)}static Backward(e=!1){return new T(0,0,e?1:-1)}static Right(){return new T(1,0,0)}static Left(){return new T(-1,0,0)}static Random(e=0,t=1){return new T(ni(e,t),ni(e,t),ni(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ni(e,t),ni(e,t),ni(e,t))}static TransformCoordinates(e,t){const i=T.Zero();return T.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return T.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],c=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*c,r._y=l*c,r._z=h*c,r._isDirty=!0,r}static TransformNormal(e,t){const i=T.Zero();return T.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,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,l=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),h=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),c=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new e.constructor(l,h,c)}static Clamp(e,t,i){const s=new e.constructor;return T.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&B<0?(ne.copyFrom(n),de=t,ge=i):B>0&&Q<0?(ne.copyFrom(l),de=i,ge=s):(ne.copyFrom(o).scaleInPlace(-1),de=s,ge=t);const fe=qe.Vector3[9],Ee=qe.Vector3[4];if(de.subtractToRef(S,I),ge.subtractToRef(S,fe),T.CrossToRef(I,fe,Ee),!(T.Dot(Ee,h)<0))return r.copyFrom(S),Math.abs(_*x);const Te=qe.Vector3[5];T.CrossToRef(ne,Ee,Te),Te.normalize();const ue=qe.Vector3[9];ue.copyFrom(de).subtractInPlace(S);const oe=ue.length();if(oethis.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,s){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(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){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(s,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 this.constructor(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 this.constructor(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(){const e=new this.constructor;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return t===0||t===1?e.copyFrom(this):this.scaleToRef(1/t,e)}toVector3(){return new T(this.x,this.y,this.z)}clone(){return new this.constructor(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,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}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 tt(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 tt.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new tt(0,0,0,0)}static One(){return new tt(1,1,1,1)}static Random(e=0,t=1){return new tt(ni(e,t),ni(e,t),ni(e,t),ni(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ni(e,t),ni(e,t),ni(e,t),ni(e,t))}static Clamp(e,t,i){const s=new e.constructor;return tt.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ts(e.x,t.x,i.x),ts(e.y,t.y,i.y),ts(e.z,t.z,i.z),ts(e.w,t.w,i.w))}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return tt._ZeroReadOnly}static Normalize(e){const t=tt.Zero();return tt.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(tt.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return tt.CenterToRef(e,t,tt.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)}static TransformCoordinates(e,t){const i=tt.Zero();return tt.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return tt.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],l=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],c=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=l,r.z=h,r.w=c,r}static TransformNormal(e,t){const i=new e.constructor;return tt.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new tt(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}tt._ZeroReadOnly=tt.Zero();Object.defineProperties(tt.prototype,{dimension:{value:[4]},rank:{value:1}});class ae{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,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){const e=Tn(this._x),t=Tn(this._y),i=Tn(this._z),s=Tn(this._w);let r=e;return r=r*397^t,r=r*397^i,r=r*397^s,r}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 ae.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=At){return e&&Or(this._x,e._x,t)&&Or(this._y,e._y,t)&&Or(this._z,e._z,t)&&Or(this._w,e._w,t)}clone(){return new this.constructor(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,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new this.constructor(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,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,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,s){return this.subtractFromFloatsToRef(e,t,i,s,new this.constructor)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(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,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,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 this.constructor)}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,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}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 this.constructor(-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 this.constructor(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=T.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const l=r*r,h=t*t,c=i*i,u=s*s;e._z=Math.atan2(2*(i*s+t*r),-h-c+u+l),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),h-c-u+l),e._isDirty=!0}return e}toRotationMatrix(e){return L.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return ae.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 ae;return ae.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],l=i[5],h=i[9],c=i[2],u=i[6],d=i[10],f=s+l+d;let m;return f>0?(m=.5/Math.sqrt(f+1),t._w=.25/m,t._x=(u-h)*m,t._y=(n-c)*m,t._z=(o-r)*m,t._isDirty=!0):s>l&&s>d?(m=2*Math.sqrt(1+s-l-d),t._w=(u-h)/m,t._x=.25*m,t._y=(r+o)/m,t._z=(n+c)/m,t._isDirty=!0):l>d?(m=2*Math.sqrt(1+l-s-d),t._w=(n-c)/m,t._x=(r+o)/m,t._y=.25*m,t._z=(h+u)/m,t._isDirty=!0):(m=2*Math.sqrt(1+d-s-l),t._w=(o-r)/m,t._x=(n+c)/m,t._y=(h+u)/m,t._z=.25*m,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 s=ae.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=s===0?1:i/s;return n=ts(n,0,1),ae.SlerpToRef(e,t,n,r),r}static Zero(){return new ae(0,0,0,0)}static Inverse(e){return new e.constructor(-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 ae(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 ae.RotationAxisToRef(e,t,new ae)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new ae(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,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new ae;return ae.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return ae.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new ae;return ae.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return ae.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=At){const r=T.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(T.CrossToRef(e,t,W.Vector3[0]),i.set(W.Vector3[0].x,W.Vector3[0].y,W.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new ae;return ae.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=i*.5,n=t*.5,o=e*.5,l=Math.sin(r),h=Math.cos(r),c=Math.sin(n),u=Math.cos(n),d=Math.sin(o),f=Math.cos(o);return s._x=f*c*h+d*u*l,s._y=d*u*h-f*c*l,s._z=f*u*l-d*c*h,s._w=f*u*h+d*c*l,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new ae;return ae.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=(i+e)*.5,n=(i-e)*.5,o=t*.5;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new ae(0,0,0,0);return ae.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=qe.Matrix[0];return L.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),ae.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new ae;return ae.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=qe.Matrix[0];return L.LookDirectionLHToRef(e,t,s),ae.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new ae;return ae.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=qe.Matrix[0];return L.LookDirectionRHToRef(e,t,s),ae.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=ae.Identity();return ae.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,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)n=1-i,r=l?-i:i;else{const h=Math.acos(o),c=1/Math.sin(h);n=Math.sin((1-i)*h)*c,r=l?-Math.sin(i*h)*c:Math.sin(i*h)*c}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e._x*l+i._x*h+t._x*c+s._x*u,f=e._y*l+i._y*h+t._y*c+s._y*u,m=e._z*l+i._z*h+t._z*c+s._z*u,_=e._w*l+i._w*h+t._w*c+s._w*u;return new e.constructor(d,f,m,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=(o-r)*6*e._x+(3*o-4*r+1)*t._x+(-o+r)*6*i._x+(3*o-2*r)*s._x,n._y=(o-r)*6*e._y+(3*o-4*r+1)*t._y+(-o+r)*6*i._y+(3*o-2*r)*s._y,n._z=(o-r)*6*e._z+(3*o-4*r+1)*t._z+(-o+r)*6*i._z+(3*o-2*r)*s._z,n._w=(o-r)*6*e._w+(3*o-4*r+1)*t._w+(-o+r)*6*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=ae.Zero();return ae.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new e.constructor;return ae.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(ts(e.x,t.x,i.x),ts(e.y,t.y,i.y),ts(e.z,t.z,i.z),ts(e.w,t.w,i.w))}static Random(e=0,t=1){return new ae(ni(e,t),ni(e,t),ni(e,t),ni(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ni(e,t),ni(e,t),ni(e,t),ni(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(ae.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return ae.CenterToRef(e,t,ae.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(ae.prototype,{dimension:{value:[4]},rank:{value:1}});class L{static get Use64Bits(){return ur.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=L._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,ur.MatrixTrackPrecisionChange&&ur.MatrixTrackedMatrices.push(this),this._m=new ur.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],s=e[2],r=e[3],n=e[4],o=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],f=e[11],m=e[12],_=e[13],x=e[14],E=e[15],S=d*E-x*f,C=u*E-_*f,y=u*x-_*d,A=c*E-m*f,I=c*x-d*m,R=c*_-m*u,N=+(o*S-l*C+h*y),k=-(n*S-l*A+h*I),B=+(n*C-o*A+h*R),Q=-(n*y-o*I+l*R);return t*N+i*k+s*B+r*Q}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 s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return L.FromArrayToRef(e,t,this)}copyFromFloats(...e){return L.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 L.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 this.constructor;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let n=0;n<16;n++)s[n]=i[n]+r[n];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]+=i[s];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 s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]-s[n];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]-=i[s];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new this.constructor)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]-r[n];return t.markAsUpdated(),t}invertToRef(e){if(this._isIdentity===!0)return L.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],f=t[10],m=t[11],_=t[12],x=t[13],E=t[14],S=t[15],C=f*S-E*m,y=d*S-x*m,A=d*E-x*f,I=u*S-_*m,R=u*E-f*_,N=u*x-_*d,k=+(l*C-h*y+c*A),B=-(o*C-h*I+c*R),Q=+(o*y-l*I+c*N),ne=-(o*A-l*R+h*N),de=i*k+s*B+r*Q+n*ne;if(de===0)return e.copyFrom(this),e;const ge=1/de,fe=h*S-E*c,Ee=l*S-x*c,De=l*E-x*h,Te=o*S-_*c,ue=o*E-_*h,oe=o*x-_*l,F=h*m-f*c,ie=l*m-d*c,he=l*f-d*h,ke=o*m-u*c,Ye=o*f-u*h,et=o*d-u*l,ye=-(s*C-r*y+n*A),Ae=+(i*C-r*I+n*R),rt=-(i*y-s*I+n*N),Ze=+(i*A-s*R+r*N),Et=+(s*fe-r*Ee+n*De),Re=-(i*fe-r*Te+n*ue),St=+(i*Ee-s*Te+n*oe),Lt=-(i*De-s*ue+r*oe),Ci=-(s*F-r*ie+n*he),ki=+(i*F-r*ke+n*Ye),Ts=-(i*ie-s*ke+n*et),ar=+(i*he-s*Ye+r*et);return L.FromValuesToRef(k*ge,ye*ge,Et*ge,Ci*ge,B*ge,Ae*ge,Re*ge,ki*ge,Q*ge,rt*ge,St*ge,Ts*ge,ne*ge,Ze*ge,Lt*ge,ar*ge,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 T(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 L.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 this.constructor;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]*=i[s];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,s=t._m,r=e;for(let n=0;n<16;n++)s[n]=i[n]*r[n];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 s=this._m,r=e.m,n=s[0],o=s[1],l=s[2],h=s[3],c=s[4],u=s[5],d=s[6],f=s[7],m=s[8],_=s[9],x=s[10],E=s[11],S=s[12],C=s[13],y=s[14],A=s[15],I=r[0],R=r[1],N=r[2],k=r[3],B=r[4],Q=r[5],ne=r[6],de=r[7],ge=r[8],fe=r[9],Ee=r[10],De=r[11],Te=r[12],ue=r[13],oe=r[14],F=r[15];return t[i]=n*I+o*B+l*ge+h*Te,t[i+1]=n*R+o*Q+l*fe+h*ue,t[i+2]=n*N+o*ne+l*Ee+h*oe,t[i+3]=n*k+o*de+l*De+h*F,t[i+4]=c*I+u*B+d*ge+f*Te,t[i+5]=c*R+u*Q+d*fe+f*ue,t[i+6]=c*N+u*ne+d*Ee+f*oe,t[i+7]=c*k+u*de+d*De+f*F,t[i+8]=m*I+_*B+x*ge+E*Te,t[i+9]=m*R+_*Q+x*fe+E*ue,t[i+10]=m*N+_*ne+x*Ee+E*oe,t[i+11]=m*k+_*de+x*De+E*F,t[i+12]=S*I+C*B+y*ge+A*Te,t[i+13]=S*R+C*Q+y*fe+A*ue,t[i+14]=S*N+C*ne+y*Ee+A*oe,t[i+15]=S*k+C*de+y*De+A*F,this}divide(e){return this.divideToRef(e,new this.constructor)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let n=0;n<16;n++)r[n]=i[n]/s[n];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]/=i[s];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);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 s=0;s<16;s++)t[s]=Math.min(t[s],i[s]);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 this.constructor)}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 s=0;s<16;s++)i[s]=-t[s];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,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let r=0;r<16;r++)if(!Or(i[r],s[r],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 this.constructor)}floorToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=Math.floor(t[s]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new this.constructor)}fractToRef(e){const t=this._m,i=e._m;for(let s=0;s<16;s++)i[s]=t[s]-Math.floor(t[s]);return e.markAsUpdated(),e}clone(){const e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Tn(this._m[0]);for(let t=1;t<16;t++)e=e*397^Tn(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new ae,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),e=e||qe.Vector3[0],e.x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const o=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,l=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,h=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=h}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,h=1/e._z;L.FromValuesToRef(n[0]*o,n[1]*o,n[2]*o,0,n[4]*l,n[5]*l,n[6]*l,0,n[8]*h,n[9]*h,n[10]*h,0,0,0,0,1,qe.Matrix[0]),ae.FromRotationMatrixToRef(qe.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=e*4;return new tt(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 this.constructor;return L.TransposeToRef(this,e),e}transposeToRef(e){return L.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=e*4;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new this.constructor;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=qe.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return L.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 this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=qe.Vector3[0];if(!this.decompose(t))return L.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return L.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,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 L;return L.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return L._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,l,h,c,u,d,f,m,_,x,E){const S=E._m;S[0]=e,S[1]=t,S[2]=i,S[3]=s,S[4]=r,S[5]=n,S[6]=o,S[7]=l,S[8]=h,S[9]=c,S[10]=u,S[11]=d,S[12]=f,S[13]=m,S[14]=_,S[15]=x,E.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,l,h,c,u,d,f,m,_,x){const E=new L,S=E._m;return S[0]=e,S[1]=t,S[2]=i,S[3]=s,S[4]=r,S[5]=n,S[6]=o,S[7]=l,S[8]=h,S[9]=c,S[10]=u,S[11]=d,S[12]=f,S[13]=m,S[14]=_,S[15]=x,E.markAsUpdated(),E}static Compose(e,t,i){const s=new L;return L.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,l=t._z,h=t._w,c=n+n,u=o+o,d=l+l,f=n*c,m=n*u,_=n*d,x=o*u,E=o*d,S=l*d,C=h*c,y=h*u,A=h*d,I=e._x,R=e._y,N=e._z;return r[0]=(1-(x+S))*I,r[1]=(m+A)*I,r[2]=(_-y)*I,r[3]=0,r[4]=(m-A)*R,r[5]=(1-(f+S))*R,r[6]=(E+C)*R,r[7]=0,r[8]=(_+y)*N,r[9]=(E-C)*N,r[10]=(1-(f+x))*N,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=L.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 L.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=L.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 L;return L.RotationXToRef(e,t),t}static Invert(e){const t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return L.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationY(e){const t=new L;return L.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return L.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationZ(e){const t=new L;return L.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return L.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(s===1&&i===0),t}static RotationAxis(e,t){const i=new L;return L.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=T.Dot(t,e),n=i._m;if(r<-1+At)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const o=T.Cross(t,e),l=1/(1+r);n[0]=o._x*o._x*l+r,n[1]=o._y*o._x*l-o._z,n[2]=o._z*o._x*l+o._y,n[3]=0,n[4]=o._x*o._y*l+o._z,n[5]=o._y*o._y*l+r,n[6]=o._z*o._y*l-o._x,n[7]=0,n[8]=o._x*o._z*l-o._y,n[9]=o._y*o._z*l+o._x,n[10]=o._z*o._z*l+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new L;return L.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return ae.RotationYawPitchRollToRef(e,t,i,qe.Quaternion[0]),qe.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new L;return L.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return L.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(e===1&&t===1&&i===1),s}static Translation(e,t,i){const s=new L;return L.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return L.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(e===0&&t===0&&i===0),s}static Lerp(e,t,i){const s=new e.constructor;return L.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let l=0;l<16;l++)r[l]=n[l]*(1-i)+o[l]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new e.constructor;return L.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=qe.Vector3[0],n=qe.Quaternion[0],o=qe.Vector3[1];e.decompose(r,n,o);const l=qe.Vector3[2],h=qe.Quaternion[1],c=qe.Vector3[3];t.decompose(l,h,c);const u=qe.Vector3[4];T.LerpToRef(r,l,i,u);const d=qe.Quaternion[2];ae.SlerpToRef(n,h,i,d);const f=qe.Vector3[5];return T.LerpToRef(o,c,i,f),L.ComposeToRef(u,d,f,s),s}static LookAtLH(e,t,i){const s=new L;return L.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=qe.Vector3[0],n=qe.Vector3[1],o=qe.Vector3[2];t.subtractToRef(e,o),o.normalize(),T.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(o,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(o,e);return L.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,h,c,u,1,s),s}static LookAtRH(e,t,i){const s=new L;return L.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=qe.Vector3[0],n=qe.Vector3[1],o=qe.Vector3[2];e.subtractToRef(t,o),o.normalize(),T.CrossToRef(i,o,r);const l=r.lengthSquared();l===0?r.x=1:r.normalizeFromLength(Math.sqrt(l)),T.CrossToRef(o,r,n),n.normalize();const h=-T.Dot(r,e),c=-T.Dot(n,e),u=-T.Dot(o,e);return L.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,h,c,u,1,s),s}static LookDirectionLH(e,t){const i=new L;return L.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=qe.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=qe.Vector3[1];return T.CrossToRef(t,s,r),L.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new L;return L.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=qe.Vector3[2];return T.CrossToRef(t,e,s),L.FromValuesToRef(s._x,s._y,s._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,s,r){const n=new L;return L.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=i,l=s,h=2/e,c=2/t,u=2/(l-o),d=-(l+o)/(l-o);return L.FromValuesToRef(h,0,0,0,0,c,0,0,0,0,u,0,0,0,d,1,r),n&&r.multiplyToRef(zh,r),r._updateIdentityStatus(h===1&&c===1&&u===1&&d===0),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const l=new L;return L.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l){const h=r,c=n,u=2/(t-e),d=2/(s-i),f=2/(c-h),m=-(c+h)/(c-h),_=(e+t)/(e-t),x=(s+i)/(i-s);return L.FromValuesToRef(u,0,0,0,0,d,0,0,0,0,f,0,_,x,m,1,o),l&&o.multiplyToRef(zh,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,l,h,c,u){const d=-o*Math.cos(l),f=-o*Math.sin(l);return L.TranslationToRef(0,0,-h,qe.Matrix[1]),L.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,qe.Matrix[0]),qe.Matrix[1].multiplyToRef(qe.Matrix[0],qe.Matrix[0]),L.TranslationToRef(0,0,h,qe.Matrix[1]),qe.Matrix[0].multiplyToRef(qe.Matrix[1],qe.Matrix[0]),L.OrthoOffCenterLHToRef(e,t,i,s,r,n,c,u),qe.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(e,t,i,s,r,n,o){const l=new L;return L.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,o),l}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,l){return L.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,l,h,c,u){const d=o*Math.cos(l),f=o*Math.sin(l);return L.TranslationToRef(0,0,h,qe.Matrix[1]),L.FromValuesToRef(1,0,0,0,0,1,0,0,d,f,1,0,0,0,0,1,qe.Matrix[0]),qe.Matrix[1].multiplyToRef(qe.Matrix[0],qe.Matrix[0]),L.TranslationToRef(0,0,-h,qe.Matrix[1]),qe.Matrix[0].multiplyToRef(qe.Matrix[1],qe.Matrix[0]),L.OrthoOffCenterRHToRef(e,t,i,s,r,n,c,u),qe.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(e,t,i,s,r,n=0){const o=new L,l=i,h=s,c=2*l/e,u=2*l/t,d=(h+l)/(h-l),f=-2*h*l/(h-l),m=Math.tan(n);return L.FromValuesToRef(c,0,0,0,0,u,0,m,0,0,d,1,0,0,f,0,o),r&&o.multiplyToRef(zh,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const l=new L;return L.PerspectiveFovLHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,m=n?d:d*t,_=h&&c===0?-1:u!==0?(u+c)/(u-c):1,x=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,E=Math.tan(l);return L.FromValuesToRef(f,0,0,0,0,m,0,E,0,0,_,1,0,0,x,0,r),o&&r.multiplyToRef(zh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return L.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(zh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const l=new L;return L.PerspectiveFovRHToRef(e,t,i,s,l,!0,r,n,o),l}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,l=0,h=!1){const c=i,u=s,d=1/Math.tan(e*.5),f=n?d/t:d,m=n?d:d*t,_=h&&c===0?1:u!==0?-(u+c)/(u-c):-1,x=h&&c===0?2*u:u!==0?-2*u*c/(u-c):-2*c,E=Math.tan(l);return L.FromValuesToRef(f,0,0,0,0,m,0,E,0,0,_,-1,0,0,x,0,r),o&&r.multiplyToRef(zh,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,l=0){const h=1/Math.tan(e*.5),c=n?h/t:h,u=n?h:h*t,d=Math.tan(l);return L.FromValuesToRef(c,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(zh,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,l=e.height,h=e.x,c=e.y,u=L.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,n-r,0,h+o/2,l/2+c,r,1),d=new t.constructor;return t.multiplyToRef(i,d),d.multiplyToRef(s,d),d.multiplyToRef(u,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return ur.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 ur.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new e.constructor;return L.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],l=i[1],h=i[5],c=i[9],u=i[13],d=i[2],f=i[6],m=i[10],_=i[14],x=i[3],E=i[7],S=i[11],C=i[15],y=t._m;return y[0]=s,y[1]=r,y[2]=n,y[3]=o,y[4]=l,y[5]=h,y[6]=c,y[7]=u,y[8]=d,y[9]=f,y[10]=m,y[11]=_,y[12]=x,y[13]=E,y[14]=S,y[15]=C,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new L;return L.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,l=-2*r;return L.FromValuesToRef(n*i+1,o*i,l*i,0,n*s,o*s+1,l*s,0,n*r,o*r,l*r+1,0,n*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return L.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,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,l=e._z*e._x,h=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(l-h),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(l+h),t._m[9]=2*(c-u),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}L._UpdateFlagSeed=0;L._IdentityReadOnly=L.Identity();Object.defineProperties(L.prototype,{dimension:{value:[4,4]},rank:{value:2}});class qe{}qe.Vector3=Os.BuildTuple(11,T.Zero);qe.Matrix=Os.BuildTuple(2,L.Identity);qe.Quaternion=Os.BuildTuple(3,ae.Zero);class W{}W.Vector2=Os.BuildTuple(3,ce.Zero);W.Vector3=Os.BuildTuple(13,T.Zero);W.Vector4=Os.BuildTuple(3,tt.Zero);W.Quaternion=Os.BuildTuple(2,ae.Zero);W.Matrix=Os.BuildTuple(8,L.Identity);H("BABYLON.Vector2",ce);H("BABYLON.Vector3",T);H("BABYLON.Vector4",tt);H("BABYLON.Matrix",L);const zh=L.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class Ne{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=Ne.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=Ne.Repeat(e,t*2);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=Ne.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return Math.abs(t-e)<=i?s=t:s=e+Ne.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=Ne.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*ts(i)}static InverseLerp(e,t,i){let s=0;return e!=t?s=ts((i-e)/(t-e)):s=0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n;return e*l+i*h+t*c+s*u}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return(n-r)*6*e+(3*n-4*r+1)*t+(-n+r)*6*i+(3*n-2*r)*s}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:Ne.HCF(t,i)}}Ne.TwoPi=Math.PI*2;Ne.WithinEpsilon=Or;Ne.ToHex=Qa;Ne.Clamp=ts;Ne.Lerp=wn;Ne.RandomRange=ni;Ne.NormalizeRadians=hI;function au(a){return Math.pow(a,Ym)}function ou(a){return a<=.04045?.0773993808*a:Math.pow(.947867299*(a+.055),2.4)}function lu(a){return Math.pow(a,ip)}function hu(a){return a<=.0031308?12.92*a:1.055*Math.pow(a,.41666)-.055}class re{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return re.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Oe(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 this.constructor(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 this.constructor(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=At){return Ne.WithinEpsilon(this.r,e.r,t)&&Ne.WithinEpsilon(this.g,e.g,t)&&Ne.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 this.constructor(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=ts(this.r,e,t),i.g=ts(this.g,e,t),i.b=ts(this.b,e,t),i}add(e){return new this.constructor(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 this.constructor(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 this.constructor(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this.r-e,this.g-t,this.b-i)}clone(){return new this.constructor(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"#"+Qa(e)+Qa(t)+Qa(i)}toHSV(){const e=new this.constructor;return this.toHSVToRef(e),e}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,l=0;const h=r,c=r-n;r!==0&&(l=c/r),r!=n&&(r==t?(o=(i-s)/c,i=0&&n<=1?(l=r,h=o):n>=1&&n<=2?(l=o,h=r):n>=2&&n<=3?(h=r,c=o):n>=3&&n<=4?(h=o,c=r):n>=4&&n<=5?(l=o,c=r):n>=5&&n<=6&&(l=r,c=o);const u=i-r;s.set(l+u,h+u,c+u)}static FromHSV(e,t,i){const s=new re(0,0,0);return re.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==7)return new re(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return re.FromInts(t,i,s)}static FromArray(e,t=0){return new re(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new re(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new re(0,0,0);return re.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.r*l+i.r*h+t.r*c+s.r*u,f=e.g*l+i.g*h+t.g*c+s.g*u,m=e.b*l+i.b*h+t.b*c+s.b*u;return new re(d,f,m)}static Hermite1stDerivative(e,t,i,s,r){const n=re.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b}static Red(){return new re(1,0,0)}static Green(){return new re(0,1,0)}static Blue(){return new re(0,0,1)}static Black(){return new re(0,0,0)}static get BlackReadOnly(){return re._BlackReadOnly}static White(){return new re(1,1,1)}static Purple(){return new re(.5,0,.5)}static Magenta(){return new re(1,0,1)}static Yellow(){return new re(1,1,0)}static Gray(){return new re(.5,.5,.5)}static Teal(){return new re(0,1,1)}static Random(){return new re(Math.random(),Math.random(),Math.random())}}re._BlackReadOnly=re.Black();Object.defineProperties(re.prototype,{dimension:{value:[3]},rank:{value:1}});class Oe{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}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 this.constructor(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,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new this.constructor(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,s){return new this.constructor(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new this.constructor(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=ts(this.r,e,t),i.g=ts(this.g,e,t),i.b=ts(this.b,e,t),i.a=ts(this.a,e,t),i}multiply(e){return new this.constructor(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,s){return new this.constructor(this.r*e,this.g*t,this.b*i,this.a*s)}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,s){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(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){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(s,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=At){return Ne.WithinEpsilon(this.r,e.r,t)&&Ne.WithinEpsilon(this.g,e.g,t)&&Ne.WithinEpsilon(this.b,e.b,t)&&Ne.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}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 this.constructor().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,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}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),s=Math.round(this.b*255);if(e)return"#"+Qa(t)+Qa(i)+Qa(s);const r=Math.round(this.a*255);return"#"+Qa(t)+Qa(i)+Qa(s)+Qa(r)}toLinearSpace(e=!1){const t=new Oe;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=ou(this.r),e.g=ou(this.g),e.b=ou(this.b)):(e.r=au(this.r),e.g=au(this.g),e.b=au(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Oe;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=hu(this.r),e.g=hu(this.g),e.b=hu(this.b)):(e.r=lu(this.r),e.g=lu(this.g),e.b=lu(this.b)),e.a=this.a,this}static FromHexString(e){if(e.substring(0,1)!=="#"||e.length!==9&&e.length!==7)return new Oe(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=e.length===9?parseInt(e.substring(7,9),16):255;return Oe.FromInts(t,i,s,r)}static Lerp(e,t,i){const s=new Oe(0,0,0,0);return Oe.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,l=2*o-3*n+1,h=-2*o+3*n,c=o-2*n+r,u=o-n,d=e.r*l+i.r*h+t.r*c+s.r*u,f=e.g*l+i.g*h+t.g*c+s.g*u,m=e.b*l+i.b*h+t.b*c+s.b*u,_=e.a*l+i.a*h+t.a*c+s.a*u;return new Oe(d,f,m,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new Oe;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=(o-r)*6*e.r+(3*o-4*r+1)*t.r+(-o+r)*6*i.r+(3*o-2*r)*s.r,n.g=(o-r)*6*e.g+(3*o-4*r+1)*t.g+(-o+r)*6*i.g+(3*o-2*r)*s.g,n.b=(o-r)*6*e.b+(3*o-4*r+1)*t.b+(-o+r)*6*i.b+(3*o-2*r)*s.b,n.a=(o-r)*6*e.a+(3*o-4*r+1)*t.a+(-o+r)*6*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Oe(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Oe(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,s){return new Oe(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===t*3){const i=[];for(let s=0;snew Oe(0,0,0,0));H("BABYLON.Color3",re);H("BABYLON.Color4",Oe);class Ri{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new K,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 s=this._condition.serialize();return s.children.push(i),t&&t.children.push(s),s}return t&&t.children.push(i),i}}Ri._SerializeValueAsString=a=>typeof a=="number"?a.toString():typeof a=="boolean"?a?"true":"false":a instanceof ce?a.x+", "+a.y:a instanceof T?a.x+", "+a.y+", "+a.z:a instanceof re?a.r+", "+a.g+", "+a.b:a instanceof Oe?a.r+", "+a.g+", "+a.b+", "+a.a:a;Ri._GetTargetProperty=a=>({name:"target",targetType:a._isMesh?"MeshProperties":a._isLight?"LightProperties":a._isCamera?"CameraProperties":a._isMaterial?"MaterialProperties":"SceneProperties",value:a._isScene?"Scene":a.name});H("BABYLON.Action",Ri);class ji{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new ji(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new ji(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new ji(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new ji(e,t.x,t.y,null,i,s)}}class Pp{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 qs extends Pp{static get IsEqual(){return qs._IsEqual}static get IsDifferent(){return qs._IsDifferent}static get IsGreater(){return qs._IsGreater}static get IsLesser(){return qs._IsLesser}constructor(e,t,i,s,r=qs.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case qs.IsGreater:return this._effectiveTarget[this._property]>this.value;case qs.IsLesser:return this._effectiveTarget[this._property]s<10?"0"+s:""+s,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 s=Array.isArray(t)?t[0]:t;if(i!==void 0&&!U._CheckLimit(s,i))return;const r=U._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const l=`
${r}

`;U._AddLogEntry(l),U._GenerateLimitMessage(s,e)}static get LogCache(){return U._LogCache}static ClearLogCache(){U._LogCache="",U._LogLimitOutputs={},U.errorsCount=0}static set LogLevels(e){U.Log=U._LogDisabled,U.Warn=U._LogDisabled,U.Error=U._LogDisabled,[U.MessageLogLevel,U.WarningLogLevel,U.ErrorLogLevel].forEach(t=>{if((e&t)===t){const i=this._Levels[t];U[i.name]=U._LogEnabled.bind(U,t)}})}}U.NoneLogLevel=0;U.MessageLogLevel=1;U.WarningLogLevel=2;U.ErrorLogLevel=4;U.AllLogLevel=7;U.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";U._LogCache="";U._LogLimitOutputs={};U._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];U.errorsCount=0;U.Log=U._LogEnabled.bind(U,U.MessageLogLevel);U.Warn=U._LogEnabled.bind(U,U.WarningLogLevel);U.Error=U._LogEnabled.bind(U,U.ErrorLogLevel);class aU extends Ri{constructor(e,t,i,s){super(e,s),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:[Ri._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class oU extends Ri{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Ri._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class lU extends Ri{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,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:[Ri._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ri._SerializeValueAsString(this.value)}]},e)}}class hU extends Ri{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,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"&&U.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:[Ri._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ri._SerializeValueAsString(this.value)}]},e)}}class cU extends Ri{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,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:[Ri._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Ri._SerializeValueAsString(this.loop)||!1}]},e)}}class uU extends Ri{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:[Ri._GetTargetProperty(this._target)]},e)}}class cI extends Ri{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class dU extends Ri{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;e!a||a.getClassName&&a.getClassName()==="Mesh"?null:a.getClassName&&(a.getClassName()==="SubMesh"||a.getClassName()==="PhysicsBody")?a.clone(e):a.clone?a.clone():Array.isArray(a)?a.slice():t&&typeof a=="object"?{...a}:null;function pU(a){const e=[];do Object.getOwnPropertyNames(a).forEach(function(t){e.indexOf(t)===-1&&e.push(t)});while(a=Object.getPrototypeOf(a));return e}class Tr{static DeepCopy(e,t,i,s,r=!1){const n=pU(e);for(const o of n){if(o[0]==="_"&&(!s||s.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;const l=e[o],h=typeof l;if(h!=="function")try{if(h==="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 c=0;c-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=si.OnPickTrigger&&t.trigger<=si.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=si.OnPickTrigger&&t.trigger<=si.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===si.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(U.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,si.Triggers[e.trigger]?si.Triggers[e.trigger]++:si.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),si.Triggers[e.trigger]-=1,si.Triggers[e.trigger]===0&&delete si.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0):!1}processTrigger(e,t){for(let i=0;i{const c=rs("BABYLON."+l);return c&&new c(...h)},n=(l,h,c,u)=>{if(u===null){const _=parseFloat(h);return h==="true"||h==="false"?h==="true":isNaN(_)?h:_}const d=u.split("."),f=h.split(",");for(let _=0;_{if(l.detached)return;const f=[];let m=null,_=null;const x=l.combine&&l.combine.length>0;if(l.type===2?f.push(s):f.push(h),x){const S=[];for(let C=0;C0){const u=c.properties[0].value,d=c.properties[0].targetType===null?u:i.getMeshByName(u);d._meshId&&(d.mesh=i.getMeshById(d._meshId)),h={trigger:si[c.name],parameter:d}}else h=si[c.name];for(let u=0;u=0;o--)(n=a[o])&&(r=(s<3?n(r):s>3?n(e,t,r):n(e,t))||r);return s>3&&r&&Object.defineProperty(e,t,r),r}const Pm={},$m={};function gU(a){const e=a.getClassName();return $m[e]||($m[e]={}),$m[e]}function FE(a){const e=a.getClassName();if(Pm[e])return Pm[e];Pm[e]={};const t=Pm[e];let i=a,s=e;for(;s;){const r=$m[s];for(const l in r)t[l]=r[l];let n,o=!1;do{if(n=Object.getPrototypeOf(i),!n.getClassName){o=!0;break}if(n.getClassName()!==s)break;i=n}while(n);if(o)break;s=n.getClassName(),i=n}return t}function fa(a,e){return(t,i)=>{const s=gU(t);s[i]||(s[i]={type:a,sourceName:e})}}function xU(a,e=null){return(t,i)=>{const s=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[s]},set:function(r){typeof this.equals=="function"&&this.equals(r)||this[s]!==r&&(this[s]=r,t[a].apply(this))},enumerable:!0,configurable:!0})}}function _e(a,e=null){return xU(a,e)}function O(a){return fa(0,a)}function Dt(a){return fa(1,a)}function Vi(a){return fa(2,a)}function t_(a){return fa(3,a)}function ev(a){return fa(4,a)}function Sr(a){return fa(5,a)}function i_(a){return fa(6,a)}function TU(a){return fa(7,a)}function tv(a){return fa(8,a)}function dI(a){return fa(9,a)}function EU(a){return fa(10,a)}function iv(a){return fa(12,a)}function SU(a){return fa(11,a)}function ph(a,e,t,i){const s=t.value;t.value=(...r)=>{let n=s;if(typeof _native<"u"&&_native[e]){const o=_native[e];i?n=(...l)=>i(...l)?o(...l):s(...l):n=o}return a[e]=n,n(...r)}}ph.filter=function(a){return(e,t,i)=>ph(e,t,i,a)};const yA={};function ot(a,e=!1){if(!(e&&yA[a]))return yA[a]=!0,`${a} needs to be imported before as it contains a side-effect required by your code.`}class Xh{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),Xh._HandleParenthesisContent(i,t))):e=Xh._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:Xh.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(r=>r==="true");let i;const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let n=Xh._SimplifyNegation(s[r].trim());const o=n.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 Gt{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Gt.HasTags(e),e.addTags=t=>Gt.AddTagsTo(e,t),e.removeTags=t=>Gt.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Gt.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 s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&e._tags[s]===!0&&i.push(s);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;t.split(" ").forEach(function(s){Gt._AddTagTo(e,s)})}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Gt.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Gt.HasTags(e))return;const i=t.split(" ");for(const s in i)Gt._RemoveTagFrom(e,i[s])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?Gt.HasTags(e):Xh.Eval(t,i=>Gt.HasTags(e)&&e._tags[i])}}const AA=function(a,e,t,i={}){const s=a();Gt&&Gt.HasTags(e)&&Gt.AddTagsTo(s,Gt.GetTags(e,!0));const r=FE(s),n={};for(const o in r){const l=r[o],h=e[o],c=l.type;if(h!=null&&(o!=="uniqueId"||Pe.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:s[o]=h;break;case 1:i.cloneTexturesOnlyOnce&&n[h.uniqueId]?s[o]=n[h.uniqueId]:(s[o]=t||h.isRenderTarget?h:h.clone(),n[h.uniqueId]=s[o]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[o]=t?h:h.clone();break}}return s};class Pe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw ot("ImageProcessingConfiguration")};Pe._FresnelParametersParser=a=>{throw ot("FresnelParameters")};Pe._ColorCurvesParser=a=>{throw ot("ColorCurves")};Pe._TextureParser=(a,e,t)=>{throw ot("Texture")};class vU{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new K,this._onClonedObservable=new K}}let Qt=class LE{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):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){this._isDirty=!1,this._nodeDataStorage=new vU,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new K,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=L.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new K,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||We.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}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 s=0;s(!t||t(s))&&s.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 LE(e,this.getScene()),this);if(t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;n{throw ot("AnimationRange")};Qt._NodeConstructors={};v([O()],Qt.prototype,"name",void 0);v([O()],Qt.prototype,"id",void 0);v([O()],Qt.prototype,"uniqueId",void 0);v([O()],Qt.prototype,"state",void 0);v([O()],Qt.prototype,"metadata",void 0);class aa{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 aa(this.width*e,this.height*t)}clone(){return new aa(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 aa(0,0)}add(e){return new aa(this.width+e.width,this.height+e.height)}subtract(e){return new aa(this.width-e.width,this.height-e.height)}scale(e){return new aa(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new aa(s,r)}}function CU(){return typeof _native<"u"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}class hs{constructor(){this._xhr=CU(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(hs.CustomRequestHeaders).length>0||hs.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in hs.CustomRequestHeaders){const t=hs.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return hs.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){hs.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of hs.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)}}hs.CustomRequestHeaders={};hs.CustomRequestModifiers=new Array;hs.SkipRequestModificationForBabylonCDN=!0;const fI=Object.freeze(new ae(0,0,0,0)),pI=Object.freeze(T.Zero()),_I=Object.freeze(ce.Zero()),mI=Object.freeze(aa.Zero()),gI=Object.freeze(re.Black()),xI=Object.freeze(new Oe(0,0,0,0)),Ya={key:0,repeatCount:0,loopMode:2};class te{static _PrepareAnimation(e,t,i,s,r,n,o,l){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=te.ANIMATIONTYPE_FLOAT:r instanceof ae?h=te.ANIMATIONTYPE_QUATERNION:r instanceof T?h=te.ANIMATIONTYPE_VECTOR3:r instanceof ce?h=te.ANIMATIONTYPE_VECTOR2:r instanceof re?h=te.ANIMATIONTYPE_COLOR3:r instanceof Oe?h=te.ANIMATIONTYPE_COLOR4:r instanceof aa&&(h=te.ANIMATIONTYPE_SIZE),h==null)return null;const c=new te(e,t,i,h,o),u=[{frame:0,value:r},{frame:s,value:n}];return c.setKeys(u),l!==void 0&&c.setEasingFunction(l),c}static CreateAnimation(e,t,i,s){const r=new te(e+"Animation",e,i,t,te.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,l,h,c,u){const d=te._PrepareAnimation(e,i,s,r,n,o,l,h);return!d||(t.getScene&&(u=t.getScene()),!u)?null:u.beginDirectAnimation(t,[d],0,r,d.loopMode===1,1,c)}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,l,h,c,u){const d=te._PrepareAnimation(e,s,r,n,o,l,h,c);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,n,d.loopMode===1,1,u):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,l,h,c){const u=te._PrepareAnimation(e,i,s,r,n,o,l,h);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,r,u.loopMode===1,1,c)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;typeof t=="object"?n=t:n={referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const l=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let h=0;const c=o._keys[0];let u=o._keys.length-1;const d=o._keys[u],f={referenceValue:c.value,referencePosition:W.Vector3[0],referenceQuaternion:W.Quaternion[0],referenceScaling:W.Vector3[1],keyPosition:W.Vector3[2],keyQuaternion:W.Quaternion[1],keyScaling:W.Vector3[3]};let m=c.frame,_=d.frame;if(n.range){const S=o.getRange(n.range);S&&(m=S.from,_=S.to)}else m=n.fromFrame??m,_=n.toFrame??_;if(m!==c.frame&&(h=o.createKeyForFrame(m)),_!==d.frame&&(u=o.createKeyForFrame(_)),o._keys.length===1){const S=o._getKeyValue(o._keys[0]);f.referenceValue=S.clone?S.clone():S}else if(l<=c.frame){const S=o._getKeyValue(c.value);f.referenceValue=S.clone?S.clone():S}else if(l>=d.frame){const S=o._getKeyValue(d.value);f.referenceValue=S.clone?S.clone():S}else{Ya.key=0;const S=o._interpolate(l,Ya);f.referenceValue=S.clone?S.clone():S}o.dataType===te.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():o.dataType===te.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let x=Number.MAX_VALUE;const E=n.clipKeys?[]:null;for(let S=h;S<=u;S++){let C=o._keys[S];if(E&&(C={frame:C.frame,value:C.value.clone?C.value.clone():C.value,inTangent:C.inTangent,outTangent:C.outTangent,interpolation:C.interpolation,lockedTangent:C.lockedTangent},x===Number.MAX_VALUE&&(x=C.frame),C.frame-=x,E.push(C)),!(S&&o.dataType!==te.ANIMATIONTYPE_FLOAT&&C.value===c.value))switch(o.dataType){case te.ANIMATIONTYPE_MATRIX:C.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),L.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,C.value);break;case te.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(C.value,C.value);break;case te.ANIMATIONTYPE_VECTOR2:case te.ANIMATIONTYPE_VECTOR3:case te.ANIMATIONTYPE_COLOR3:case te.ANIMATIONTYPE_COLOR4:C.value.subtractToRef(f.referenceValue,C.value);break;case te.ANIMATIONTYPE_SIZE:C.value.width-=f.referenceValue.width,C.value.height-=f.referenceValue.height;break;default:C.value-=f.referenceValue}}return E&&o.setKeys(E,!0),o}static TransitionTo(e,t,i,s,r,n,o,l=null){if(o<=0)return i[e]=t,l&&l(),null;const h=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const c=s.beginAnimation(i,0,h,!1);return c.onAnimationEnd=l,c}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=r===void 0?te.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=te._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 s in this._ranges)i&&(t+=", ",i=!1),t+=s;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;n--)this._keys[n].frame>=s&&this._keys[n].frame<=r&&this._keys.splice(n,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 s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],l=s[n+1];if(i&&(e===o.frame||e===l.frame))return;const h=this._getKeyValue(o.value),c=this._getKeyValue(l.value);if(o.interpolation===og.STEP)return l.frame>e?h:c;const u=o.outTangent!==void 0&&l.inTangent!==void 0,d=l.frame-o.frame;let f=(e-o.frame)/d;const m=o.easingFunction||this.getEasingFunction();switch(m!==null&&(f=m.ease(f)),this.dataType){case te.ANIMATIONTYPE_FLOAT:{const _=u?this.floatInterpolateFunctionWithTangents(h,o.outTangent*d,c,l.inTangent*d,f):this.floatInterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+_}break}case te.ANIMATIONTYPE_QUATERNION:{const _=u?this.quaternionInterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.quaternionInterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.addInPlace((t.offsetValue||fI).scale(t.repeatCount))}return _}case te.ANIMATIONTYPE_VECTOR3:{const _=u?this.vector3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.vector3InterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||pI).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_VECTOR2:{const _=u?this.vector2InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.vector2InterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||_I).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,c,f);case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,c,f).add((t.offsetValue||mI).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_COLOR3:{const _=u?this.color3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.color3InterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||gI).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_COLOR4:{const _=u?this.color4InterpolateFunctionWithTangents(h,o.outTangent.scale(d),c,l.inTangent.scale(d),f):this.color4InterpolateFunction(h,c,f);switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return _;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return _.add((t.offsetValue||xI).scale(t.repeatCount))}break}case te.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case te.ANIMATIONLOOPMODE_CYCLE:case te.ANIMATIONLOOPMODE_CONSTANT:case te.ANIMATIONLOOPMODE_YOYO:return te.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,c,f,t.workValue):h;case te.ANIMATIONLOOPMODE_RELATIVE:case te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}break}}return 0}matrixInterpolateFunction(e,t,i,s){return te.AllowMatrixDecomposeForInterpolation?s?(L.DecomposeLerpToRef(e,t,i,s),s):L.DecomposeLerp(e,t,i):s?(L.LerpToRef(e,t,i,s),s):L.Lerp(e,t,i)}clone(){const e=new te(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){Ya.key=0;const t=this._interpolate(e,Ya,!0);if(!t)return this._keys[Ya.key].frame===e?Ya.key:Ya.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Ya.key+1,0,i),Ya.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 s=0;s=2&&(l=o.values[1]),o.values.length>=3&&(h=o.values[2]),o.values.length>=4&&(c=o.values[3]);break;case te.ANIMATIONTYPE_QUATERNION:if(r=ae.FromArray(o.values),o.values.length>=8){const d=ae.FromArray(o.values.slice(4,8));d.equals(ae.Zero())||(l=d)}if(o.values.length>=12){const d=ae.FromArray(o.values.slice(8,12));d.equals(ae.Zero())||(h=d)}o.values.length>=13&&(c=o.values[12]);break;case te.ANIMATIONTYPE_MATRIX:r=L.FromArray(o.values),o.values.length>=17&&(c=o.values[16]);break;case te.ANIMATIONTYPE_COLOR3:r=re.FromArray(o.values),o.values[3]&&(l=re.FromArray(o.values[3])),o.values[4]&&(h=re.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break;case te.ANIMATIONTYPE_COLOR4:r=Oe.FromArray(o.values),o.values[4]&&(l=Oe.FromArray(o.values[4])),o.values[5]&&(h=Oe.FromArray(o.values[5])),o.values[6]&&(c=Oe.FromArray(o.values[6]));break;case te.ANIMATIONTYPE_VECTOR3:default:r=T.FromArray(o.values),o.values[3]&&(l=T.FromArray(o.values[3])),o.values[4]&&(h=T.FromArray(o.values[4])),o.values[5]&&(c=o.values[5]);break}const u={};u.frame=o.frame,u.value=r,l!=null&&(u.inTangent=l),h!=null&&(u.outTangent=h),c!=null&&(u.interpolation=c),s.push(u)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new hs;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let n=JSON.parse(r.responseText);if(n.animations&&(n=n.animations),n.length){const o=[];for(const l of n)o.push(this.Parse(l));i(o)}else{const o=this.Parse(n);e&&(o.name=e),i(o)}}else s("Unable to load the animation")}),r.open("GET",t),r.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{const s=new hs;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){const r=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(r.animations){const n=JSON.parse(r.animations),o=[];for(const l of n.animations){const h=this.Parse(l);h.snippetId=e,o.push(h)}t(o)}else{const n=JSON.parse(r.animation),o=this.Parse(n);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()})}}te._UniqueIdGenerator=0;te.AllowMatricesInterpolation=!1;te.AllowMatrixDecomposeForInterpolation=!0;te.SnippetUrl="https://snippet.babylonjs.com";te.ANIMATIONTYPE_FLOAT=0;te.ANIMATIONTYPE_VECTOR3=1;te.ANIMATIONTYPE_QUATERNION=2;te.ANIMATIONTYPE_MATRIX=3;te.ANIMATIONTYPE_COLOR3=4;te.ANIMATIONTYPE_COLOR4=7;te.ANIMATIONTYPE_VECTOR2=5;te.ANIMATIONTYPE_SIZE=6;te.ANIMATIONLOOPMODE_RELATIVE=0;te.ANIMATIONLOOPMODE_CYCLE=1;te.ANIMATIONLOOPMODE_CONSTANT=2;te.ANIMATIONLOOPMODE_YOYO=4;te.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;te.CreateFromSnippetAsync=te.ParseFromSnippetAsync;H("BABYLON.Animation",te);Qt._AnimationRangeFactory=(a,e,t)=>new xu(a,e,t);class bU extends Ri{constructor(e,t,i,s,r=1e3,n,o,l){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new K,this.propertyPath=i,this.value=s,this.duration=r,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=te.ANIMATIONTYPE_FLOAT;else if(this.value instanceof re)i=te.ANIMATIONTYPE_COLOR3;else if(this.value instanceof T)i=te.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof L)i=te.ANIMATIONTYPE_MATRIX;else if(this.value instanceof ae)i=te.ANIMATIONTYPE_QUATERNION;else{U.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}const s=new te("InterpolateValueAction",this._property,100*(1e3/this.duration),i,te.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);const r=()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()};e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,r)}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Ri._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ri._SerializeValueAsString(this.value)},{name:"duration",value:Ri._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Ri._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}H("BABYLON.InterpolateValueAction",bU);class yU{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,s){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=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===te.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=L.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 n={frame:0,value:this._minValue};this._keys.splice(0,0,n)}if(this._target instanceof Array){let n=0;for(const o of this._target)this._preparePath(o,n),this._getOriginalValues(n),n++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach(n=>{this._events.push(n._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 s=e;for(let r=0;r-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let r=0;rthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,f=0,m=!1;const _=s&&this._animationState.loopMode===te.ANIMATIONLOOPMODE_YOYO;if(_){const C=(d-t)/c,y=Math.sin(C*Math.PI);d=Math.abs(y)*c+t;const I=y>=0?1:-1;this._yoyoDirection!==I&&(m=!0),this._yoyoDirection=I}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!s&&i>=t&&(d>=c&&r>0||d<=0&&r<0))h=!1,f=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(d<=c&&r<0||d>=0&&r>0))h=!1,f=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==te.ANIMATIONLOOPMODE_CYCLE){const C=i.toString()+t.toString();if(!this._offsetsCache[C]){this._animationState.repeatCount=0,this._animationState.loopMode=te.ANIMATIONLOOPMODE_CYCLE;const y=o._interpolate(t,this._animationState),A=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case te.ANIMATIONTYPE_FLOAT:this._offsetsCache[C]=A-y;break;case te.ANIMATIONTYPE_QUATERNION:this._offsetsCache[C]=A.subtract(y);break;case te.ANIMATIONTYPE_VECTOR3:this._offsetsCache[C]=A.subtract(y);break;case te.ANIMATIONTYPE_VECTOR2:this._offsetsCache[C]=A.subtract(y);break;case te.ANIMATIONTYPE_SIZE:this._offsetsCache[C]=A.subtract(y);break;case te.ANIMATIONTYPE_COLOR3:this._offsetsCache[C]=A.subtract(y);break}this._highLimitsCache[C]=A}f=this._highLimitsCache[C],u=this._offsetsCache[C]}if(u===void 0)switch(o.dataType){case te.ANIMATIONTYPE_FLOAT:u=0;break;case te.ANIMATIONTYPE_QUATERNION:u=fI;break;case te.ANIMATIONTYPE_VECTOR3:u=pI;break;case te.ANIMATIONTYPE_VECTOR2:u=_I;break;case te.ANIMATIONTYPE_SIZE:u=mI;break;case te.ANIMATIONTYPE_COLOR3:u=gI;break;case te.ANIMATIONTYPE_COLOR4:u=xI;break}let x;if(this._host&&this._host.syncRoot){const C=this._host.syncRoot,y=(C.masterFrame-C.fromFrame)/(C.toFrame-C.fromFrame);x=t+c*y}else d>0&&t>i||d<0&&t0&&this.currentFrame>x||r<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=x,this._animationState.repeatCount=c===0?0:d/c>>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const S=o._interpolate(x,this._animationState);if(this.setValue(S,n),E.length){for(let C=0;C=0&&x>=E[C].frame&&E[C].frame>=t||c<0&&x<=E[C].frame&&E[C].frame<=t){const y=E[C];y.isDone||(y.onlyOnce&&(E.splice(C,1),C--),y.isDone=!0,y.action(x))}}return h||(this._stopped=!0),h}}function Vs(){return typeof window<"u"}function Qc(){return typeof navigator<"u"}function sp(){return typeof document<"u"}function sv(a){let e="",t=a.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}class ks{static get Now(){return Vs()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class rp{}rp.FilesToLoad={};class AU{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>s.status!==0||r>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,r)*t}}class Tu extends Error{}Tu._setPrototypeOf=Object.setPrototypeOf||((a,e)=>(a.__proto__=e,a));const ml={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class oo extends Tu{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Tu._setPrototypeOf(this,oo.prototype)}}const RU=a=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(a);let e="";for(let t=0;t{const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i,s,r,n,o,l,h,c=0;const u=ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);for(;c>2,o=(i&3)<<4|s>>4,l=(s&15)<<2|r>>6,h=r&63,isNaN(s)?l=h=64:isNaN(r)&&(h=64),t+=e.charAt(n)+e.charAt(o)+e.charAt(l)+e.charAt(h);return t},EI=a=>atob(a),IU=a=>{const e=EI(a),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let s=0;s{i+=c.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class OU{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{const r=t.split(";");for(let n=0;n{c=c.trim(),c!==""&&(i.push(c),c="")},n=u=>{sos._Stack[s],l=()=>s===-1?"!!INVALID EXPRESSION!!":os._Stack[s--];let h=0,c="";for(;h1){for(r();s!==-1&&os._OperatorPriority[o()]>=os._OperatorPriority[d];)i.push(l());n(d),h++}else c+=u;h++}for(r();s!==-1;)o()==="("?l():i.push(l());return os._InfixToPostfixCache.size>=os.InfixToPostfixCacheLimitSize&&os.ClearCache(),os._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(os._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r;break}return i}}var vt;(function(a){a[a.GLSL=0]="GLSL",a[a.WGSL=1]="WGSL"})(vt||(vt={}));const hg={};function SI(a,e,t=""){return t+(e?e+` +`:"")+a}function vI(a,e,t,i,s,r,n){const o=n||hg.loadFile;if(o)return o(a,e,t,i,s,r);throw ot("FileTools")}function CI(a,e,t,i){if(a){e?a.IS_NDC_HALF_ZRANGE="":delete a.IS_NDC_HALF_ZRANGE,t?a.USE_REVERSE_DEPTHBUFFER="":delete a.USE_REVERSE_DEPTHBUFFER,i?a.USE_EXACT_SRGB_CONVERSIONS="":delete a.USE_EXACT_SRGB_CONVERSIONS;return}else{let s="";return e&&(s+="#define IS_NDC_HALF_ZRANGE"),t&&(s&&(s+=` +`),s+="#define USE_REVERSE_DEPTHBUFFER"),i&&(s&&(s+=` +`),s+="#define USE_EXACT_SRGB_CONVERSIONS"),s}}const LU=/defined\s*?\((.+?)\)/g,rE=/defined\s*?\[(.+?)\]/g,BU=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,UU=/__decl__/,RA=/light\{X\}.(\w*)/g,IA=/\{X\}/g,Mm=[],VU=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function bI(a){a.processor&&a.processor.initializeShaders&&a.processor.initializeShaders(a.processingContext)}function PA(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),Mp(a,e,r=>{e.processCodeAfterIncludes&&(r=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",r));const n=WU(r,e,i);t(n,r)})}function kU(a,e,t,i){var s;(s=e.processor)!=null&&s.preProcessShaderCode&&(a=e.processor.preProcessShaderCode(a,e.isFragment)),Mp(a,e,r=>{e.processCodeAfterIncludes&&(r=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",r));const n=HU(r,e,i);t(n,r)})}function yI(a,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:a,fragmentCode:e}:t.processor.finalizeShaders(a,e,t.processingContext)}function GU(a,e){var i;if((i=e.processor)!=null&&i.noPrecision)return a;const t=e.shouldUseHighPrecisionShader;return a.indexOf("precision highp float")===-1?t?a=`precision highp float; +`+a:a=`precision mediump float; +`+a:t||(a=a.replace("precision highp float","precision mediump float")),a}function nE(a){const t=/defined\((.+)\)/.exec(a);if(t&&t.length)return new lg(t[1].trim(),a[0]==="!");const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=a.indexOf(s),r>-1)break;if(r===-1)return new lg(a);const n=a.substring(0,r).trim(),o=a.substring(r+s.length).trim();return new FU(n,s,o)}function zU(a){a=a.replace(LU,"defined[$1]");const e=os.infixToPostfix(a),t=[];for(const s of e)if(s!=="||"&&s!=="&&")t.push(s);else if(t.length>=2){let r=t[t.length-1],n=t[t.length-2];t.length-=2;const o=s=="&&"?new wU:new NU;typeof r=="string"&&(r=r.replace(rE,"defined($1)")),typeof n=="string"&&(n=n.replace(rE,"defined($1)")),o.leftOperand=typeof n=="string"?nE(n):n,o.rightOperand=typeof r=="string"?nE(r):r,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(rE,"defined($1)")),typeof i=="string"?nE(i):i}function Km(a,e){const t=new DU,i=a.substring(0,e);let s=a.substring(e);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new lg(s):i==="#ifndef"?t.testExpression=new lg(s,!0):t.testExpression=zU(s),t}function aE(a,e,t){let i=a.currentLine;for(;BE(a,t);){i=a.currentLine;const s=i.substring(0,5).toLowerCase();if(s==="#else"){const r=new s_;e.children.push(r),BE(a,r);return}else if(s==="#elif"){const r=Km(i,5);e.children.push(r),t=r}}}function BE(a,e){for(;a.canRead;){a.lineIndex++;const t=a.currentLine;if(t.indexOf("#")>=0){const s=VU.exec(t);if(s&&s.length){switch(s[0]){case"#ifdef":{const n=new sE;e.children.push(n);const o=Km(t,6);n.children.push(o),aE(a,n,o);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new sE;e.children.push(n);const o=Km(t,7);n.children.push(o),aE(a,n,o);break}case"#if":{const n=new sE,o=Km(t,3);e.children.push(n),n.children.push(o),aE(a,n,o);break}}continue}}const i=new s_;if(i.line=t,e.children.push(i),t[0]==="#"&&t[1]==="d"){const s=t.replace(";","").split(" ");i.additionalDefineKey=s[1],s.length===3&&(i.additionalDefineValue=s[2])}}return!1}function AI(a,e,t){const i=new s_,s=new OU;return s.lineIndex=-1,s.lines=a.split(` +`),BE(s,i),i.process(e,t)}function RI(a,e){var s;const t=a.defines,i={};for(const r of t){const o=r.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((s=a.processor)==null?void 0:s.shaderLanguage)===vt.GLSL&&(i.GL_ES="true"),i.__VERSION__=a.version,i[a.platformName]="true",CI(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function WU(a,e,t){let i=GU(a,e);if(!e.processor||e.processor.shaderLanguage===vt.GLSL&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;const s=e.defines,r=RI(e,t);return e.processor.preProcessor&&(i=e.processor.preProcessor(i,s,e.isFragment,e.processingContext)),i=AI(i,r,e),e.processor.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function HU(a,e,t){var n,o;let i=a;const s=e.defines,r=RI(e,t);return(n=e.processor)!=null&&n.preProcessor&&(i=e.processor.preProcessor(i,s,e.isFragment,e.processingContext)),i=AI(i,r,e),(o=e.processor)!=null&&o.postProcessor&&(i=e.processor.postProcessor(i,s,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{})),t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function Mp(a,e,t){Mm.length=0;let i;for(;(i=BU.exec(a))!==null;)Mm.push(i);let s=String(a),r=[a],n=!1;for(const o of Mm){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(UU,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let h=e.includesShadersStore[l];if(o[2]){const u=o[3].split(",");for(let d=0;dS+"{X}")),h+=_.replace(IA,x.toString())+` +`}else e.supportsUniformBuffers||(h=h.replace(RA,(d,f)=>f+"{X}")),h=h.replace(IA,u)}const c=[];for(const u of r){const d=u.split(o[0]);for(let f=0;f=0||h.indexOf("#include <")>=0}else{const h=e.shadersRepository+"ShadersInclude/"+l+".fx";II.loadFile(h,c=>{e.includesShadersStore[l]=c,Mp(r.join(""),e,t)});return}}Mm.length=0,s=r.join(""),n?Mp(s.toString(),e,t):t(s)}const II={loadFile:(a,e,t,i,s,r)=>{throw ot("FileTools")}};class Eu{static SetImmediate(e){Vs()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class j{static GetShadersRepository(e=vt.GLSL){return e===vt.GLSL?j.ShadersRepository:j.ShadersRepositoryWGSL}static GetShadersStore(e=vt.GLSL){return e===vt.GLSL?j.ShadersStore:j.ShadersStoreWGSL}static GetIncludesShadersStore(e=vt.GLSL){return e===vt.GLSL?j.IncludesShadersStore:j.IncludesShadersStoreWGSL}}j.ShadersRepository="src/Shaders/";j.ShadersStore={};j.IncludesShadersStore={};j.ShadersRepositoryWGSL="src/ShadersWGSL/";j.ShadersStoreWGSL={};j.IncludesShadersStoreWGSL={};class XU{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,s,r,n,o,l){const h=this.engine;if(h.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,f)=>{s[i[f]]=d}),this._uniforms=s;let u;for(u=0;u{n[d]=f});for(const d of h.getAttributes(this,o))l.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||s.length!==2)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||r.length!==3)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||n.length!==4)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(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,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(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 UE=new WeakMap,YU={_webGLVersion:2,cachedPipelines:{}};function ha(a){let e=UE.get(a);if(!e){if(!a)return YU;e={_webGLVersion:a.TEXTURE_BINDING_3D?2:1,_context:a,cachedPipelines:{}},UE.set(a,e)}return e}function $U(a){UE.delete(a)}function PI(a,e,t,i,s,r){const n=ha(i);r||(r=n._createShaderProgramInjection??rv);const o=VE(e,"vertex",i,n._contextWasLost),l=VE(t,"fragment",i,n._contextWasLost);return r(a,o,l,i,s,n.validateShaderPrograms)}function MI(a,e,t,i,s,r=null,n){const o=ha(s);n||(n=o._createShaderProgramInjection??rv);const l=o._webGLVersion>1?`#version 300 es +#define WEBGL2 +`:"",h=MA(e,"vertex",i,l,s,o._contextWasLost),c=MA(t,"fragment",i,l,s,o._contextWasLost);return n(a,h,c,s,r,o.validateShaderPrograms)}function KU(a,e){const t=new XU,i=ha(a);return i.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function rv(a,e,t,i,s=null,r){const n=i.createProgram();if(a.program=n,!n)throw new Error("Unable to create program");return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),a.context=i,a.vertexShader=e,a.fragmentShader=t,a.isParallelCompiled||OI(a,i,r),n}function OI(a,e,t){const i=a.context,s=a.vertexShader,r=a.fragmentShader,n=a.program;if(!i.getProgramParameter(n,i.LINK_STATUS)){if(!e.getShaderParameter(s,e.COMPILE_STATUS)){const h=e.getShaderInfoLog(s);if(h)throw a.vertexCompilationError=h,new Error("VERTEX SHADER "+h)}if(!e.getShaderParameter(r,e.COMPILE_STATUS)){const h=e.getShaderInfoLog(r);if(h)throw a.fragmentCompilationError=h,new Error("FRAGMENT SHADER "+h)}const l=i.getProgramInfoLog(n);if(l)throw a.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(n),!i.getProgramParameter(n,i.VALIDATE_STATUS))){const h=i.getProgramInfoLog(n);if(h)throw a.programValidationError=h,new Error(h)}i.deleteShader(s),i.deleteShader(r),a.vertexShader=void 0,a.fragmentShader=void 0,a.onCompiled&&(a.onCompiled(),a.onCompiled=void 0)}function jU(a,e,t,i,s,r,n,o,l,h="",c,u){const d=ha(a.context);c||(c=d.createRawShaderProgramInjection??PI),u||(u=d.createShaderProgramInjection??MI);const f=a;i?f.program=c(f,e,t,f.context,l):f.program=u(f,e,t,o,f.context,l),f.program.__SPECTOR_rebuildProgram=n}function MA(a,e,t,i,s,r){return VE(SI(a,t,i),e,s,r)}function VE(a,e,t,i){const s=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!s){let r=t.NO_ERROR,n=t.NO_ERROR;for(;(n=t.getError())!==t.NO_ERROR;)r=n;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${r}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(s,a),t.compileShader(s),s}function qU(a,e){e.useProgram(a)}function DI(a,e){const t=a;if(!t.isParallelCompiled){e(a);return}const i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(a)}}function QU(a,e){return ha(e).cachedPipelines[a]}function nv(a){const e=a._name,t=a.context;if(e&&t){const i=ha(t),s=i.cachedPipelines[e];s==null||s.dispose(),delete i.cachedPipelines[e]}}function ZU(a,e,t,i,s,r,n){let o,l;const h=Vs()?r==null?void 0:r.getHostDocument():null;typeof e=="string"?o=e:e.vertexSource?o="source:"+e.vertexSource:e.vertexElement?o=(h==null?void 0:h.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:e.fragmentSource?l="source:"+e.fragmentSource:e.fragmentElement?l=(h==null?void 0:h.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){a.isFragment=!0;const[d,f]=c;PA(f,a,(m,_)=>{n&&(n._fragmentSourceCodeBeforeMigration=_),t&&(m=t("fragment",m));const x=yI(d,m,a);a=null;const E=JU(x.vertexCode,x.fragmentCode,e,s);i==null||i(E.vertexSourceCode,E.fragmentSourceCode)},r)}};OA(o,"Vertex","",d=>{bI(a),PA(d,a,(f,m)=>{n&&(n._rawVertexSourceCode=d,n._vertexSourceCodeBeforeMigration=m),t&&(f=t("vertex",f)),c[0]=f,u()},r)},s),OA(l,"Fragment","Pixel",d=>{n&&(n._rawFragmentSourceCode=d),c[1]=d,u()},s)}function OA(a,e,t,i,s,r){if(typeof HTMLElement<"u"&&a instanceof HTMLElement){const l=sv(a);i(l);return}if(a.substr(0,7)==="source:"){i(a.substr(7));return}if(a.substr(0,7)==="base64:"){const l=window.atob(a.substr(7));i(l);return}const n=j.GetShadersStore(s);if(n[a+e+"Shader"]){i(n[a+e+"Shader"]);return}if(t&&n[a+t+"Shader"]){i(n[a+t+"Shader"]);return}let o;if(a[0]==="."||a[0]==="/"||a.indexOf("http")>-1?o=a:o=j.GetShadersRepository(s)+a,r=r||vI,!r)throw new Error("loadFileInjection is not defined");r(o+"."+e.toLowerCase()+".fx",i)}function JU(a,e,t,i){if(t){const s=t.vertexElement||t.vertex||t.spectorName||t,r=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===vt.WGSL?"//":"")+"#define SHADER_NAME vertex:"+s+` +`+a,fragmentSourceCode:(i===vt.WGSL?"//":"")+"#define SHADER_NAME fragment:"+r+` +`+e}}else return{vertexSourceCode:a,fragmentSourceCode:e}}const eV=(a,e,t)=>{try{const i=a.existingPipelineContext||e(a.shaderProcessingContext);if(i._name=a.name,a.name&&a.context){const s=ha(a.context);s.cachedPipelines[a.name]=i}return t(i,a.vertex,a.fragment,!!a.createAsRaw,"","",a.rebuildRebind,a.defines,a.transformFeedbackVaryings,""),DI(i,s=>{var r;(r=a.onRenderingStateCompiled)==null||r.call(a,s)}),i}catch(i){throw U.Error("Error compiling effect"),i}};class ri{static get ShadersRepository(){return j.ShadersRepository}static set ShadersRepository(e){j.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new K),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,l=null,h=null,c,u="",d=vt.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this._onBindObservable=null,this._isDisposed=!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=u;const f=this._key.replace(/\r/g,"").replace(/\n/g,"|");let m;if(t.attributes){const _=t;if(this._engine=i,this._attributesNames=_.attributes,this._uniformsNames=_.uniformsNames.concat(_.samplers),this._samplerList=_.samplers.slice(),this.defines=_.defines,this.onError=_.onError,this.onCompiled=_.onCompiled,this._fallbacks=_.fallbacks,this._indexParameters=_.indexParameters,this._transformFeedbackVaryings=_.transformFeedbackVaryings||null,this._multiTarget=!!_.multiTarget,this._shaderLanguage=_.shaderLanguage??vt.GLSL,_.uniformBuffersNames){this._uniformBuffersNamesList=_.uniformBuffersNames.slice();for(let x=0;x<_.uniformBuffersNames.length;x++)this._uniformBuffersNames[_.uniformBuffersNames[x]]=x}this._processFinalCode=_.processFinalCode??null,this._processCodeAfterIncludes=_.processCodeAfterIncludes??void 0,m=_.existingPipelineContext}else this._engine=r,this.defines=n??"",this._uniformsNames=i.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=d,this.onError=h,this.onCompiled=l,this._indexParameters=c,this._fallbacks=o;this._engine.shaderPlatformName==="WEBGL2"&&(m=QU(f,this._engine._gl)??m),this._attributeLocationByName={},this.uniqueId=ri._UniqueIdSeed++,m?(this._pipelineContext=m,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCode()}_processShaderCode(e=null,t=!1){this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);const i={defines:this.defines.split(` +`),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:j.GetShadersRepository(this._shaderLanguage),includesShadersStore:j.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes};ZU(i,this.name,this._processFinalCode,(s,r)=>{this._vertexSourceCode=s,this._fragmentSourceCode=r,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,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(r,n)=>{s&&s(n)},this.onCompiled=()=>{var n,o;const r=this.getEngine().scenes;if(r)for(let l=0;lthis._rebuildProgram(l,h,c,u),defines:s,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._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&n.length===2){const o=parseInt(n[1]),l=e.split(` +`,-1);l.length>=o&&(r=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var n,o,l;this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(U.Error("Unable to compile effect:"),U.Error("Uniforms: "+this._uniformsNames.map(function(h){return" "+h})),U.Error("Attributes: "+i.map(function(h){return" "+h})),U.Error(`Defines: +`+this.defines),ri.LogShaderCodeOnCompilationError){let h=null,c=null,u=null;(n=this._pipelineContext)!=null&&n._getVertexShaderCode()&&([u,h]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),u&&(U.Error("Vertex code:"),U.Error(u))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([u,c]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),u&&(U.Error("Fragment code:"),U.Error(u))),h&&U.Error(h),c&&U.Error(c)}U.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,U.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){const s=this._samplerList.indexOf(e);for(let n=1;n{s._swapAndDie(this,!1),this.isReady=t.isReady};t.isAsync?t.proxy.then(i):i(t.proxy);return}let e;switch(this.source){case xt.Temp:break;case xt.Url: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 xt.Raw: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 xt.Raw3D: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 xt.Raw2DArray: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 xt.Dynamic: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 xt.Cube: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);return;case xt.CubeRaw: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 xt.CubeRawRGBD:return;case xt.CubePrefiltered: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;case xt.DepthStencil:case xt.Depth:break}}_swapAndDie(e,t=!0){var r;(r=this._hardwareTexture)==null||r.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 s=i.indexOf(this);s!==-1&&i.splice(s,1),s=i.indexOf(e),s===-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)}}$t._Counter=0;function LI(a,e){if(Vs()){const{requestAnimationFrame:t}=e||window;if(typeof t=="function")return t(a)}else if(typeof requestAnimationFrame=="function")return requestAnimationFrame(a);return setTimeout(a,16)}class He{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()}ri.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(){U.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,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,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,Vs()){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;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let t=0;t-1?e.substring(I).toLowerCase():""),N=null;R.indexOf("?")>-1&&(R=R.split("?")[0]);for(const ne of He._TextureLoaders)if(ne.canLoad(R,m)){N=ne;break}s&&s.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=r,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(!!x,t),this._doNotHandleContextLost||(y._buffer=c);let B=null;n&&!u&&(B=y.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(y);const Q=(ne,de)=>{s&&s.removePendingData(y),e===A?(B&&y.onLoadedObservable.remove(B),We.UseFallbackTexture&&e!==We.FallbackTexture&&this._createTextureBase(We.FallbackTexture,t,y.invertY,s,r,null,o,l,h,c,y),ne=(ne||"Unknown error")+(We.UseFallbackTexture?" - Fallback texture was used":""),y.onErrorObservable.notifyObservers({message:ne,exception:de}),o&&o(ne,de)):(U.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,y.invertY,s,r,n,o,l,h,c,y,d,f,m,_,x))};if(N){const ne=de=>{N.loadData(de,y,(ge,fe,Ee,De,Te,ue)=>{ue?Q("TextureLoader failed to load data"):l(y,R,s,{width:ge,height:fe},y.invertY,!Ee,De,()=>(Te(),!1),r)},_)};c?c instanceof ArrayBuffer?ne(new Uint8Array(c)):ArrayBuffer.isView(c)?ne(c):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,de=>ne(new Uint8Array(de)),void 0,s?s.offlineProvider:void 0,!0,(de,ge)=>{Q("Unable to load "+(de&&de.responseURL,ge))})}else{const ne=de=>{S&&!this._doNotHandleContextLost&&(y._buffer=de),l(y,R,s,de,y.invertY,t,!1,h,r)};!E||C?c&&(typeof c.decoding=="string"||c.close)?ne(c):He._FileToolsLoadImage(e||"",ne,Q,s?s.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):typeof c=="string"||c instanceof ArrayBuffer||ArrayBuffer.isView(c)||c instanceof Blob?He._FileToolsLoadImage(c,ne,Q,s?s.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):c&&ne(c)}return y}_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:sp()?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.5.0"}static get Version(){return"7.5.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 n,o;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new NI,this._stencilStateComposer=new wI,this._stencilState=new ul,this._alphaState=new tV,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 K,this.onCanvasFocusObservable=new K,this.onNewSceneAddedObservable=new K,this.onResizeObservable=new K,this.onCanvasPointerOutObservable=new K,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 K,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new K,this.onAfterShaderCompilationObservable=new K,this.onBeginFrameObservable=new K,this.onEndFrameObservable=new K,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new K,this.onContextRestoredObservable=new K,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 K,We.Instances.push(this),this.startTime=ks.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,ur.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Qc()&&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=((n=t.audioEngineOptions)==null?void 0:n.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 s=Vs()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const s=Vs()&&window.devicePixelRatio||1,r=this._lastDevicePixelRatio/s;this._lastDevicePixelRatio=s,this._hardwareScalingLevel*=r}if(Vs()&&sp())if(this._renderingCanvas){const s=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||s.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||s.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 s=0;s{const e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&sp()&&"ontouchend"in document},this._checkForMobile(),Vs()&&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 He._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw ot("FileTools")}_loadFile(e,t,i,s,r,n){const o=vI(e,t,i,s,r,n);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,s,r,n){if(hg.loadFile)return hg.loadFile(e,t,i,s,r,n);throw ot("FileTools")}dispose(){var t;for(this.hideLoadingUI(),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),ri.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(),Vs()&&window.removeEventListener("resize",this._checkForMobile);const e=We.Instances.indexOf(this);e>=0&&We.Instances.splice(e,1),We.Instances.length||We.OnEnginesDisposedObservable.notifyObservers(this),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw ot("LoadingScreen")}}He._TextureLoaders=[];He._RenderPassIdCounter=0;He._RescalePostProcessFactory=null;const BI=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Op extends oo{constructor(e,t){super(e,ml.LoadFileError),this.name="LoadFileError",Tu._setPrototypeOf(this,Op.prototype),t instanceof hs?this.request=t:this.file=t}}class cg extends oo{constructor(e,t){super(e,ml.RequestFileError),this.request=t,this.name="RequestFileError",Tu._setPrototypeOf(this,cg.prototype)}}class av extends oo{constructor(e,t){super(e,ml.ReadFileError),this.file=t,this.name="ReadFileError",Tu._setPrototypeOf(this,av.prototype)}}const Ls={DefaultRetryStrategy:AU.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:a=>a,ScriptBaseUrl:"",ScriptPreprocessUrl:a=>a};let UI=a=>(a=a.replace(/#/gm,"%23"),a);const ov=(a,e)=>{if(!(a&&a.indexOf("data:")===0)&&Ls.CorsBehavior)if(typeof Ls.CorsBehavior=="string"||Ls.CorsBehavior instanceof String)e.crossOrigin=Ls.CorsBehavior;else{const t=Ls.CorsBehavior(a);t&&(e.crossOrigin=t)}},r_=(a,e,t,i,s="",r)=>{const n=We.LastCreatedEngine;if(typeof HTMLImageElement>"u"&&!(n!=null&&n._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;a instanceof ArrayBuffer||ArrayBuffer.isView(a)?typeof Blob<"u"&&typeof URL<"u"?(o=URL.createObjectURL(new Blob([a],{type:s})),l=!0):o=`data:${s};base64,`+TI(a):a instanceof Blob?(o=URL.createObjectURL(a),l=!0):(o=UI(a),o=Ls.PreprocessUrl(a));const h=A=>{if(t){const I=o||a.toString();t(`Error while trying to load image: ${I.indexOf("http")===0||I.length<=128?I:I.slice(0,128)+"..."}`,A)}};if(n!=null&&n._features.forceBitmapOverHTMLImageElement)return _h(o,A=>{n.createImageBitmap(new Blob([A],{type:s}),{premultiplyAlpha:"none",...r}).then(I=>{e(I),l&&URL.revokeObjectURL(o)}).catch(I=>{t&&t("Error while trying to load image: "+a,I)})},void 0,i||void 0,!0,(A,I)=>{h(I)}),null;const c=new Image;ov(o,c);const u=[],d=()=>{u.forEach(A=>{A.target.addEventListener(A.name,A.handler)})},f=()=>{u.forEach(A=>{A.target.removeEventListener(A.name,A.handler)}),u.length=0},m=()=>{f(),e(c),l&&c.src&&URL.revokeObjectURL(c.src)},_=A=>{f(),h(A),l&&c.src&&URL.revokeObjectURL(c.src)},x=A=>{if(A.blockedURI!==c.src)return;f();const I=new Error(`CSP violation of policy ${A.effectiveDirective} ${A.blockedURI}. Current policy is ${A.originalPolicy}`);We.UseFallbackTexture=!1,h(I),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""};u.push({target:c,name:"load",handler:m}),u.push({target:c,name:"error",handler:_}),u.push({target:document,name:"securitypolicyviolation",handler:x}),d();const E=o.substring(0,5)==="blob:",S=o.substring(0,5)==="data:",C=()=>{E||S||!hs.IsCustomRequestAvailable?c.src=o:_h(o,(A,I,R)=>{const N=!s&&R?R:s,k=new Blob([A],{type:N}),B=URL.createObjectURL(k);l=!0,c.src=B},void 0,i||void 0,!0,(A,I)=>{h(I)})},y=()=>{i&&i.loadImage(o,c)};if(!E&&!S&&i&&i.enableTexturesOffline)i.open(y,C);else{if(o.indexOf("file:")!==-1){const A=decodeURIComponent(o.substring(5).toLowerCase());if(rp.FilesToLoad[A]&&typeof URL<"u"){try{let I;try{I=URL.createObjectURL(rp.FilesToLoad[A])}catch{I=URL.createObjectURL(rp.FilesToLoad[A])}c.src=I,l=!0}catch{c.src=""}return c}}C()}return c},Dp=(a,e,t,i,s)=>{const r=new FileReader,n={onCompleteObservable:new K,abort:()=>r.abort()};return r.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(r.onerror=()=>{s(new av(`Unable to read ${a.name}`,a))}),r.onload=o=>{e(o.target.result)},t&&(r.onprogress=t),i?r.readAsArrayBuffer(a):r.readAsText(a),n},_h=(a,e,t,i,s,r,n)=>{if(a.name)return Dp(a,e,t,s,r?c=>{r(void 0,c)}:void 0);const o=a;if(o.indexOf("file:")!==-1){let c=decodeURIComponent(o.substring(5).toLowerCase());c.indexOf("./")===0&&(c=c.substring(2));const u=rp.FilesToLoad[c];if(u)return Dp(u,e,t,s,r?d=>r(void 0,new Op(d.message,d.file)):void 0)}const{match:l,type:h}=iV(o);if(l){const c={onCompleteObservable:new K,abort:()=>()=>{}};try{const u=s?n_(o):kI(o);e(u,void 0,h)}catch(u){r?r(void 0,u):U.Error(u.message||"Failed to parse the Data URL")}return Eu.SetImmediate(()=>{c.onCompleteObservable.notifyObservers(c)}),c}return lv(o,(c,u)=>{e(c,u==null?void 0:u.responseURL,u==null?void 0:u.getResponseHeader("content-type"))},t,i,s,r?c=>{r(c.request,new Op(c.message,c.request))}:void 0,n)},lv=(a,e,t,i,s,r,n)=>{a=UI(a),a=Ls.PreprocessUrl(a);const o=Ls.BaseUrl+a;let l=!1;const h={onCompleteObservable:new K,abort:()=>l=!0},c=()=>{let u=new hs,d=null,f;const m=()=>{u&&(t&&u.removeEventListener("progress",t),f&&u.removeEventListener("readystatechange",f),u.removeEventListener("loadend",_))};let _=()=>{m(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),t=void 0,f=null,_=null,r=void 0,n=void 0,e=void 0};h.abort=()=>{l=!0,_&&_(),u&&u.readyState!==(XMLHttpRequest.DONE||4)&&u.abort(),d!==null&&(clearTimeout(d),d=null),u=null};const x=S=>{const C=S.message||"Unknown error";r&&u?r(new cg(C,u)):U.Error(C)},E=S=>{if(u){if(u.open("GET",o),n)try{n(u)}catch(C){x(C);return}s&&(u.responseType="arraybuffer"),t&&u.addEventListener("progress",t),_&&u.addEventListener("loadend",_),f=()=>{if(!(l||!u)&&u.readyState===(XMLHttpRequest.DONE||4)){if(f&&u.removeEventListener("readystatechange",f),u.status>=200&&u.status<300||u.status===0&&(!Vs()||VI())){try{e&&e(s?u.response:u.responseText,u)}catch(A){x(A)}return}const C=Ls.DefaultRetryStrategy;if(C){const A=C(o,u,S);if(A!==-1){m(),u=new hs,d=setTimeout(()=>E(S+1),A);return}}const y=new cg("Error status: "+u.status+" "+u.statusText+" - Unable to load "+o,u);r&&r(y)}},u.addEventListener("readystatechange",f),u.send()}};E(0)};if(i&&i.enableSceneOffline){const u=f=>{f&&f.status>400?r&&r(f):c()},d=()=>{i&&i.loadFile(Ls.BaseUrl+a,f=>{!l&&e&&e(f),h.onCompleteObservable.notifyObservers(h)},t?f=>{!l&&t&&t(f)}:void 0,u,s)};i.open(d,u)}else c();return h},VI=()=>typeof location<"u"&&location.protocol==="file:",Bg=a=>BI.test(a),iV=a=>{const e=BI.exec(a);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace("base64,","")}};function n_(a){return IU(a.split(",")[1])}const kI=a=>EI(a.split(",")[1]),sV=()=>{He._FileToolsLoadImage=r_,hg.loadFile=_h,II.loadFile=_h};sV();let $f;const rV=(a,e,t,i,s,r,n,o,l,h)=>{$f={DecodeBase64UrlToBinary:a,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:s,LoadFile:r,LoadImage:n,ReadFile:o,RequestFile:l,SetCorsBehavior:h},Object.defineProperty($f,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(c){t.DefaultRetryStrategy=c}}),Object.defineProperty($f,"BaseUrl",{get:function(){return t.BaseUrl},set:function(c){t.BaseUrl=c}}),Object.defineProperty($f,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(c){t.PreprocessUrl=c}}),Object.defineProperty($f,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(c){t.CorsBehavior=c}})};rV(n_,kI,Ls,Bg,VI,_h,r_,Dp,lv,ov);class np{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=rs(e);if(t)return t;U.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let r=0,n=i.length;r{const e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}function Np(a){let e=1;do e*=2;while(ea-t?t:e}function cv(a){return a--,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a|=a>>16,a++,a}function Ug(a){return a=a|a>>1,a=a|a>>2,a=a|a>>4,a=a|a>>8,a=a|a>>16,a-(a>>1)}function on(a,e,t=2){let i;switch(t){case 1:i=Ug(a);break;case 2:i=hv(a);break;case 3:default:i=cv(a);break}return Math.min(i,e)}class Z{static get BaseUrl(){return Ls.BaseUrl}static set BaseUrl(e){Ls.BaseUrl=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("://"){_h(e,r=>{i(r)},void 0,void 0,t,(r,n)=>{s(n)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Z.ScriptBaseUrl&&e.startsWith(Z._DefaultCdnUrl)){const i=Z.ScriptBaseUrl[Z.ScriptBaseUrl.length-1]==="/"?Z.ScriptBaseUrl.substring(0,Z.ScriptBaseUrl.length-1):Z.ScriptBaseUrl;e=e.replace(Z._DefaultCdnUrl,i)}return e=Z.ScriptPreprocessUrl(e),t&&(e=Z.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Z.GetBabylonScriptURL(e),Z.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Z.GetBabylonScriptURL(e),Z.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if(typeof importScripts=="function"){try{importScripts(e),t()}catch(o){i==null||i(`Unable to load script '${e}' in worker`,o)}return}else if(!Vs()){i==null||i(`Cannot load script '${e}' outside of a window or a worker`);return}const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=o=>{i&&i(`Unable to load script '${e}'`,o)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise((i,s)=>{this.LoadScript(e,()=>{i()},(r,n)=>{s(n||new Error(r))},t)})}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new K,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=n=>{t(n.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return Dp(e,t,i,s,r)}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,s){Tr.DeepCopy(e,t,i,s)}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(n,o).split(",")[1]),h=l.length,c=new Uint8Array(h);for(let u=0;ut(r)):e.toBlob(function(r){t(r)},i,s)}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"}Z.Download(e,t)}else if(e&&typeof URL<"u"){const i=URL.createObjectURL(e),s=window.open("");if(!s)return;const r=s.document.createElement("img");r.onload=function(){URL.revokeObjectURL(i)},r.src=i,s.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if(typeof s=="string"||!t)this.ToBlob(e,function(n){n&&Z.DownloadBlob(n,s),t&&t("")},i,r);else if(t){if(Z._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:r}).then(o=>{const l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{const h=l.result;t(h)}});return}const n=e.toDataURL(i,r);t(n)}}static Download(e,t){if(typeof URL>"u")return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",()=>{s.parentElement&&s.parentElement.removeChild(s)}),s.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,s,r="image/png",n=!1,o){throw ot("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw ot("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,l,h=!1,c=!1,u=!0,d){throw ot("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,l=!1,h=!1,c=!0,u){throw ot("ScreenshotTools")}static RandomId(){return La()}static IsBase64(e){return Bg(e)}static DecodeBase64(e){return n_(e)}static get errorsCount(){return U.errorsCount}static Log(e){U.Log(e)}static Warn(e){U.Warn(e)}static Error(e){U.Error(e)}static get LogCache(){return U.LogCache}static ClearLogCache(){U.ClearLogCache()}static set LogLevels(e){U.LogLevels=e}static set PerformanceLogLevel(e){if((e&Z.PerformanceUserMarkLogLevel)===Z.PerformanceUserMarkLogLevel){Z.StartPerformanceCounter=Z._StartUserMark,Z.EndPerformanceCounter=Z._EndUserMark;return}if((e&Z.PerformanceConsoleLogLevel)===Z.PerformanceConsoleLogLevel){Z.StartPerformanceCounter=Z._StartPerformanceConsole,Z.EndPerformanceCounter=Z._EndPerformanceConsole;return}Z.StartPerformanceCounter=Z._StartPerformanceCounterDisabled,Z.EndPerformanceCounter=Z._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Z._Performance){if(!Vs())return;Z._Performance=window.performance}!t||!Z._Performance.mark||Z._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!Z._Performance.mark||(Z._Performance.mark(e+"-End"),Z._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Z._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Z._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ks.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,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(s!=null?s+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Qc()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}}Z.UseCustomRequestHeaders=!1;Z.CustomRequestHeaders=hs.CustomRequestHeaders;Z.GetDOMTextContent=sv;Z._DefaultCdnUrl="https://cdn.babylonjs.com";Z.GetAbsoluteUrl=typeof document=="object"?a=>{const e=document.createElement("a");return e.href=a,e.href}:typeof URL=="function"&&typeof location=="object"?a=>new URL(a,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};Z.NoneLogLevel=U.NoneLogLevel;Z.MessageLogLevel=U.MessageLogLevel;Z.WarningLogLevel=U.WarningLogLevel;Z.ErrorLogLevel=U.ErrorLogLevel;Z.AllLogLevel=U.AllLogLevel;Z.IsWindowObjectExist=Vs;Z.PerformanceNoneLogLevel=0;Z.PerformanceUserMarkLogLevel=1;Z.PerformanceConsoleLogLevel=2;Z.StartPerformanceCounter=Z._StartPerformanceCounterDisabled;Z.EndPerformanceCounter=Z._EndPerformanceCounterDisabled;class Fa{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(h),r&&r()){o.breakLoop();break}}o.executeNext()},n)},s)}}Z.Mix=kE;Z.IsExponentOfTwo=Np;We.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 Ps{constructor(e){this.length=0,this.data=new Array(e),this._id=Ps._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}}Ps._GlobalId=0;class Yl extends Ps{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],s=e(t,i);if(s)return s}return null}}function GI(a){a.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class Ji{constructor(){this._dirty=!0,this._tempColor=new Oe(0,0,0,0),this._globalCurve=new Oe(0,0,0,0),this._highlightsCurve=new Oe(0,0,0,0),this._midtonesCurve=new Oe(0,0,0,0),this._shadowsCurve=new Oe(0,0,0,0),this._positiveCurve=new Oe(0,0,0,0),this._negativeCurve=new Oe(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",s="vCameraColorCurveNeutral",r="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(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){e!=null&&(e=Ji._Clamp(e,0,360),t=Ji._Clamp(t,-100,100),i=Ji._Clamp(i,-100,100),s=Ji._Clamp(s,-100,100),t=Ji._ApplyColorGradingSliderNonlinear(t),t*=.5,s=Ji._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),Ji._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.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,s){let r=Ji._Clamp(e,0,360);const n=Ji._Clamp(t/100,0,1),o=Ji._Clamp(i/100,0,1);if(n===0)s.r=o,s.g=o,s.b=o;else{r/=60;const l=Math.floor(r),h=r-l,c=o*(1-n),u=o*(1-n*h),d=o*(1-n*(1-h));switch(l){case 0:s.r=o,s.g=d,s.b=c;break;case 1:s.r=u,s.g=o,s.b=c;break;case 2:s.r=c,s.g=o,s.b=d;break;case 3:s.r=c,s.g=u,s.b=o;break;case 4:s.r=d,s.g=c,s.b=o;break;default:s.r=o,s.g=c,s.b=u;break}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Pe.Clone(()=>new Ji,this)}serialize(){return Pe.Serialize(this)}static Parse(e){return Pe.Parse(()=>new Ji,e,null,null)}}Ji.PrepareUniforms=GI;v([O()],Ji.prototype,"_globalHue",void 0);v([O()],Ji.prototype,"_globalDensity",void 0);v([O()],Ji.prototype,"_globalSaturation",void 0);v([O()],Ji.prototype,"_globalExposure",void 0);v([O()],Ji.prototype,"_highlightsHue",void 0);v([O()],Ji.prototype,"_highlightsDensity",void 0);v([O()],Ji.prototype,"_highlightsSaturation",void 0);v([O()],Ji.prototype,"_highlightsExposure",void 0);v([O()],Ji.prototype,"_midtonesHue",void 0);v([O()],Ji.prototype,"_midtonesDensity",void 0);v([O()],Ji.prototype,"_midtonesSaturation",void 0);v([O()],Ji.prototype,"_midtonesExposure",void 0);Pe._ColorCurvesParser=Ji.Parse;function zI(a,e){e.EXPOSURE&&a.push("exposureLinear"),e.CONTRAST&&a.push("contrast"),e.COLORGRADING&&a.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&a.push("vInverseScreenSize"),e.VIGNETTE&&(a.push("vignetteSettings1"),a.push("vignetteSettings2")),e.COLORCURVES&&GI(a),e.DITHER&&a.push("ditherIntensity")}function WI(a,e){e.COLORGRADING&&a.push("txColorTransform")}class Mt{constructor(){this.colorCurves=new Ji,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Mt.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Oe(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Mt.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new K}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===Mt._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case Mt.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Mt.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&&Ji.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=t??s/i;let n=Math.tan(this.vignetteCameraFov*.5),o=n*r;const l=Math.sqrt(o*n);o=kE(o,l,this.vignetteStretch),n=kE(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}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 Pe.Clone(()=>new Mt,this)}serialize(){return Pe.Serialize(this)}static Parse(e){const t=Pe.Parse(()=>new Mt,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}}Mt.TONEMAPPING_STANDARD=0;Mt.TONEMAPPING_ACES=1;Mt.TONEMAPPING_KHR_PBR_NEUTRAL=2;Mt.PrepareUniforms=zI;Mt.PrepareSamplers=WI;Mt._VIGNETTEMODE_MULTIPLY=0;Mt._VIGNETTEMODE_OPAQUE=1;v([TU()],Mt.prototype,"colorCurves",void 0);v([O()],Mt.prototype,"_colorCurvesEnabled",void 0);v([Dt("colorGradingTexture")],Mt.prototype,"_colorGradingTexture",void 0);v([O()],Mt.prototype,"_colorGradingEnabled",void 0);v([O()],Mt.prototype,"_colorGradingWithGreenDepth",void 0);v([O()],Mt.prototype,"_colorGradingBGR",void 0);v([O()],Mt.prototype,"_exposure",void 0);v([O()],Mt.prototype,"_toneMappingEnabled",void 0);v([O()],Mt.prototype,"_toneMappingType",void 0);v([O()],Mt.prototype,"_contrast",void 0);v([O()],Mt.prototype,"vignetteStretch",void 0);v([O()],Mt.prototype,"vignetteCenterX",void 0);v([O()],Mt.prototype,"vignetteCenterY",void 0);v([O()],Mt.prototype,"vignetteWeight",void 0);v([tv()],Mt.prototype,"vignetteColor",void 0);v([O()],Mt.prototype,"vignetteCameraFov",void 0);v([O()],Mt.prototype,"_vignetteBlendMode",void 0);v([O()],Mt.prototype,"_vignetteEnabled",void 0);v([O()],Mt.prototype,"_ditheringEnabled",void 0);v([O()],Mt.prototype,"_ditheringIntensity",void 0);v([O()],Mt.prototype,"_skipFinalColorClamp",void 0);v([O()],Mt.prototype,"_applyByPostProcess",void 0);v([O()],Mt.prototype,"_isEnabled",void 0);Pe._ImageProcessingConfigurationParser=Mt.Parse;function HI(a){return a.getPipelineContext===void 0}class nV{constructor(){this.shaderLanguage=vt.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const n=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(n,"")}return e}}const aV=/(flat\s)?\s*varying\s*.*/;class XI{constructor(){this.shaderLanguage=vt.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return aV.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,r=/#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(r,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){const n=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,(s||n?"":`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 _c{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=_c._Counter++}}_c._Counter=0;class wp extends _c{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class of{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 oV{}class nt extends He{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return ri.ShadersRepository}static set ShadersRepository(e){ri.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,s){if(i=i||{},super(t??i.antialias,i,s),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 r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();const l=navigator.userAgent;for(const h of nt.ExceptionList){const c=h.key,u=h.targets;if(new RegExp(c).test(l)){if(h.capture&&h.captureConstraint){const f=h.capture,m=h.captureConstraint,x=new RegExp(f).exec(l);if(x&&x.length>0&&parseInt(x[x.length-1])>=m)continue}for(const f of u)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,U.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.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(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.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 XI:new nV;const n=`Babylon.js v${nt.Version}`;U.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=ha(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const t=this._gl.getExtension("WEBGL_draw_buffers");if(t!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const t=this._gl.getExtension("WEBGL_depth_texture");t!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=t.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const t=this._gl.getExtension("OES_vertex_array_object");t!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=t.createVertexArrayOES.bind(t),this._gl.bindVertexArray=t.bindVertexArrayOES.bind(t),this._gl.deleteVertexArray=t.deleteVertexArrayOES.bind(t))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const t=this._gl.getExtension("ANGLE_instanced_arrays");t!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=t.drawArraysInstancedANGLE.bind(t),this._gl.drawElementsInstanced=t.drawElementsInstancedANGLE.bind(t),this._gl.vertexAttribDivisor=t.vertexAttribDivisorANGLE.bind(t)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const t=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),i=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);t&&i&&(this._caps.highPrecisionShaderSupported=t.precision!==0&&i.precision!==0)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const t=this._gl.getExtension("EXT_blend_minmax");t!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=t.MAX_EXT,this._gl.MIN=t.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const t=this._gl.getExtension("EXT_sRGB");t!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:t.SRGB_EXT,SRGB8:t.SRGB_ALPHA_EXT,SRGB8_ALPHA8:t.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let t=0;t"u",supportRenderAndCopyToLodForFloatTextures:this._webGLVersion!==1,supportDepthStencilTexture:this._webGLVersion!==1,supportShadowSamplers:this._webGLVersion!==1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:this._webGLVersion!==1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:this._webGLVersion!==1,basisNeedsPOT:this._webGLVersion===1,support3DTextures:this._webGLVersion!==1,needTypeSuffixInShaderConstants:this._webGLVersion!==1,supportMSAA:this._webGLVersion!==1,supportSSAO2:this._webGLVersion!==1,supportExtendedTextureFormats:this._webGLVersion!==1,supportSwitchCaseInShader:this._webGLVersion!==1,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_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,s=!1){var o,l;const r=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=r;let n=0;if(t&&e){let h=!0;if(this._currentRenderTarget){const c=(o=this._currentRenderTarget.texture)==null?void 0:o.format;if(c===8||c===9||c===10||c===11){const u=(l=this._currentRenderTarget.texture)==null?void 0:l.type;u===7||u===5?(nt._TempClearColorUint32[0]=e.r*255,nt._TempClearColorUint32[1]=e.g*255,nt._TempClearColorUint32[2]=e.b*255,nt._TempClearColorUint32[3]=e.a*255,this._gl.clearBufferuiv(this._gl.COLOR,0,nt._TempClearColorUint32),h=!1):(nt._TempClearColorInt32[0]=e.r*255,nt._TempClearColorInt32[1]=e.g*255,nt._TempClearColorInt32[2]=e.b*255,nt._TempClearColorInt32[3]=e.a*255,this._gl.clearBufferiv(this._gl.COLOR,0,nt._TempClearColorInt32),h=!1)}}h&&(this._gl.clearColor(e.r,e.g,e.b,e.a!==void 0?e.a:1),n|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),s&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)}_viewport(e,t,i,s){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||s!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=s,this._gl.viewport(e,t,i,s))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,i,s,r,n=0,o=0){var u,d,f,m,_,x;const l=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(l._MSAAFramebuffer?l._MSAAFramebuffer:l._framebuffer);const h=this._gl;e.isMulti||(e.is2DArray||e.is3D?h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,(u=e.texture._hardwareTexture)==null?void 0:u.underlyingResource,n,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(d=e.texture._hardwareTexture)==null?void 0:d.underlyingResource,n):l._currentLOD!==n&&(h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,(f=e.texture._hardwareTexture)==null?void 0:f.underlyingResource,n),l._currentLOD=n));const c=e._depthStencilTexture;if(c){e.is3D&&(e.texture.width!==c.width||e.texture.height!==c.height||e.texture.depth!==c.depth)&&U.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment");const E=e._depthStencilTextureWithStencil?h.DEPTH_STENCIL_ATTACHMENT:h.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?h.framebufferTextureLayer(h.FRAMEBUFFER,E,(m=c._hardwareTexture)==null?void 0:m.underlyingResource,n,o):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,E,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,(_=c._hardwareTexture)==null?void 0:_.underlyingResource,n):h.framebufferTexture2D(h.FRAMEBUFFER,E,h.TEXTURE_2D,(x=c._hardwareTexture)==null?void 0:x.underlyingResource,n)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,i,s):(i||(i=e.width,n&&(i=i/Math.pow(2,n))),s||(s=e.height,n&&(s=s/Math.pow(2,n))),this._viewport(0,0,i,s)),this.wipeCaches()}setState(e,t=0,i,s=!1,r,n,o=0){(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);const l=this.cullBackFaces??r??!0?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==l||i)&&(this._depthCullingState.cullFace=l),this.setZOffset(t),this.setZOffsetUnits(o);const h=s?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==h||i)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=n}_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 n;const s=e;this._currentRenderTarget=null;const r=this._gl;if(s._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}r.bindFramebuffer(r.READ_FRAMEBUFFER,s._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,s._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}(n=e.texture)!=null&&n.generateMipMaps&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(s._MSAAFramebuffer&&this._bindUnboundFramebuffer(s._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 s=new wp(i);return this.bindArrayBuffer(s),typeof e!="number"?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),s.capacity=e.length*4):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),s.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),s.capacity=e),this._resetVertexBufferBinding(),s.references=1,s}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){const s=this._gl.createBuffer(),r=new wp(s);if(!s)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=n.BYTES_PER_ELEMENT===4,r}_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 s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,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,s,r,n,o){const l=this._currentBufferPointers[t];if(!l)return;let h=!1;l.active?(l.buffer!==e&&(l.buffer=e,h=!0),l.size!==i&&(l.size=i,h=!0),l.type!==s&&(l.type=s,h=!0),l.normalized!==r&&(l.normalized=r,h=!0),l.stride!==n&&(l.stride=n,h=!0),l.offset!==o&&(l.offset=o,h=!0)):(h=!0,l.active=!0,l.index=t,l.size=i,l.type=s,l.normalized=r,l.stride=n,l.offset=o,l.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const o=s[r];let l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const h=l.getBuffer();h&&(this._vertexAttribPointer(h,n,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(h))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}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,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const n=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(h),this._vertexAttribArraysEnabled[h]=!0,this._vertexAttribPointer(e,h,i[l],this._gl.FLOAT,!1,s,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(n===1&&!this._caps.textureFloatLinearFiltering||n===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),n===1&&!this._caps.textureFloat&&(n=0,U.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,f=new $t(this,s),m=e.width||e,_=e.height||e,x=e.depth||0,E=e.layers||0,S=this._getSamplingParameters(o,r),C=E!==0?d.TEXTURE_2D_ARRAY:x!==0?d.TEXTURE_3D:d.TEXTURE_2D,y=this._getRGBABufferInternalSizedFormat(n,l,h),A=this._getInternalFormat(l),I=this._getWebGLTextureType(n);return this._bindTextureDirectly(C,f),E!==0?(f.is2DArray=!0,d.texImage3D(C,0,y,m,_,E,0,A,I,null)):x!==0?(f.is3D=!0,d.texImage3D(C,0,y,m,_,x,0,A,I,null)):d.texImage2D(C,0,y,m,_,0,A,I,null),d.texParameteri(C,d.TEXTURE_MAG_FILTER,S.mag),d.texParameteri(C,d.TEXTURE_MIN_FILTER,S.min),d.texParameteri(C,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(C,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),r&&this._gl.generateMipmap(C),this._bindTextureDirectly(C,null),f._useSRGBBuffer=h,f.baseWidth=m,f.baseHeight=_,f.width=m,f.height=_,f.depth=E,f.isReady=!0,f.samples=c,f.generateMipMaps=r,f.samplingMode=o,f.type=n,f.format=l,f.label=u,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,m,_){return this._createTextureBase(e,t,i,s,r,n,o,(...x)=>this._prepareWebGLTexture(...x,c),(x,E,S,C,y,A)=>{const I=this._gl,R=S.width===x&&S.height===E;y._creationFlags=m??0;const N=this._getTexImageParametersForCreateTexture(y.format,y._useSRGBBuffer);if(R)return I.texImage2D(I.TEXTURE_2D,0,N.internalFormat,N.format,N.type,S),!1;const k=this._caps.maxTextureSize;if(S.width>k||S.height>k||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=x,this._workingCanvas.height=E,this._workingContext.drawImage(S,0,0,S.width,S.height,0,0,x,E),I.texImage2D(I.TEXTURE_2D,0,N.internalFormat,N.format,N.type,this._workingCanvas),y.width=x,y.height=E),!1;{const B=new $t(this,xt.Temp);this._bindTextureDirectly(I.TEXTURE_2D,B,!0),I.texImage2D(I.TEXTURE_2D,0,N.internalFormat,N.format,N.type,S),this._rescaleTexture(B,y,s,N.format,()=>{this._releaseTexture(B),this._bindTextureDirectly(I.TEXTURE_2D,y,!0),A()})}return!0},l,h,c,u,d,f,_)}_getTexImageParametersForCreateTexture(e,t){let i,s;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}createRawTexture(e,t,i,s,r,n,o,l=null,h=0,c=0,u=!1){throw ot("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,o,l=null){throw ot("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,o,l,h=null,c=0){throw ot("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,o,l,h=null,c=0){throw ot("Engine.RawTexture")}_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 s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const o=t.width||t,l=t.height||t,h=t.layers||0,c=t.depth||0;e.baseWidth=o,e.baseHeight=l,e.width=o,e.height=l,e.is2DArray=h>0,e.depth=h||c,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const u=this._gl,d=this._getTextureTarget(e),f=this._getSamplingParameters(e.samplingMode,!1);u.texParameteri(d,u.TEXTURE_MAG_FILTER,f.mag),u.texParameteri(d,u.TEXTURE_MIN_FILTER,f.min),u.texParameteri(d,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(d,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),this.webGLVersion>1&&(r===0?(u.texParameteri(d,u.TEXTURE_COMPARE_FUNC,515),u.texParameteri(d,u.TEXTURE_COMPARE_MODE,u.NONE)):(u.texParameteri(d,u.TEXTURE_COMPARE_FUNC,r),u.texParameteri(d,u.TEXTURE_COMPARE_MODE,u.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const l=this._gl;let h=l.TEXTURE_2D;if(e.isCube&&(h=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),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(h,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,l=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),c=r===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=o.TEXTURE_2D;e.isCube&&(u=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),m=n?e.width:Math.pow(2,Math.max(d-s,0)),_=n?e.height:Math.pow(2,Math.max(f-s,0));o.texImage2D(u,s,c,m,_,0,h,l,t)}updateTextureData(e,t,i,s,r,n,o=0,l=0,h=!1){const c=this._gl,u=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let f=c.TEXTURE_2D,m=c.TEXTURE_2D;e.isCube&&(m=c.TEXTURE_CUBE_MAP_POSITIVE_X+o,f=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(f,e,!0),c.texSubImage2D(m,l,i,s,r,n,d,u,t),h&&this._gl.generateMipmap(m),this._bindTextureDirectly(f,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),!i&&!s&&n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,l,h,c){const u=this.getCaps().maxTextureSize,d=Math.min(u,this.needPOTTextures?on(s.width,u):s.width),f=Math.min(u,this.needPOTTextures?on(s.height,u):s.height),m=this._gl;if(m){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(m.TEXTURE_2D,e,!0),this._unpackFlipY(r===void 0?!0:!!r),e.baseWidth=s.width,e.baseHeight=s.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:c??(t===".jpg"&&!e._useSRGBBuffer?4:5),!l(d,f,s,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,o,h)})&&this._prepareWebGLTextureContinuation(e,i,n,o,h)}}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let o=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(o=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,o,o,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const h=this._gl.createRenderbuffer();return this._updateRenderBuffer(h,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,l=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,n,t,i):h.renderbufferStorage(h.RENDERBUFFER,r,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,o,h.RENDERBUFFER,e),l&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){var i;this._deleteTexture((i=e._hardwareTexture)==null?void 0:i.underlyingResource),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&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(qU(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let s=0;s-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw U.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&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,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,s){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,s=!1,r=""){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 h=t.getInternalTexture();h&&(h._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const l=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(l,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const h=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=h,t.wrapV=h}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let r=0;r=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},Vs()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),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()),$U(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 s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===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,h=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,h),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),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,s,r=!0,n=!0){const o=r?4:3,l=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,l,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}generateMipMapsForCubemap(e,t){}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=He._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=He._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}}nt._TempClearColorUint32=new Uint32Array(4);nt._TempClearColorInt32=new Int32Array(4);nt.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"]}];nt.CollisionsEpsilon=.001;nt._ConcatenateShader=SI;nt._IsSupported=null;nt._HasMajorPerformanceCaveat=null;nt.CeilingPOT=cv;nt.FloorPOT=Ug;nt.NearestPOT=hv;nt.GetExponentOfTwo=on;nt.QueueNewFrame=LI;nt.prototype.createUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new wp(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};nt.prototype.createDynamicUniformBuffer=function(a,e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new wp(t);return this.bindUniformBuffer(i),a instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,a,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(a),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};nt.prototype.updateUniformBuffer=function(a,e,t,i){this.bindUniformBuffer(a),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)};nt.prototype.bindUniformBuffer=function(a){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,a?a.underlyingResource:null)};nt.prototype.bindUniformBufferBase=function(a,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,a?a.underlyingResource:null)};nt.prototype.bindUniformBlock=function(a,e,t){const i=a.program,s=this._gl.getUniformBlockIndex(i,e);s!==4294967295&&this._gl.uniformBlockBinding(i,s,t)};class ze{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"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 s=this._uniformLocationPointer-i;for(let r=0;r0){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 n=(4-t)*i;t=t*i+n}s=[];for(let r=0;r1&&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&&(ze._UpdatedUbosInFrame[this._name]||(ze._UpdatedUbosInFrame[this._name]=0),ze._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 s=this._uniformLocations[e];if(s===void 0){if(this._buffer){U.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let r=0;r0){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}U.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,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?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 P{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,s,r,n,o,l,h,c,u=!1,d=!1,f=1,m=!1){this._isDisposed=!1;let _=!1;if(this.engine=e,typeof s=="object"&&s!==null?(_=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,l=s.offset,h=s.size,c=s.type,u=s.normalized??!1,d=s.useBytes??!1,f=s.divisor??1,m=s.takeBufferOwnership??!1,this._label=s.label):_=!!s,t instanceof Gs?(this._buffer=t,this._ownsBuffer=m):(this._buffer=new Gs(e,t,_,n,r,o,d,f,this._label),this._ownsBuffer=!0),this.uniqueId=P._Counter++,this._kind=i,c===void 0){const E=this.getData();this.type=E?P.GetDataType(E):P.FLOAT}else this.type=c;const x=P.GetTypeByteLength(this.type);d?(this._size=h||(n?n/x:P.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*x,this.byteOffset=l||0):(this._size=h||n||P.DeduceStride(i),this.byteStride=n?n*x:this._buffer.byteStride||this._size*x,this.byteOffset=(l||0)*x),this.normalized=u,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?P.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/P.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/P.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*P.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){P.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case P.UVKind:case P.UV2Kind:case P.UV3Kind:case P.UV4Kind:case P.UV5Kind:case P.UV6Kind:return 2;case P.NormalKind:case P.PositionKind:return 3;case P.ColorKind:case P.ColorInstanceKind:case P.MatricesIndicesKind:case P.MatricesIndicesExtraKind:case P.MatricesWeightsKind:case P.MatricesWeightsExtraKind:case P.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?P.BYTE:e instanceof Uint8Array?P.UNSIGNED_BYTE:e instanceof Int16Array?P.SHORT:e instanceof Uint16Array?P.UNSIGNED_SHORT:e instanceof Int32Array?P.INT:e instanceof Uint32Array?P.UNSIGNED_INT:P.FLOAT}static GetTypeByteLength(e){switch(e){case P.BYTE:case P.UNSIGNED_BYTE:return 1;case P.SHORT:case P.UNSIGNED_SHORT:return 2;case P.INT:case P.UNSIGNED_INT:case P.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,l){if(e instanceof Array){let h=t/4;const c=i/4;for(let u=0;uu[f]=d),u}if(!(e instanceof Array||e instanceof Float32Array)||s!==0||e.length!==c)if(e instanceof Array){const u=s/4;return e.slice(u,u+c)}else{if(e instanceof ArrayBuffer)return new Float32Array(e,s,c);{let u=e.byteOffset+s;if(l){const f=new Float32Array(c),m=new Float32Array(e.buffer,u,c);return f.set(m),f}const d=u%4;return d&&(u=Math.max(0,u-d)),new Float32Array(e.buffer,u,c)}}return l?e.slice():e}}P._Counter=0;P.BYTE=5120;P.UNSIGNED_BYTE=5121;P.SHORT=5122;P.UNSIGNED_SHORT=5123;P.INT=5124;P.UNSIGNED_INT=5125;P.FLOAT=5126;P.PositionKind="position";P.NormalKind="normal";P.TangentKind="tangent";P.UVKind="uv";P.UV2Kind="uv2";P.UV3Kind="uv3";P.UV4Kind="uv4";P.UV5Kind="uv5";P.UV6Kind="uv6";P.ColorKind="color";P.ColorInstanceKind="instanceColor";P.MatricesIndicesKind="matricesIndices";P.MatricesWeightsKind="matricesWeights";P.MatricesIndicesExtraKind="matricesIndicesExtra";P.MatricesWeightsExtraKind="matricesWeightsExtra";class zs{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(P.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let s;const r=W.Vector3[0],n=W.Vector3[1],o=W.Vector3[2];if(t){const h=this.pickedMesh.getVerticesData(P.NormalKind);let c=i?T.FromArrayToRef(h,i[this.faceId*3]*3,r):r.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?T.FromArrayToRef(h,i[this.faceId*3+1]*3,n):n.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),d=i?T.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]);c=c.scale(this.bu),u=u.scale(this.bv),d=d.scale(1-this.bu-this.bv),s=new T(c.x+u.x+d.x,c.y+u.y+d.y,c.z+u.z+d.z)}else{const h=this.pickedMesh.getVerticesData(P.PositionKind),c=i?T.FromArrayToRef(h,i[this.faceId*3]*3,r):r.copyFromFloats(h[this.faceId*3*3],h[this.faceId*3*3+1],h[this.faceId*3*3+2]),u=i?T.FromArrayToRef(h,i[this.faceId*3+1]*3,n):n.copyFromFloats(h[(this.faceId*3+1)*3],h[(this.faceId*3+1)*3+1],h[(this.faceId*3+1)*3+2]),d=i?T.FromArrayToRef(h,i[this.faceId*3+2]*3,o):o.copyFromFloats(h[(this.faceId*3+2)*3],h[(this.faceId*3+2)*3+1],h[(this.faceId*3+2)*3+2]),f=c.subtract(u),m=d.subtract(u);s=T.Cross(f,m)}const l=(h,c)=>{let u=h.getWorldMatrix();h.nonUniformScaling&&(W.Matrix[0].copyFrom(u),u=W.Matrix[0],u.setTranslationFromFloats(0,0,0),u.invert(),u.transposeToRef(W.Matrix[1]),u=W.Matrix[1]),T.TransformNormalToRef(c,u,c)};if(e&&l(this.pickedMesh,s),this.ray){const h=W.Vector3[0].copyFrom(s);e||l(this.pickedMesh,h),T.Dot(h,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=P.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 s=ce.FromArray(i,t[this.faceId*3]*2),r=ce.FromArray(i,t[this.faceId*3+1]*2),n=ce.FromArray(i,t[this.faceId*3+2]*2);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new ce(s.x+r.x+n.x,s.y+r.y+n.y)}}class ug{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[P.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[P.PositionKind]=new P(this._scene.getEngine(),e,P.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[P.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!i||(t=t||i._postProcesses.filter(s=>s!=null),!t||t.length===0||!this._scene.postProcessesEnabled)?!1:(t[0].activate(i,e,t!=null),!0)}directRender(e,t=null,i=!1,s=0,r=0,n=!1){var l;const o=this._scene.getEngine();for(let h=0;hh!=null),s.length===0||!this._scene.postProcessesEnabled))return;const o=this._scene.getEngine();for(let h=0,c=s.length;ht._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(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.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=gt.LeftClick&&i<=gt.RightClick&&(l.type=s===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=lf.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case gt.MouseWheelX:o.deltaX=s;break;case gt.MouseWheelY:o.deltaY=s;break;case gt.MouseWheelZ:o.deltaZ=s;break}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),l=r.pollInput(e,t,gt.Horizontal),h=r.pollInput(e,t,gt.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,dg.DeltaHorizontal),o.movementY=r.pollInput(e,t,dg.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=at.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=t===1?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(at.Keyboard),s=i&&t.pollInput(at.Keyboard,0,18)===1,r=i&&t.pollInput(at.Keyboard,0,17)===1,n=i&&(t.pollInput(at.Keyboard,0,91)===1||t.pollInput(at.Keyboard,0,92)===1||t.pollInput(at.Keyboard,0,93)===1),o=i&&t.pollInput(at.Keyboard,0,16)===1;e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={};return t.preventDefault=()=>{},t.target=e,t}}class cV{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(s,r,n,o)=>{const l=Wh.CreateDeviceEvent(s,r,n,o,this);i(s,r,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===at.Mouse||e===at.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const UA=255,VA=Object.keys(gt).length/2;class uV{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Z.IsSafari(),this._usingMacOS=Qc()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=r=>{},this._keyboardUpEvent=r=>{},this._keyboardBlurEvent=r=>{},this._pointerMoveEvent=r=>{},this._pointerDownEvent=r=>{},this._pointerUpEvent=r=>{},this._pointerCancelEvent=r=>{},this._pointerWheelEvent=r=>{},this._pointerBlurEvent=r=>{},this._pointerMacOSChromeOutEvent=r=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Qc()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Qc()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=r=>{},this._gamepadDisconnectedEvent=r=>{},this._eventPrefix=Z.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,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 s=this._inputs[e][t];if(!s)throw`Unable to find device ${at[e]}`;e>=at.DualShock&&e<=at.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(r===void 0)throw`Unable to find input ${i} for device ${at[e]} in slot ${t}`;return i===gt.Move&&Z.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}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 s=+i,r=t[s];if(r)for(let n=0;n{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(at.Keyboard,0,UA));const t=this._inputs[at.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(at.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(at.Keyboard,0,UA));const t=this._inputs[at.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 s of this._metaKeys){const r=Wh.CreateDeviceEvent(at.Keyboard,0,s,0,this,this._elementToAttachTo);t[s]=0,this._onInputChanged(at.Keyboard,0,r)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(at.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[at.Keyboard][0];for(let t=0;t{const s=this._getPointerType(i);let r=s===at.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===at.Touch&&r===-1){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(s,r);else{Z.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]||this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const o=i;o.inputIndex=gt.Move,n[gt.Horizontal]=i.clientX,n[gt.Vertical]=i.clientY,s===at.Touch&&n[gt.LeftClick]===0&&(n[gt.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(s,r,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,n[i.button+2]=n[i.button+2]?0:1,this._onInputChanged(s,r,o))}},this._pointerDownEvent=i=>{const s=this._getPointerType(i);let r=s===at.Mouse?0:i.pointerId;if(s===at.Touch){const o=this._activeTouchIds.indexOf(-1);if(o>=0)r=o,this._activeTouchIds[o]=i.pointerId;else{Z.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[s]||(this._inputs[s]={}),this._inputs[s][r]?s===at.Touch&&this._onDeviceConnected(s,r):this._addPointerDevice(s,r,i.clientX,i.clientY);const n=this._inputs[s][r];if(n){const o=n[gt.Horizontal],l=n[gt.Vertical];if(s===at.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{}n[gt.Horizontal]=i.clientX,n[gt.Vertical]=i.clientY,n[i.button+2]=1;const h=i;h.inputIndex=i.button+2,this._onInputChanged(s,r,h),(o!==i.clientX||l!==i.clientY)&&(h.inputIndex=gt.Move,this._onInputChanged(s,r,h))}},this._pointerUpEvent=i=>{var o,l,h,c,u;const s=this._getPointerType(i),r=s===at.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(s===at.Touch){if(r===-1)return;this._activeTouchIds[r]=-1}const n=(o=this._inputs[s])==null?void 0:o[r];if(n&&n[i.button+2]!==0){const d=n[gt.Horizontal],f=n[gt.Vertical];n[gt.Horizontal]=i.clientX,n[gt.Vertical]=i.clientY,n[i.button+2]=0;const m=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(d!==i.clientX||f!==i.clientY)&&(m.inputIndex=gt.Move,this._onInputChanged(s,r,m)),m.inputIndex=i.button+2,s===at.Mouse&&this._mouseId>=0&&((h=(l=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(l,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(c=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(c,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(s,r,m),s===at.Touch&&this._onDeviceDisconnected(s,r)}},this._pointerCancelEvent=i=>{var s,r,n,o;if(i.pointerType==="mouse"){const l=this._inputs[at.Mouse][0];this._mouseId>=0&&((r=(s=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(s,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=gt.LeftClick;h<=gt.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Wh.CreateDeviceEvent(at.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(at.Mouse,0,c)}}else{const l=this._activeTouchIds.indexOf(i.pointerId);if(l===-1)return;(o=(n=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(n,i.pointerId)&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._inputs[at.Touch][l][gt.LeftClick]=0;const h=Wh.CreateDeviceEvent(at.Touch,l,gt.LeftClick,0,this,this._elementToAttachTo,i.pointerId);this._onInputChanged(at.Touch,l,h),this._activeTouchIds[l]=-1,this._onDeviceDisconnected(at.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,s,r,n,o;if(this.isDeviceAvailable(at.Mouse)){const l=this._inputs[at.Mouse][0];this._mouseId>=0&&((s=(i=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let h=gt.LeftClick;h<=gt.BrowserForward;h++)if(l[h]===1){l[h]=0;const c=Wh.CreateDeviceEvent(at.Mouse,0,h,0,this,this._elementToAttachTo);this._onInputChanged(at.Mouse,0,c)}}if(this.isDeviceAvailable(at.Touch)){const l=this._inputs[at.Touch];for(let h=0;h{const s=at.Mouse,r=0;this._inputs[s]||(this._inputs[s]=[]),this._inputs[s][r]||(this._pointerActive=!0,this._registerDevice(s,r,VA));const n=this._inputs[s][r];if(n){n[gt.MouseWheelX]=i.deltaX||0,n[gt.MouseWheelY]=i.deltaY||i.wheelDelta||0,n[gt.MouseWheelZ]=i.deltaZ||0;const o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),n[gt.MouseWheelX]!==0&&(o.inputIndex=gt.MouseWheelX,this._onInputChanged(s,r,o)),n[gt.MouseWheelY]!==0&&(o.inputIndex=gt.MouseWheelY,this._onInputChanged(s,r,o)),n[gt.MouseWheelZ]!==0&&(o.inputIndex=gt.MouseWheelZ,this._onInputChanged(s,r,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(at.Mouse)){const i=this._inputs[at.Mouse][0];i[gt.MouseWheelX]=0,i[gt.MouseWheelY]=0,i[gt.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 s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?at.DualSense:at.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?at.Xbox:e.indexOf("057e")!==-1?at.Switch:at.Generic}_getPointerType(e){let t=at.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=at.Touch),t}}class kA{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new K,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class dV{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=n=>{for(let o=0;o{const o=this._registeredManagers.indexOf(n);o>-1&&this._registeredManagers.splice(o,1)};const t=Object.keys(at).length/2;this._devices=new Array(t);const i=(n,o)=>{this._devices[n]||(this._devices[n]=new Array),this._devices[n][o]||(this._devices[n][o]=o);for(const l of this._registeredManagers){const h=new kA(this._deviceInputSystem,n,o);l._addDevice(h)}},s=(n,o)=>{var l;(l=this._devices[n])!=null&&l[o]&&delete this._devices[n][o];for(const h of this._registeredManagers)h._removeDevice(n,o)},r=(n,o,l)=>{if(l)for(const h of this._registeredManagers)h._onInputChanged(n,o,l)};typeof _native<"u"?this._deviceInputSystem=new cV(i,s,r):this._deviceInputSystem=new uV(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class fV{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(at).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new dV(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new K(i=>{for(const s of this._devices)if(s)for(const r of s)r&&this.onDeviceConnectedObservable.notifyObserver(i,r)}),this.onDeviceDisconnectedObservable=new K,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 s,r;const i=(s=this._devices[e])==null?void 0:s[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(r=this._devices[e])!=null&&r[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var s,r;(r=(s=this._devices[e])==null?void 0:s[t])==null||r.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case at.Keyboard:case at.Mouse:this._firstDevice[e]=0;break;case at.Touch:case at.DualSense:case at.DualShock:case at.Xbox:case at.Switch:case at.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t){for(let i=0;i=gt.MouseWheelX&&t.inputIndex<=gt.MouseWheelZ?Ke.POINTERWHEEL:Ke.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n));let o;e?(o=new wa(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new wa(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,L.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 s=this._scene,r=new hV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.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 r=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=gt.Move,!this._checkPrePointerObservable(e,i,Ke.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,Ke.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,ji.CreateNew(e.pickedMesh,t,e)),t.button){case 0:n.processTrigger(2,ji.CreateNew(e.pickedMesh,t,e));break;case 1:n.processTrigger(4,ji.CreateNew(e.pickedMesh,t,e));break;case 2:n.processTrigger(3,ji.CreateNew(e.pickedMesh,t,e));break}n.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&&n&&this._totalPointersPressed!==0&&Date.now()-this._startingPointerTime>ms.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,ji.CreateNew(o.pickedMesh,t)))},ms.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Ke.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new wa(r,t,e),this._setRayOnPointerInfo(e,t)):s=new wa(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=gt.Move;const r=new GA;i?r.doubleClick=!0:r.singleClick=!0,!this._checkPrePointerObservable(e,s,Ke.POINTERUP)&&this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const n=Ke.POINTERPICK,o=new wa(n,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(o,n)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,ji.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,ji.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,ji.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const r=this._pickedDownMesh._getActionManagerForTrigger(16);r&&r.processTrigger(16,ji.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new wa(Ke.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Ke.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ke.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=Ke.POINTERTAP:i.doubleClick&&(n=Ke.POINTERDOUBLETAP),n){const o=new wa(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(o,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new fV(n),this._initActionManager=o=>{if(!this._meshPickProceed){const l=r.skipPointerUpPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,h)=>{if((Date.now()-this._previousStartingPointerTime>ms.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){const c=this._delayedClicks[o].evt,u=Ke.POINTERTAP,d=new wa(u,c,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(u)&&r.onPointerObservable.notifyObservers(d,u),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,h,c)=>{var _,x;const u=new GA;this._currentPickResult=null;let d=null,f=o.hasSpecificMask(Ke.POINTERPICK)||l.hasSpecificMask(Ke.POINTERPICK)||o.hasSpecificMask(Ke.POINTERTAP)||l.hasSpecificMask(Ke.POINTERTAP)||o.hasSpecificMask(Ke.POINTERDOUBLETAP)||l.hasSpecificMask(Ke.POINTERDOUBLETAP);!f&&Wn&&(d=this._initActionManager(d,u),d&&(f=d.hasPickTriggers));let m=!1;if(f){const E=h.button;if(u.hasSwiped=this._isPointerSwiping(),!u.hasSwiped){let S=!ms.ExclusiveDoubleClickMode;if(S||(S=!o.hasSpecificMask(Ke.POINTERDOUBLETAP)&&!l.hasSpecificMask(Ke.POINTERDOUBLETAP),S&&!Wn.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(S=!d.hasSpecificTrigger(6)))),S)(Date.now()-this._previousStartingPointerTime>ms.DoubleClickDelay||E!==this._previousButtonPressed)&&(u.singleClick=!0,c(u,this._currentPickResult),m=!0);else{const y={evt:h,clickInfo:u,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,E,u,c),ms.DoubleClickDelay)};this._delayedClicks[E]=y}let C=o.hasSpecificMask(Ke.POINTERDOUBLETAP)||l.hasSpecificMask(Ke.POINTERDOUBLETAP);!C&&Wn.HasSpecificTrigger(6)&&(d=this._initActionManager(d,u),d&&(C=d.hasSpecificTrigger(6))),C&&(E===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>ms.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>ms.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=gt.MouseWheelX&&o.inputIndex<=gt.MouseWheelZ?Ke.POINTERWHEEL:Ke.POINTERMOVE)||!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking){this._processPointerMove(new zs,o);return}r.pointerMovePredicate||(r.pointerMovePredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(h.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||h._getActionManagerForTrigger()!==null)&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&h.layerMask)!==0));const l=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var h;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,ms.ExclusiveDoubleClickMode){for(let c=0;cc.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),this._pickedDownMesh=null;let l;r.skipPointerDownPicking||r._registeredActions===0&&!this._checkForPicking()&&!r.onPointerDown?l=new zs:l=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(l,o)},this._onPointerUp=o=>{this._totalPointersPressed!==0&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),r.preventDefaultOnPointerUp&&s&&(o.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,o,(l,h)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!l.ignore)){if(this._checkPrePointerObservable(null,o,Ke.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}l.hasSwiped||(l.singleClick&&r.onPrePointerObservable.hasSpecificMask(Ke.POINTERTAP)&&this._checkPrePointerObservable(null,o,Ke.POINTERTAP)&&(this._skipPointerTap=!0),l.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Ke.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,Ke.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),!(!r.cameraToUseForPointers&&!r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(!r.cameraToUseForPointers||(r.cameraToUseForPointers.layerMask&c.layerMask)!==0)),!this._meshPickProceed&&(Wn&&Wn.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,l),h||(h=this._currentPickResult),this._processPointerUp(h,o,l),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{const l=mh.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const h=new DA(l,o);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new zE(l,o);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(14,ji.CreateNewFromScene(r,o))},this._onKeyUp=o=>{const l=mh.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const h=new DA(l,o);if(r.onPreKeyboardObservable.notifyObservers(h,l),h.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const h=new zE(l,o);r.onKeyboardObservable.notifyObservers(h,l)}r.actionManager&&r.actionManager.processTrigger(15,ji.CreateNewFromScene(r,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===at.Mouse?o.onInputChangedObservable.add(l=>{l.inputIndex===gt.LeftClick||l.inputIndex===gt.MiddleClick||l.inputIndex===gt.RightClick||l.inputIndex===gt.BrowserBack||l.inputIndex===gt.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===gt.Move?this._onPointerMove(l):(l.inputIndex===gt.MouseWheelX||l.inputIndex===gt.MouseWheelY||l.inputIndex===gt.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===at.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===gt.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===gt.Move&&this._onPointerMove(l)}):o.deviceType===at.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,s){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,ji.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,ji.CreateNew(e,s,{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]}}ms.DragMovementThreshold=10;ms.LongPressDelay=500;ms.DoubleClickDelay=300;ms.ExclusiveDoubleClickMode=!1;class Xn{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){Xn.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Xn.Enabled&&(this._startMonitoringTime=ks.Now)}endMonitoring(e=!0){if(!Xn.Enabled)return;e&&this.fetchNewFrame();const t=ks.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=ks.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Xn.Enabled=!0;class nn{constructor(e,t,i,s){this.normal=new T(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new nn(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=nn._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,l=s*i[0]+r*i[1]+n*i[2]+o*i[3],h=s*i[4]+r*i[5]+n*i[6]+o*i[7],c=s*i[8]+r*i[9]+n*i[10]+o*i[11],u=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new nn(l,h,c,u)}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 s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=r*h-n*l,u=n*o-s*h,d=s*l-r*o,f=Math.sqrt(c*c+u*u+d*d);let m;return f!==0?m=1/f:m=0,this.normal.x=c*m,this.normal.y=u*m,this.normal.z=d*m,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return T.Dot(this.normal,e)<=t}signedDistanceTo(e){return T.Dot(e,this.normal)+this.d}static FromArray(e){return new nn(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new nn(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new nn(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 s=-(t.x*e.x+t.y*e.y+t.z*e.z);return T.Dot(i,t)+s}}nn._TmpMatrix=L.Identity();class oa{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new nn(0,0,0,0));return oa.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){oa.GetNearPlaneToRef(e,t[0]),oa.GetFarPlaneToRef(e,t[1]),oa.GetLeftPlaneToRef(e,t[2]),oa.GetRightPlaneToRef(e,t[3]),oa.GetTopPlaneToRef(e,t[4]),oa.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 a_{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}a_._UniqueIdCounter=1;class hi{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}hi.FALLOFF_DEFAULT=0;hi.FALLOFF_PHYSICAL=1;hi.FALLOFF_GLTF=2;hi.FALLOFF_STANDARD=3;hi.LIGHTMAP_DEFAULT=0;hi.LIGHTMAP_SPECULAR=1;hi.LIGHTMAP_SHADOWSONLY=2;hi.INTENSITYMODE_AUTOMATIC=0;hi.INTENSITYMODE_LUMINOUSPOWER=1;hi.INTENSITYMODE_LUMINOUSINTENSITY=2;hi.INTENSITYMODE_ILLUMINANCE=3;hi.INTENSITYMODE_LUMINANCE=4;hi.LIGHTTYPEID_POINTLIGHT=0;hi.LIGHTTYPEID_DIRECTIONALLIGHT=1;hi.LIGHTTYPEID_SPOTLIGHT=2;hi.LIGHTTYPEID_HEMISPHERICLIGHT=3;class pV{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var wo;(function(a){a[a.BackwardCompatible=0]="BackwardCompatible",a[a.Intermediate=1]="Intermediate",a[a.Aggressive=2]="Aggressive"})(wo||(wo={}));class Ue extends xs{static DefaultMaterialFactory(e){throw ot("StandardMaterial")}static CollisionCoordinatorFactory(){throw ot("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 wo.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case wo.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case wo.Aggressive: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 ms.DragMovementThreshold}static set DragMovementThreshold(e){ms.DragMovementThreshold=e}static get LongPressDelay(){return ms.LongPressDelay}static set LongPressDelay(e){ms.LongPressDelay=e}static get DoubleClickDelay(){return ms.DoubleClickDelay}static set DoubleClickDelay(e){ms.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return ms.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){ms.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(this._mirroredCameraPosition!=null);return W.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,W.Vector4[0].x,W.Vector4[0].y,W.Vector4[0].z):e.setVector4(t,W.Vector4[0])),W.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=oI(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=Ue.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=Ue.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 ms(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Oe(.2,.2,.3,1),this.ambientColor=new re(0,0,0),this.environmentIntensity=1,this._performancePriority=wo.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new K,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 K,this._onDisposeObserver=null,this.onBeforeRenderObservable=new K,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new K,this.onAfterRenderCameraObservable=new K,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new K,this.onAfterAnimationsObservable=new K,this.onBeforeDrawPhaseObservable=new K,this.onAfterDrawPhaseObservable=new K,this.onReadyObservable=new K,this.onBeforeCameraRenderObservable=new K,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new K,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new K,this.onAfterActiveMeshesEvaluationObservable=new K,this.onBeforeParticlesRenderingObservable=new K,this.onAfterParticlesRenderingObservable=new K,this.onDataLoadedObservable=new K,this.onNewCameraAddedObservable=new K,this.onCameraRemovedObservable=new K,this.onNewLightAddedObservable=new K,this.onLightRemovedObservable=new K,this.onNewGeometryAddedObservable=new K,this.onGeometryRemovedObservable=new K,this.onNewTransformNodeAddedObservable=new K,this.onTransformNodeRemovedObservable=new K,this.onNewMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onNewSkeletonAddedObservable=new K,this.onSkeletonRemovedObservable=new K,this.onNewMaterialAddedObservable=new K,this.onNewMultiMaterialAddedObservable=new K,this.onMaterialRemovedObservable=new K,this.onMultiMaterialRemovedObservable=new K,this.onNewTextureAddedObservable=new K,this.onTextureRemovedObservable=new K,this.onBeforeRenderTargetsRenderObservable=new K,this.onAfterRenderTargetsRenderObservable=new K,this.onBeforeStepObservable=new K,this.onAfterStepObservable=new K,this.onActiveCameraChanged=new K,this.onActiveCamerasChanged=new K,this.onBeforeRenderingGroupObservable=new K,this.onAfterRenderingGroupObservable=new K,this.onMeshImportedObservable=new K,this.onAnimationFileImportedObservable=new K,this._registeredForLateAnimationBindings=new Yl(256),this._pointerPickingConfiguration=new pV,this.onPrePointerObservable=new K,this.onPointerObservable=new K,this.onPreKeyboardObservable=new K,this.onKeyboardObservable=new K,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Ue.FOGMODE_NONE,this.fogColor=new re(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new T(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Yl(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Xn,this._activeIndices=new Xn,this._activeParticles=new Xn,this._activeBones=new Xn,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 Ps(256),this._processedMaterials=new Ps(256),this._renderTargets=new Yl(256),this._materialsRenderTargets=new Yl(256),this._activeParticleSystems=new Ps(256),this._activeSkeletons=new Yl(32),this._softwareSkinnedMeshes=new Yl(32),this._activeAnimatables=new Array,this._transformMatrix=L.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=fs.Create(),this._beforeClearStage=fs.Create(),this._beforeRenderTargetClearStage=fs.Create(),this._gatherRenderTargetsStage=fs.Create(),this._gatherActiveCameraRenderTargetsStage=fs.Create(),this._isReadyForMeshStage=fs.Create(),this._beforeEvaluateActiveMeshStage=fs.Create(),this._evaluateSubMeshStage=fs.Create(),this._preActiveMeshStage=fs.Create(),this._cameraDrawRenderTargetStage=fs.Create(),this._beforeCameraDrawStage=fs.Create(),this._beforeRenderTargetDrawStage=fs.Create(),this._beforeRenderingGroupDrawStage=fs.Create(),this._beforeRenderingMeshStage=fs.Create(),this._afterRenderingMeshStage=fs.Create(),this._afterRenderingGroupDrawStage=fs.Create(),this._afterCameraDrawStage=fs.Create(),this._afterCameraPostProcessStage=fs.Create(),this._afterRenderTargetDrawStage=fs.Create(),this._afterRenderTargetPostProcessStage=fs.Create(),this._afterRenderStage=fs.Create(),this._pointerMoveStage=fs.Create(),this._pointerDownStage=fs.Create(),this._pointerUpStage=fs.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||We.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(We._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new mr(this),ug&&(this.postProcessManager=new ug(this)),Vs()&&this.attachControl(),this._createUbo(),Mt&&(this._imageProcessingConfiguration=new Mt),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 n,o;if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=((n=this.activeCamera)==null?void 0:n.renderPassId)??s;let r=!0;for(this._pendingData.length>0&&(r=!1),(o=this.prePassRenderer)==null||o.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const u of this._isReadyForMeshStage)u.action(l,h)||(r=!1);if(!e)continue;const c=l.material||this.defaultMaterial;if(c)if(c._storeEffectOnSubMeshes)for(const u of l.subMeshes){const d=u.getMaterial();d&&d.hasRenderTargetTextures&&d.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(d)===-1&&(this._processedMaterials.push(d),this._materialsRenderTargets.concatWithNoDuplicate(d.getRenderTargetTextures()))}else c.hasRenderTargetTextures&&c.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(c)===-1&&(this._processedMaterials.push(c),this._materialsRenderTargets.concatWithNoDuplicate(c.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const l of this.activeCameras)l.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const l of this.particleSystems)l.isReady()||(r=!1);if(this.layers)for(const l of this.layers)l.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}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=ks.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){!i&&!s&&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?oa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=oa.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):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 ze(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 a_.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[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(s=>{this.removeMesh(s)}),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 s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||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=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let n=0;ne.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 s=this._activeMeshes.length;for(let r=0;r0&&r.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(r),this.activeCamera._activeMeshes.push(r),n!==r&&n._activate(this._renderId,!1);for(const o of this._preActiveMeshStage)o.action(r);r._activate(this._renderId,!1)&&(r.isAnInstance?r._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=r):n._internalAbstractMeshDataInfo._onlyForInstances=!1,n._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(r,n)),r._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let s=0;s0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||r===1;for(let n=0;n0&&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 r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Z.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let o=0;o0),this._renderId++}for(const o of this._cameraDrawRenderTargetStage)r=o.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=((n=e.outputRenderTarget)==null?void 0:n.renderPassId)??e.renderPassId??0,r&&!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),s.snapshotRendering&&s.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&&(s.trigger===13&&s._executeCurrent(ji.CreateNew(t,void 0,n)),(!t.actionManager.hasSpecificTrigger(13,h=>{const c=h.mesh?h.mesh:h;return n===c})||s.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Ue.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Ue.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let o=0;o0),this._intermediateRendering=!0;for(let o=0;o0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=(s==null?void 0:s.renderPassId)??0,this.activeCamera=s,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{r.onAnimationEndObservable.clear(),r.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 r of e)r.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(r){U.Error("An error occurred while calling onDisposeObservable!",r)}if(this.detachControl(),this._engine.getInputElement())for(let r=0;rr.dispose(!0)),this._disposeList(this.transformNodes,r=>r.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 s=this._engine.scenes.indexOf(this);s>-1&&this._engine.scenes.splice(s,1),We._LastCreatedScene===this&&(this._engine.scenes.length>0?We._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:We._LastCreatedScene=null),s=this._engine._virtualScenes.indexOf(this),s>-1&&this._engine._virtualScenes.splice(s,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??(s=>s.dispose());for(const s of i)t(s);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(s=>{if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)return;const r=s.getBoundingInfo(),n=r.boundingBox.minimumWorld,o=r.boundingBox.maximumWorld;T.CheckExtends(n,t,i),T.CheckExtends(o,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw ot("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw ot("Ray")}createPickingRayInCameraSpace(e,t,i){throw ot("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw ot("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=ot("Ray",!0);return o&&U.Warn(o),new zs}pickWithBoundingInfo(e,t,i,s,r){const n=ot("Ray",!0);return n&&U.Warn(n),new zs}pickWithRay(e,t,i,s){throw ot("Ray")}multiPick(e,t,i,s,r){throw ot("Ray")}multiPickWithRay(e,t,i){throw ot("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 s=[];for(const r in e){const n=e[r];Gt&&Gt.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}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,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}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,s,r,n,o){const l=_h(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_loadFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._loadFile(e,l=>{n(l)},t,i,s,(l,h)=>{o(h)},r)})}_requestFile(e,t,i,s,r,n,o){const l=lv(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(l),l.onCompleteObservable.add(h=>{this._activeRequests.splice(this._activeRequests.indexOf(h),1)}),l}_requestFileAsync(e,t,i,s,r){return new Promise((n,o)=>{this._requestFile(e,l=>{n(l)},t,i,s,l=>{o(l)},r)})}_readFile(e,t,i,s,r){const n=Dp(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),n}_readFileAsync(e,t,i){return new Promise((s,r)=>{this._readFile(e,n=>{s(n)},t,i,n=>{r(n)})})}getPerfCollector(){throw ot("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)}}Ue.FOGMODE_NONE=0;Ue.FOGMODE_EXP=1;Ue.FOGMODE_EXP2=2;Ue.FOGMODE_LINEAR=3;Ue.MinDeltaTime=1;Ue.MaxDeltaTime=1e3;var Wt;(function(a){a[a.LOCAL=0]="LOCAL",a[a.WORLD=1]="WORLD",a[a.BONE=2]="BONE"})(Wt||(Wt={}));class Vr{}Vr.X=new T(1,0,0);Vr.Y=new T(0,1,0);Vr.Z=new T(0,0,1);var Yh;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(Yh||(Yh={}));class mi extends Qt{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,s=null,r=null,n=null,o=null){super(e,t.getScene()),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=(s==null?void 0:s.clone())??L.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new L,this._absoluteBindMatrix=new L,this._absoluteInverseBindMatrix=new L,this._finalMatrix=new L,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=W.Vector3[0],t=W.Quaternion[0],i=W.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??ae.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=T.Zero(),this._localRotation=ae.Zero(),this._localPosition=T.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,L.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(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let n=r.length-1;n>=0;n--){const o=r[n];e&&o.animation.name!=e||t&&!t(o.target)||(o.dispose(),r.splice(n,1))}r.length==0&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);const r=this._runtimeAnimations;for(let n=0;n{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 s;for(s=0;s0)return;this._animationTimeLast=e}this.deltaTime=a!==void 0?a: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 s=0;sa.playOrder-e.playOrder)};Ue.prototype.beginWeightedAnimation=function(a,e,t,i=1,s,r=1,n,o,l,h,c=!1){const u=this.beginAnimation(a,e,t,s,r,n,o,!1,l,h,c);return u.weight=i,u};Ue.prototype.beginAnimation=function(a,e,t,i,s=1,r,n,o=!0,l,h,c=!1){e>t&&s>0&&(s*=-1),o&&this.stopAnimation(a,void 0,l),n||(n=new $I(this,a,e,t,i,s,r,void 0,h,c));const u=l?l(a):!0;if(a.animations&&u&&n.appendAnimations(a,a.animations),a.getAnimatables){const d=a.getAnimatables();for(let f=0;fi&&r>0)r*=-1;else if(i>t&&r<0){const c=i;i=t,t=c}return new $I(this,a,t,i,s,r,n,e,o,l)};Ue.prototype.beginDirectHierarchyAnimation=function(a,e,t,i,s,r,n,o,l,h=!1){const c=a.getDescendants(e),u=[];u.push(this.beginDirectAnimation(a,t,i,s,r,n,o,l,h));for(const d of c)u.push(this.beginDirectAnimation(d,t,i,s,r,n,o,l,h));return u};Ue.prototype.getAnimatableByTarget=function(a){for(let e=0;e0?l:-l,s),f.scaleAndAddToRef(l,t)}s.normalize()}for(let u=0;u0)s.copyFrom(i);else if(a.animations.length===1){if(ae.SlerpToRef(i,t.currentValue,Math.min(1,a.totalWeight),s),a.totalAdditiveWeight===0)return s}else if(a.animations.length>1){let r=1,n,o;if(a.totalWeight<1){const h=1-a.totalWeight;n=[],o=[],n.push(i),o.push(h)}else{if(a.animations.length===2&&(ae.SlerpToRef(a.animations[0].currentValue,a.animations[1].currentValue,a.animations[1].weight/a.totalWeight,e),a.totalAdditiveWeight===0))return e;n=[],o=[],r=a.totalWeight}for(let h=0;h=n&&x.frame<=o&&(i?(S=x.value.clone(),d?(E=S.getTranslation(),S.setTranslation(E.scaleInPlace(f))):m&&s?(E=S.getTranslation(),S.setTranslation(E.multiplyInPlace(s))):S=x.value):S=x.value,_.push({frame:x.frame+t,value:S}));return this.animations[0].createRange(e,n+t,o+t),!0};var cu;(function(a){a[a.CW=0]="CW",a[a.CCW=1]="CCW"})(cu||(cu={}));class Mo{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),s=Math.atan2(i.y,i.x);return new Mo(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new Mo(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=Ne.Clamp(s,-1,1);const r=Math.acos(s);return new Mo(r)}static FromRadians(e){return new Mo(e)}static FromDegrees(e){return new Mo(e*Math.PI/180)}}class _V{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-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 ce((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Mo.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=Mo.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=Mo.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?cu.CW:cu.CCW,this.angle=Mo.FromDegrees(this.orientation===cu.CW?l-c:c-l)}}class Vg{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new ce(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new ce(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new ce(e,t),l=new ce(i,s),h=new _V(n,o,l);let c=h.angle.radians()/r;h.orientation===cu.CW&&(c*=-1);let u=h.startAngle.radians()+c;for(let d=0;d(1-l)*(1-l)*h+2*l*(1-l)*c+l*l*u,o=this._points[this._points.length-1];for(let l=0;l<=r;l++){const h=l/r,c=n(h,o.x,e,i),u=n(h,o.y,t,s);this.addLineTo(c,u)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const l=(c,u,d,f,m)=>(1-c)*(1-c)*(1-c)*u+3*c*(1-c)*(1-c)*d+3*c*c*(1-c)*f+c*c*c*m,h=this._points[this._points.length-1];for(let c=0;c<=o;c++){const u=c/o,d=l(u,h.x,e,i,r),f=l(u,h.y,t,s,n);this.addLineTo(d,f)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(h<0&&(n=this._points[r],l=-l,o=this._points[s],h=-h),e.yo.y)continue;if(e.y===n.y&&e.x===n.x)return!0;{const c=h*(e.x-n.x)-l*(e.y-n.y);if(c===0)return!0;if(c<0)continue;t=!t}}else{if(e.y!==n.y)continue;if(o.x<=e.x&&e.x<=n.x||n.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,s=0;s1)return ce.Zero();const t=e*this.length();let i=0;for(let s=0;s=i&&t<=h){const c=l.normalize(),u=t-i;return new ce(n.x+c.x*u,n.y+c.y*u)}i=h}return ce.Zero()}static StartingAt(e,t){return new Vg(e,t)}}class Fp{constructor(e,t=null,i,s=!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:T.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:L.Identity()};for(let r=0;rt){const h=e;e=t,t=h}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(r++,l.push(s)),l.push(...i.slice(r,o)),(t!==1||e===1)&&l.push(n),new Fp(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let s=0;st+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(s===0&&(s=1),t==null){let r;Ne.WithinEpsilon(Math.abs(e.y)/s,1,At)?Ne.WithinEpsilon(Math.abs(e.x)/s,1,At)?Ne.WithinEpsilon(Math.abs(e.z)/s,1,At)?r=T.Zero():r=new T(0,0,1):r=new T(1,0,0):r=new T(0,-1,0),i=T.Cross(e,r)}else i=T.Cross(e,t),T.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 s=i[0],r,n=0;const o=e*this.length();for(let l=1;lo){const u=(n-o)/h,d=s.subtract(r),f=r.add(d.scaleInPlace(u));return this._setPointAtData(e,1-u,f,l-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=L.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),h=ae.RotationQuaternionFromAxis(s,r,i),c=ae.RotationQuaternionFromAxis(o,l,n);ae.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class yo{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(o,l,h,c)=>(1-o)*(1-o)*l+2*o*(1-o)*h+o*o*c;for(let o=0;o<=s;o++)r.push(new T(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new yo(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(l,h,c,u,d)=>(1-l)*(1-l)*(1-l)*h+3*l*(1-l)*(1-l)*c+3*l*l*(1-l)*u+l*l*l*d;for(let l=0;l<=r;l++)n.push(new T(o(l/r,e.x,t.x,i.x,s.x),o(l/r,e.y,t.y,i.y,s.y),o(l/r,e.z,t.z,i.z,s.z)));return new yo(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let l=0;l<=r;l++)n.push(T.Hermite(e,t,i,s,l*o));return new yo(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=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}}kr.EASINGMODE_EASEIN=0;kr.EASINGMODE_EASEOUT=1;kr.EASINGMODE_EASEINOUT=2;class mV extends kr{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class gV extends kr{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 xV extends kr{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 TV extends kr{easeInCore(e){return e*e}}class KI extends kr{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class uv{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new uv(this.frame,this.action,this.onlyOnce)}}class EV{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class Ao{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;tn&&(n=l.to);const o=new Ao(e[0].name+"_merged",e[0]._scene,s);for(const l of e){i&&l.normalize(r,n);for(const h of l.targetedAnimations)o.addTargetedAnimation(h.animation,h.target);t&&l.dispose()}return o}constructor(e,t=null,i=-1,s=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._parentContainer=null,this.onAnimationEndObservable=new K,this.onAnimationLoopObservable=new K,this.onAnimationGroupLoopObservable=new K,this.onAnimationGroupEndObservable=new K,this.onAnimationGroupPauseObservable=new K,this.onAnimationGroupPlayObservable=new K,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||We.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new EV;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[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:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.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,s,r){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,n),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[t++]=s)}return this._scene._activeAnimatables.length=t,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){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),this._animatables.length===0&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new Ao(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const r of this._targetedAnimations)s.addTargetedAnimation(i?r.animation.clone():r.animation,t?t(r.target):r.target);return s}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;t_[0].frame&&(h=_[0].frame),c<_[_.length-1].frame&&(c=_[_.length-1].frame)}o._from=h,o._to=c}return o}static ClipKeys(e,t,i,s,r){const n=e.clone(s||e.name);return Ao.ClipKeysInPlace(n,t,i,r)}static ClipKeysInPlace(e,t,i,s){return Ao.ClipInPlace(e,t,i,s,!1)}static ClipFrames(e,t,i,s,r){const n=e.clone(s||e.name);return Ao.ClipFramesInPlace(n,t,i,r)}static ClipFramesInPlace(e,t,i,s){return Ao.ClipInPlace(e,t,i,s,!0)}static ClipInPlace(e,t,i,s,r=!1){let n=Number.MAX_VALUE,o=-Number.MAX_VALUE;const l=e.targetedAnimations;for(let h=0;h=t&&_<=i||r&&x.frame>=t&&x.frame<=i){const E={frame:x.frame,value:x.value.clone?x.value.clone():x.value,inTangent:x.inTangent,outTangent:x.outTangent,interpolation:x.interpolation,lockedTangent:x.lockedTangent};m===Number.MAX_VALUE&&(m=E.frame),E.frame-=m,f.push(E)}}if(f.length===0){l.splice(h,1),h--;continue}n>f[0].frame&&(n=f[0].frame),o{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function SV(a=25){let e;return(t,i,s)=>{const r=performance.now();e===void 0||r-e>a?(e=r,setTimeout(()=>{fg(t,i,s)},0)):fg(t,i,s)}}function jI(a,e,t,i,s){const r=()=>{let n;const o=l=>{l.done?t(l.value):n===void 0?n=!0:r()};do n=void 0,!s||!s.aborted?e(a,o,i):i(new Error("Aborted")),n===void 0&&(n=!1);while(n)};r()}function dv(a,e){let t;return jI(a,fg,i=>t=i,i=>{throw i},e),t}function qI(a,e,t){return new Promise((i,s)=>{jI(a,e,i,s,t)})}function vV(a,e){return(...t)=>dv(a(...t),e)}class da{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new da(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 da(this.x,this.y,this.width,this.height)}}class Ve extends Qt{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===Ve.PERSPECTIVE_CAMERA)this.fovMode===Ve.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,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}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,s=!0){super(e,i),this._position=T.Zero(),this._upVector=T.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=Ve.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new da(0,0,1,1),this.layerMask=268435455,this.fovMode=Ve.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Ve.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new K,this.onProjectionMatrixChangedObservable=new K,this.onAfterCheckInputsObservable=new K,this.onRestoreStateObservable=new K,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new L,this._postProcesses=new Array,this._activeMeshes=new Ps(256),this._globalPosition=T.Zero(),this._computedViewMatrix=L.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=L.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=ae.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!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}_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?(U.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 L.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 r,n,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(),s=t.useReverseDepthBuffer;if(this.mode===Ve.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=L.PerspectiveFovRHToRef:l=L.PerspectiveFovLHToRef,l(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Ve.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const l=t.getRenderWidth()/2,h=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?L.ObliqueOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):L.OrthoOffCenterRHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?L.ObliqueOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):L.OrthoOffCenterLHToRef(this.orthoLeft??-l,this.orthoRight??l,this.orthoBottom??-h,this.orthoTop??h,s?this.maxZ:this.minZ,s?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=(r=this.oblique)==null?void 0:r.angle,this._cache.obliqueLength=(n=this.oblique)==null?void 0:n.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?T.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?oa.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=oa.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(s=>{s._updateFrustumPlanes(),i=i||e.isInFrustum(s._frustumPlanes)}),i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw ot("Ray")}getForwardRayToRef(e,t=100,i,s){throw ot("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 s=this._rigCameras.pop();s&&s.dispose()}if(this._parentContainer){const s=this._parentContainer.cameras.indexOf(this);s>-1&&this._parentContainer.cameras.splice(s,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==Ve.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let s=this._postProcesses.length;for(;--s>=0;){const r=this._postProcesses[s];r&&r.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=Z.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Ve.RIG_MODE_NONE){const i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);const s=this.createRigCamera(this.name+"_R",1);s&&(s._isRightCamera=!0),i&&s&&(this._rigCameras.push(i),this._rigCameras.push(s))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return L.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=Z.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eVe._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=Ve.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Pe.Parse(s,e,t);if(e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=T.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(T.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(T.FromArray(e.target)),e.cameraRigMode){const n=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,n)}if(e.animations){for(let n=0;n{throw ot("UniversalCamera")};Ve.PERSPECTIVE_CAMERA=0;Ve.ORTHOGRAPHIC_CAMERA=1;Ve.FOVMODE_VERTICAL_FIXED=0;Ve.FOVMODE_HORIZONTAL_FIXED=1;Ve.RIG_MODE_NONE=0;Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;Ve.RIG_MODE_STEREOSCOPIC_INTERLACED=14;Ve.RIG_MODE_VR=20;Ve.RIG_MODE_CUSTOM=22;Ve.ForceAttachControlToAlwaysPreventDefault=!1;v([Sr("position")],Ve.prototype,"_position",void 0);v([Sr("upVector")],Ve.prototype,"_upVector",void 0);v([O()],Ve.prototype,"orthoLeft",null);v([O()],Ve.prototype,"orthoRight",null);v([O()],Ve.prototype,"orthoBottom",null);v([O()],Ve.prototype,"orthoTop",null);v([O()],Ve.prototype,"fov",void 0);v([O()],Ve.prototype,"projectionPlaneTilt",void 0);v([O()],Ve.prototype,"minZ",void 0);v([O()],Ve.prototype,"maxZ",void 0);v([O()],Ve.prototype,"inertia",void 0);v([O()],Ve.prototype,"mode",null);v([O()],Ve.prototype,"layerMask",void 0);v([O()],Ve.prototype,"fovMode",void 0);v([O()],Ve.prototype,"cameraRigMode",void 0);v([O()],Ve.prototype,"interaxialDistance",void 0);v([O()],Ve.prototype,"isStereoscopicSideBySide",void 0);class WE{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class to{constructor(e,t,i){this.vectors=Os.BuildArray(8,T.Zero),this.center=T.Zero(),this.centerWorld=T.Zero(),this.extendSize=T.Zero(),this.extendSizeWorld=T.Zero(),this.directions=Os.BuildArray(3,T.Zero),this.vectorsWorld=Os.BuildArray(8,T.Zero),this.minimumWorld=T.Zero(),this.maximumWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,l,h),c[0].copyFromFloats(s,r,n),c[1].copyFromFloats(o,l,h),c[2].copyFromFloats(o,r,n),c[3].copyFromFloats(s,l,n),c[4].copyFromFloats(s,r,h),c[5].copyFromFloats(o,l,n),c[6].copyFromFloats(s,l,h),c[7].copyFromFloats(o,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||L.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=to._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(r*.5),o=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)r[o].copyFrom(n[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=r[o];T.TransformCoordinatesToRef(n[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}T.FromArrayToRef(e.m,0,s[0]),T.FromArrayToRef(e.m,4,s[1]),T.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return to.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return to.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,l=i.y,h=i.z,c=e.x,u=e.y,d=e.z,f=-At;return!(o-cc-s||l-uu-r||h-dd-n)}intersectsSphere(e){return to.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,l=s.x,h=s.y,c=s.z,u=e.x,d=e.y,f=e.z,m=t.x,_=t.y,x=t.z;return!(lm||h_||cx)}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,s){const r=to._TmpVector3[0];return T.ClampToRef(i,e,t,r),T.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let r=0;r<8;++r)if(s.dotCoordinate(e[r])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let n=0;n<8;++n)if(r.dotCoordinate(e[n])>=0){s=!1;break}if(s)return!1}return!0}}to._TmpVector3=Os.BuildArray(3,T.Zero);class gl{constructor(e,t,i){this.center=T.Zero(),this.centerWorld=T.Zero(),this.minimum=T.Zero(),this.maximum=T.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=T.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=s*.5,this._update(i||L.IdentityReadOnly)}scale(e){const t=this.radius*e,i=gl._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{T.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=gl._TmpVector3[0];T.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 s=0;s<6;s++)if(e[s].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=T.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const i=T.Dot(e.centerWorld,a),s=Math.abs(T.Dot(e.directions[0],a))*e.extendSize.x,r=Math.abs(T.Dot(e.directions[1],a))*e.extendSize.y,n=Math.abs(T.Dot(e.directions[2],a))*e.extendSize.z,o=s+r+n;t.min=i-o,t.max=i+o},_n=(a,e,t)=>(WA(a,e,oE),WA(a,t,lE),!(oE.min>lE.max||lE.min>oE.max));class En{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new to(e,t,i),this.boundingSphere=new gl(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=En._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=En._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=T.Minimize(this.minimum,e),i=T.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=W.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=W.Vector3[0];return T.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),T.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,En._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(!gl.Intersects(this.boundingSphere,e.boundingSphere)||!to.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!(!_n(i.directions[0],i,s)||!_n(i.directions[1],i,s)||!_n(i.directions[2],i,s)||!_n(s.directions[0],i,s)||!_n(s.directions[1],i,s)||!_n(s.directions[2],i,s)||!_n(T.Cross(i.directions[0],s.directions[0]),i,s)||!_n(T.Cross(i.directions[0],s.directions[1]),i,s)||!_n(T.Cross(i.directions[0],s.directions[2]),i,s)||!_n(T.Cross(i.directions[1],s.directions[0]),i,s)||!_n(T.Cross(i.directions[1],s.directions[1]),i,s)||!_n(T.Cross(i.directions[1],s.directions[2]),i,s)||!_n(T.Cross(i.directions[2],s.directions[0]),i,s)||!_n(T.Cross(i.directions[2],s.directions[1]),i,s)||!_n(T.Cross(i.directions[2],s.directions[2]),i,s))}}En._TmpVector3=Os.BuildArray(2,T.Zero);class kg{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(a)&&!Array.isArray(e))],kg,"extractMinAndMaxIndexed",null);v([ph.filter((...[a])=>!Array.isArray(a))],kg,"extractMinAndMax",null);function CV(a,e,t,i,s=null){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return kg.extractMinAndMaxIndexed(a,e,t,i,r,n),s&&(r.x-=r.x*s.x+s.y,r.y-=r.y*s.x+s.y,r.z-=r.z*s.x+s.y,n.x+=n.x*s.x+s.y,n.y+=n.y*s.x+s.y,n.z+=n.z*s.x+s.y),{minimum:r,maximum:n}}function Lp(a,e,t,i=null,s){const r=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),kg.extractMinAndMax(a,e,t,s,r,n),i&&(r.x-=r.x*i.x+i.y,r.y-=r.y*i.x+i.y,r.z-=r.z*i.x+i.y,n.x+=n.x*i.x+i.y,n.y+=n.y*i.x+i.y,n.z+=n.z*i.x+i.y),{minimum:r,maximum:n}}class Ws{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 s;this.effect=e,t!==void 0&&(this.defines=t),i&&((s=this.drawContext)==null||s.reset())}dispose(){var e;(e=this.drawContext)==null||e.dispose()}}class xr{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 Ws(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,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),i!==void 0&&(r.materialContext=i),e||(r.defines=null,r.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,s,r,n,o,l=!0){return new xr(e,t,i,s,r,n,o,l)}constructor(e,t,i,s,r,n,o,l=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,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=n,this._renderingMesh=o||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,l&&(this.refreshBoundingInfo(),n.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(P.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 s=this._renderingMesh.getBoundingInfo();i={minimum:s.minimum.clone(),maximum:s.maximum.clone()}}else i=CV(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new En(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 s=this.indexStart;sl&&(l=d)}return new xr(e,o,l-o+1,t,i,s,r,n)}}class jm{}class Se{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=vV(this._applyToCoroutine.bind(this)),this.uniqueId=Se._UniqueIDGenerator,Se._UniqueIDGenerator++}set(e,t){switch(e.length||U.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case P.PositionKind:this.positions=e;break;case P.NormalKind:this.normals=e;break;case P.TangentKind:this.tangents=e;break;case P.UVKind:this.uvs=e;break;case P.UV2Kind:this.uvs2=e;break;case P.UV3Kind:this.uvs3=e;break;case P.UV4Kind:this.uvs4=e;break;case P.UV5Kind:this.uvs5=e;break;case P.UV6Kind:this.uvs6=e;break;case P.ColorKind:this.colors=e;break;case P.MatricesIndicesKind:this.matricesIndices=e;break;case P.MatricesWeightsKind:this.matricesWeights=e;break;case P.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case P.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(P.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(P.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(P.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(P.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(P.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(P.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(P.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(P.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(P.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(P.ColorKind,this.colors,t),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(P.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(P.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(P.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 s=e;s.subMeshes=[];for(const r of this.materialInfos)new xr(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,s)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(P.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(P.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(P.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(P.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(P.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(P.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(P.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(P.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(P.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(P.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(P.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(P.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(P.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(P.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=W.Vector3[0],n=W.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return dv(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){var f,m;this._validate();let l=t.map(_=>_.vertexData),h=this;if(o)for(const _ of l)_&&(_._validate(),!this.normals&&_.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&_.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&_.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&_.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&_.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&_.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&_.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&_.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&_.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&_.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&_.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&_.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&_.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const _ of l)if(_){if(o)this.normals&&!_.normals&&(_.normals=new Float32Array(_.positions.length)),this.tangents&&!_.tangents&&(_.tangents=new Float32Array(_.positions.length/3*4)),this.uvs&&!_.uvs&&(_.uvs=new Float32Array(_.positions.length/3*2)),this.uvs2&&!_.uvs2&&(_.uvs2=new Float32Array(_.positions.length/3*2)),this.uvs3&&!_.uvs3&&(_.uvs3=new Float32Array(_.positions.length/3*2)),this.uvs4&&!_.uvs4&&(_.uvs4=new Float32Array(_.positions.length/3*2)),this.uvs5&&!_.uvs5&&(_.uvs5=new Float32Array(_.positions.length/3*2)),this.uvs6&&!_.uvs6&&(_.uvs6=new Float32Array(_.positions.length/3*2)),this.colors&&!_.colors&&(_.colors=new Float32Array(_.positions.length/3*4),_.colors.fill(1)),this.matricesIndices&&!_.matricesIndices&&(_.matricesIndices=new Float32Array(_.positions.length/3*4)),this.matricesWeights&&!_.matricesWeights&&(_.matricesWeights=new Float32Array(_.positions.length/3*4)),this.matricesIndicesExtra&&!_.matricesIndicesExtra&&(_.matricesIndicesExtra=new Float32Array(_.positions.length/3*4)),this.matricesWeightsExtra&&!_.matricesWeightsExtra&&(_.matricesWeightsExtra=new Float32Array(_.positions.length/3*4));else if(_._validate(),!this.normals!=!_.normals||!this.tangents!=!_.tangents||!this.uvs!=!_.uvs||!this.uvs2!=!_.uvs2||!this.uvs3!=!_.uvs3||!this.uvs4!=!_.uvs4||!this.uvs5!=!_.uvs5||!this.uvs6!=!_.uvs6||!this.colors!=!_.colors||!this.matricesIndices!=!_.matricesIndices||!this.matricesWeights!=!_.matricesWeights||!this.matricesIndicesExtra!=!_.matricesIndicesExtra||!this.matricesWeightsExtra!=!_.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let _=0,x=0,E=0;const S=[];let C=null;const y=[];for(const I of this.splitBasedOnMaterialID())y.push({vertexData:I,transform:e});for(const I of t)if(I.vertexData)for(const R of I.vertexData.splitBasedOnMaterialID())y.push({vertexData:R,transform:I.transform});y.sort((I,R)=>{const N=I.vertexData.materialInfos?I.vertexData.materialInfos[0].materialIndex:0,k=R.vertexData.materialInfos?R.vertexData.materialInfos[0].materialIndex:0;return N>k?1:N===k?0:-1});for(const I of y){const R=I.vertexData;if(R.materialInfos?_=R.materialInfos[0].materialIndex:_=0,C&&C.materialIndex===_)C.indexCount+=R.indices.length,C.verticesCount+=R.positions.length/3;else{const N=new jm;N.materialIndex=_,N.indexStart=x,N.indexCount=R.indices.length,N.verticesStart=E,N.verticesCount=R.positions.length/3,S.push(N),C=N}x+=R.indices.length,E+=R.positions.length/3}const A=y.splice(0,1)[0];h=A.vertexData,e=A.transform,l=y.map(I=>I.vertexData),t=y,this.materialInfos=S}const c=l.reduce((_,x)=>{var E;return _+(((E=x.indices)==null?void 0:E.length)??0)},((f=h.indices)==null?void 0:f.length)??0);let d=r||l.some(_=>_.indices===h.indices)?(m=h.indices)==null?void 0:m.slice():h.indices;if(c>0){let _=(d==null?void 0:d.length)??0;if(d||(d=new Array(c)),d.length!==c){if(Array.isArray(d))d.length=c;else{const E=i||d instanceof Uint32Array?new Uint32Array(c):new Uint16Array(c);E.set(d),d=E}e&&e.determinant()<0&&Se._FlipFaces(d,0,_)}let x=h.positions?h.positions.length/3:0;for(const{vertexData:E,transform:S}of t)if(E.indices){for(let C=0;C[_.vertexData.positions,_.transform])),s&&(yield),h.normals&&(this.normals=Se._MergeElement(P.NormalKind,h.normals,e,t.map(_=>[_.vertexData.normals,_.transform])),s&&(yield)),h.tangents&&(this.tangents=Se._MergeElement(P.TangentKind,h.tangents,e,t.map(_=>[_.vertexData.tangents,_.transform])),s&&(yield)),h.uvs&&(this.uvs=Se._MergeElement(P.UVKind,h.uvs,e,t.map(_=>[_.vertexData.uvs,_.transform])),s&&(yield)),h.uvs2&&(this.uvs2=Se._MergeElement(P.UV2Kind,h.uvs2,e,t.map(_=>[_.vertexData.uvs2,_.transform])),s&&(yield)),h.uvs3&&(this.uvs3=Se._MergeElement(P.UV3Kind,h.uvs3,e,t.map(_=>[_.vertexData.uvs3,_.transform])),s&&(yield)),h.uvs4&&(this.uvs4=Se._MergeElement(P.UV4Kind,h.uvs4,e,t.map(_=>[_.vertexData.uvs4,_.transform])),s&&(yield)),h.uvs5&&(this.uvs5=Se._MergeElement(P.UV5Kind,h.uvs5,e,t.map(_=>[_.vertexData.uvs5,_.transform])),s&&(yield)),h.uvs6&&(this.uvs6=Se._MergeElement(P.UV6Kind,h.uvs6,e,t.map(_=>[_.vertexData.uvs6,_.transform])),s&&(yield)),h.colors&&(this.colors=Se._MergeElement(P.ColorKind,h.colors,e,t.map(_=>[_.vertexData.colors,_.transform])),(h.hasVertexAlpha!==void 0||t.some(_=>_.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some(_=>_.vertexData.hasVertexAlpha)),s&&(yield)),h.matricesIndices&&(this.matricesIndices=Se._MergeElement(P.MatricesIndicesKind,h.matricesIndices,e,t.map(_=>[_.vertexData.matricesIndices,_.transform])),s&&(yield)),h.matricesWeights&&(this.matricesWeights=Se._MergeElement(P.MatricesWeightsKind,h.matricesWeights,e,t.map(_=>[_.vertexData.matricesWeights,_.transform])),s&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=Se._MergeElement(P.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map(_=>[_.vertexData.matricesIndicesExtra,_.transform])),s&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=Se._MergeElement(P.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map(_=>[_.vertexData.matricesWeightsExtra,_.transform]))),this}static _MergeElement(e,t,i,s){const r=s.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&r.length==0)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce((l,h)=>l+h[0].length,t.length),o=e===P.PositionKind?Se._TransformVector3Coordinates:e===P.NormalKind?Se._TransformVector3Normals:e===P.TangentKind?Se._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const l=new Float32Array(n);l.set(t),i&&o(l,i,0,t.length);let h=t.length;for(const[c,u]of r)l.set(c,h),u&&o(l,u,h,c.length),h+=c.length;return l}else{const l=new Array(n);for(let c=0;c{const n=P.DeduceStride(s);if(r.length%n!==0)throw new Error("The "+s+"s array count must be a multiple of "+n);return r.length/n},t=e(P.PositionKind,this.positions),i=(s,r)=>{const n=e(s,r);if(n!==t)throw new Error("The "+s+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(P.NormalKind,this.normals),this.tangents&&i(P.TangentKind,this.tangents),this.uvs&&i(P.UVKind,this.uvs),this.uvs2&&i(P.UV2Kind,this.uvs2),this.uvs3&&i(P.UV3Kind,this.uvs3),this.uvs4&&i(P.UV4Kind,this.uvs4),this.uvs5&&i(P.UV5Kind,this.uvs5),this.uvs6&&i(P.UV6Kind,this.uvs6),this.colors&&i(P.ColorKind,this.colors),this.matricesIndices&&i(P.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(P.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(P.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(P.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Se.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 Se._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Se._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Se;return e.isVerticesDataPresent(P.PositionKind)&&(s.positions=e.getVerticesData(P.PositionKind,t,i)),e.isVerticesDataPresent(P.NormalKind)&&(s.normals=e.getVerticesData(P.NormalKind,t,i)),e.isVerticesDataPresent(P.TangentKind)&&(s.tangents=e.getVerticesData(P.TangentKind,t,i)),e.isVerticesDataPresent(P.UVKind)&&(s.uvs=e.getVerticesData(P.UVKind,t,i)),e.isVerticesDataPresent(P.UV2Kind)&&(s.uvs2=e.getVerticesData(P.UV2Kind,t,i)),e.isVerticesDataPresent(P.UV3Kind)&&(s.uvs3=e.getVerticesData(P.UV3Kind,t,i)),e.isVerticesDataPresent(P.UV4Kind)&&(s.uvs4=e.getVerticesData(P.UV4Kind,t,i)),e.isVerticesDataPresent(P.UV5Kind)&&(s.uvs5=e.getVerticesData(P.UV5Kind,t,i)),e.isVerticesDataPresent(P.UV6Kind)&&(s.uvs6=e.getVerticesData(P.UV6Kind,t,i)),e.isVerticesDataPresent(P.ColorKind)&&(s.colors=e.getVerticesData(P.ColorKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(P.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(P.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(P.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(P.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(P.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(P.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw ot("ribbonBuilder")}static CreateBox(e){throw ot("boxBuilder")}static CreateTiledBox(e){throw ot("tiledBoxBuilder")}static CreateTiledPlane(e){throw ot("tiledPlaneBuilder")}static CreateSphere(e){throw ot("sphereBuilder")}static CreateCylinder(e){throw ot("cylinderBuilder")}static CreateTorus(e){throw ot("torusBuilder")}static CreateLineSystem(e){throw ot("linesBuilder")}static CreateDashedLines(e){throw ot("linesBuilder")}static CreateGround(e){throw ot("groundBuilder")}static CreateTiledGround(e){throw ot("groundBuilder")}static CreateGroundFromHeightMap(e){throw ot("groundBuilder")}static CreatePlane(e){throw ot("planeBuilder")}static CreateDisc(e){throw ot("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw ot("polygonBuilder")}static CreateIcoSphere(e){throw ot("icoSphereBuilder")}static CreatePolyhedron(e){throw ot("polyhedronBuilder")}static CreateCapsule(e={orientation:T.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw ot("capsuleBuilder")}static CreateTorusKnot(e){throw ot("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0,f=0,m=0,_=0,x=0,E=0,S=0,C=0,y=0,A=0,I=0,R=0,N=0,k=!1,B=!1,Q=!1,ne=!1,de=1,ge=0,fe=null;s&&(k=!!s.facetNormals,B=!!s.facetPositions,Q=!!s.facetPartitioning,de=s.useRightHandedSystem===!0?-1:1,ge=s.ratio||0,ne=!!s.depthSort,fe=s.distanceTo,ne&&fe===void 0&&(fe=T.Zero()));let Ee=0,De=0,Te=0,ue=0;for(Q&&s&&s.bbSize&&(Ee=s.subDiv.X*ge/s.bbSize.x,De=s.subDiv.Y*ge/s.bbSize.y,Te=s.subDiv.Z*ge/s.bbSize.z,ue=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(a))],Se,"_TransformVector3Coordinates",null);v([ph.filter((...[a])=>!Array.isArray(a))],Se,"_TransformVector3Normals",null);v([ph.filter((...[a])=>!Array.isArray(a))],Se,"_TransformVector4Normals",null);v([ph.filter((...[a])=>!Array.isArray(a))],Se,"_FlipFaces",null);class Us{static get ForceFullSceneLoadingForIncremental(){return Us._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Us._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Us._ShowLoadingScreen}static set ShowLoadingScreen(e){Us._ShowLoadingScreen=e}static get loggingLevel(){return Us._LoggingLevel}static set loggingLevel(e){Us._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Us._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Us._CleanBoneMatrixWeights=e}}Us._ForceFullSceneLoadingForIncremental=!1;Us._ShowLoadingScreen=!0;Us._CleanBoneMatrixWeights=!1;Us._LoggingLevel=0;class Ht{}Ht.UseOpenGLOrientationForUV=!1;class Is{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 Is(Is.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||We.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.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,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new P(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===P.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const o=this._extend&&this._extend.minimum||new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let h=0;h65535);for(const s of this._meshes)s._createGlobalSubMesh(!0),s.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 s of this._meshes)s._createGlobalSubMesh(!0),s.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,s=i.indexOf(e);s!==-1&&(i.splice(s,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(P.PositionKind),!e))return;this._extend=Lp(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===P.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 s=this._meshes,r=s.length;for(let n=0;n0){for(let s=0;s0){for(let s=0;s0){for(let s=0;s-1&&this._parentContainer.geometries.splice(s,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Se;t.indices=[];const i=this.getIndices();if(i)for(let l=0;l0){const o=new Float32Array(e,n.positionsAttrDesc.offset,n.positionsAttrDesc.count);t.setVerticesData(P.PositionKind,o,!1)}if(n.normalsAttrDesc&&n.normalsAttrDesc.count>0){const o=new Float32Array(e,n.normalsAttrDesc.offset,n.normalsAttrDesc.count);t.setVerticesData(P.NormalKind,o,!1)}if(n.tangetsAttrDesc&&n.tangetsAttrDesc.count>0){const o=new Float32Array(e,n.tangetsAttrDesc.offset,n.tangetsAttrDesc.count);t.setVerticesData(P.TangentKind,o,!1)}if(n.uvsAttrDesc&&n.uvsAttrDesc.count>0){const o=new Float32Array(e,n.uvsAttrDesc.offset,n.uvsAttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs2AttrDesc.offset,n.uvs2AttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs3AttrDesc.offset,n.uvs3AttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs4AttrDesc.offset,n.uvs4AttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs5AttrDesc.offset,n.uvs5AttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.uvs6AttrDesc.offset,n.uvs6AttrDesc.count);if(Ht.UseOpenGLOrientationForUV)for(let l=1;l0){const o=new Float32Array(e,n.colorsAttrDesc.offset,n.colorsAttrDesc.count);t.setVerticesData(P.ColorKind,o,!1,n.colorsAttrDesc.stride)}if(n.matricesIndicesAttrDesc&&n.matricesIndicesAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesAttrDesc.offset,n.matricesIndicesAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesKind,l,!1)}if(n.matricesIndicesExtraAttrDesc&&n.matricesIndicesExtraAttrDesc.count>0){const o=new Int32Array(e,n.matricesIndicesExtraAttrDesc.offset,n.matricesIndicesExtraAttrDesc.count),l=[];for(let h=0;h>8),l.push((c&16711680)>>16),l.push(c>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,l,!1)}if(n.matricesWeightsAttrDesc&&n.matricesWeightsAttrDesc.count>0){const o=new Float32Array(e,n.matricesWeightsAttrDesc.offset,n.matricesWeightsAttrDesc.count);t.setVerticesData(P.MatricesWeightsKind,o,!1)}if(n.indicesAttrDesc&&n.indicesAttrDesc.count>0){const o=new Int32Array(e,n.indicesAttrDesc.offset,n.indicesAttrDesc.count);t.setIndices(o,null)}if(n.subMeshesAttrDesc&&n.subMeshesAttrDesc.count>0){const o=new Int32Array(e,n.subMeshesAttrDesc.offset,n.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesKind,n,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(P.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const n=[];for(let o=0;o>8),n.push((l&16711680)>>16),n.push(l>>24&255)}t.setVerticesData(P.MatricesIndicesExtraKind,n,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Is._CleanMatricesWeights(e,t),t.setVerticesData(P.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let n=0;n-1){const u=t.getScene().getLastSkeletonById(e.skeletonId);if(!u)return;s=u.bones.length}else return;const r=t.getVerticesData(P.MatricesIndicesKind),n=t.getVerticesData(P.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,h=e.numBoneInfluencer,c=o.length;for(let u=0;uh-1)&&(f=h-1),d>.001){const m=1/d;for(let _=0;_<4;_++)o[u+_]*=m;if(l)for(let _=0;_<4;_++)l[u+_]*=m}else f>=4?(l[u+f-4]=1-d,n[u+f-4]=s):(o[u+f]=1-d,r[u+f]=s)}t.setVerticesData(P.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(P.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Is(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Gt&&Gt.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new En(T.FromArray(e.boundingBoxMinimum),T.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(P.UVKind),e.hasUVs2&&s._delayInfo.push(P.UV2Kind),e.hasUVs3&&s._delayInfo.push(P.UV3Kind),e.hasUVs4&&s._delayInfo.push(P.UV4Kind),e.hasUVs5&&s._delayInfo.push(P.UV5Kind),e.hasUVs6&&s._delayInfo.push(P.UV6Kind),e.hasColors&&s._delayInfo.push(P.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(P.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(P.MatricesWeightsKind),s._delayLoadingFunction=Se.ImportVertexData):Se.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class QI{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new bV(e)}sampleFrame(e=ks.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 bV{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}}nt.prototype.setAlphaMode=function(a,e=!1){if(this._alphaMode===a){if(!e){const t=a===0;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(a){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=a===0),this._alphaMode=a};function HE(a,e,t=!1,i){switch(a){case 3:{const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e);return i&&r.set(new Int8Array(i)),r}case 0:{const r=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}case 4:{const r=e instanceof ArrayBuffer?new Int16Array(e):new Int16Array(t?e/2:e);return i&&r.set(new Int16Array(i)),r}case 5:case 8:case 9:case 10:case 2:{const r=e instanceof ArrayBuffer?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&r.set(new Uint16Array(i)),r}case 6:{const r=e instanceof ArrayBuffer?new Int32Array(e):new Int32Array(t?e/4:e);return i&&r.set(new Int32Array(i)),r}case 7:case 11:case 12:case 13:case 14:case 15:{const r=e instanceof ArrayBuffer?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&r.set(new Uint32Array(i)),r}case 1:{const r=e instanceof ArrayBuffer?new Float32Array(e):new Float32Array(t?e/4:e);return i&&r.set(new Float32Array(i)),r}}const s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}nt.prototype._readTexturePixelsSync=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,h=0){var d,f;const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const m=c.createFramebuffer();if(!m)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=m}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),i>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,(d=a._hardwareTexture)==null?void 0:d.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,(f=a._hardwareTexture)==null?void 0:f.underlyingResource,s);let u=a.type!==void 0?this._getWebGLTextureType(a.type):c.UNSIGNED_BYTE;if(o)r||(r=HE(a.type,4*e*t));else switch(u){case c.UNSIGNED_BYTE:r||(r=new Uint8Array(4*e*t)),u=c.UNSIGNED_BYTE;break;default:r||(r=new Float32Array(4*e*t)),u=c.FLOAT;break}return n&&this.flushFramebuffer(),c.readPixels(l,h,e,t,c.RGBA,u,r),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),r};nt.prototype._readTexturePixels=function(a,e,t,i=-1,s=0,r=null,n=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(a,e,t,i,s,r,n,o,l,h))};nt.prototype.updateDynamicIndexBuffer=function(a,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(a);let i;a.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()};nt.prototype.updateDynamicVertexBuffer=function(a,e,t,i){this.bindArrayBuffer(a),t===void 0&&(t=0);const s=e.byteLength||e.length;i===void 0||i>=s&&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()};He.prototype.displayLoadingUI=function(){if(!Vs())return;const a=this.loadingScreen;a&&a.displayLoadingUI()};He.prototype.hideLoadingUI=function(){if(!Vs())return;const a=this._loadingScreen;a&&a.hideLoadingUI()};Object.defineProperty(He.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=He.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(a){this._loadingScreen=a},enumerable:!0,configurable:!0});Object.defineProperty(He.prototype,"loadingUIText",{set:function(a){this.loadingScreen.loadingUIText=a},enumerable:!0,configurable:!0});Object.defineProperty(He.prototype,"loadingUIBackgroundColor",{set:function(a){this.loadingScreen.loadingUIBackgroundColor=a},enumerable:!0,configurable:!0});He.prototype.getInputElement=function(){return this._renderingCanvas};He.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};He.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};He.prototype.getAspectRatio=function(a,e=!1){const t=a.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};He.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};He.prototype._verifyPointerLock=function(){var a;(a=this._onPointerLockChange)==null||a.call(this)};He.prototype.getInputElement=function(){return this._renderingCanvas};He.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};He.prototype.setDepthFunction=function(a){this._depthCullingState.depthFunc=a};He.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};He.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};He.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};He.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};He.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};He.prototype.setDepthWrite=function(a){this._depthCullingState.depthMask=a};He.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};He.prototype.setStencilBuffer=function(a){this._stencilState.stencilTest=a};He.prototype.getStencilMask=function(){return this._stencilState.stencilMask};He.prototype.setStencilMask=function(a){this._stencilState.stencilMask=a};He.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};He.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};He.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};He.prototype.setStencilFunction=function(a){this._stencilState.stencilFunc=a};He.prototype.setStencilFunctionReference=function(a){this._stencilState.stencilFuncRef=a};He.prototype.setStencilFunctionMask=function(a){this._stencilState.stencilFuncMask=a};He.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};He.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};He.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};He.prototype.setStencilOperationFail=function(a){this._stencilState.stencilOpStencilFail=a};He.prototype.setStencilOperationDepthFail=function(a){this._stencilState.stencilOpDepthFail=a};He.prototype.setStencilOperationPass=function(a){this._stencilState.stencilOpStencilDepthPass=a};He.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()};He.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)};He.prototype.setAlphaConstants=function(a,e,t,i){this._alphaState.setAlphaBlendConstants(a,e,t,i)};He.prototype.getAlphaMode=function(){return this._alphaMode};He.prototype.getAlphaEquation=function(){return this._alphaEquation};He.prototype.getRenderPassNames=function(){return this._renderPassNames};He.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};He.prototype.createRenderPassId=function(a){const e=++He._RenderPassIdCounter;return this._renderPassNames[e]=a??"NONAME",e};He.prototype.releaseRenderPassId=function(a){this._renderPassNames[a]=void 0;for(let e=0;e{a.onCanvasFocusObservable.notifyObservers(a)},a._onCanvasBlur=()=>{a.onCanvasBlurObservable.notifyObservers(a)},a._onCanvasContextMenu=s=>{a.disableContextMenu&&s.preventDefault()},e.addEventListener("focus",a._onCanvasFocus),e.addEventListener("blur",a._onCanvasBlur),e.addEventListener("contextmenu",a._onCanvasContextMenu),a._onBlur=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.disable(),a._windowIsBackground=!0},a._onFocus=()=>{a.disablePerformanceMonitorInBackground&&a.performanceMonitor.enable(),a._windowIsBackground=!1},a._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==e&&a.onCanvasPointerOutObservable.notifyObservers(s)};const i=a.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",a._onBlur),i.addEventListener("focus",a._onFocus)),e.addEventListener("pointerout",a._onCanvasPointerOut),t.doNotHandleTouchAction||yV(e),!He.audioEngine&&t.audioEngine&&He.AudioEngineFactory&&(He.audioEngine=He.AudioEngineFactory(a.getRenderingCanvas(),a.getAudioContext(),a.getAudioDestination())),sp()&&(a._onFullscreenChange=()=>{a.isFullscreen=!!document.fullscreenElement,a.isFullscreen&&a._pointerLockRequested&&e&&fv(e)},document.addEventListener("fullscreenchange",a._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",a._onFullscreenChange,!1),a._onPointerLockChange=()=>{a.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",a._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",a._onPointerLockChange,!1)),a.enableOfflineSupport=He.OfflineProviderFactory!==void 0,a._deterministicLockstep=!!t.deterministicLockstep,a._lockstepMaxSteps=t.lockstepMaxSteps||0,a._timeStep=t.timeStep||1/60}function JI(a,e){We.Instances.length===1&&He.audioEngine&&(He.audioEngine.dispose(),He.audioEngine=null);const t=a.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",a._onBlur),t.removeEventListener("focus",a._onFocus)),e&&(e.removeEventListener("focus",a._onCanvasFocus),e.removeEventListener("blur",a._onCanvasBlur),e.removeEventListener("pointerout",a._onCanvasPointerOut),e.removeEventListener("contextmenu",a._onCanvasContextMenu)),sp()&&(document.removeEventListener("fullscreenchange",a._onFullscreenChange),document.removeEventListener("mozfullscreenchange",a._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",a._onFullscreenChange),document.removeEventListener("msfullscreenchange",a._onFullscreenChange),document.removeEventListener("pointerlockchange",a._onPointerLockChange),document.removeEventListener("mspointerlockchange",a._onPointerLockChange),document.removeEventListener("mozpointerlockchange",a._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",a._onPointerLockChange))}function eP(a){const e=document.createElement("span");e.innerHTML="Hg",e.setAttribute("style",`font: ${a} !important`);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 s=0,r=0;try{r=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",s=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:s,height:r,descent:r-s}}function tP(a,e,t){return new Promise((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{a.createImageBitmap(n,t).then(o=>{s(o)})})},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=e})}function iP(a,e,t,i){const r=a.createCanvas(t,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}function sP(a){const e=a.requestFullscreen||a.webkitRequestFullscreen;e&&e.call(a)}function rP(){const a=document;document.exitFullscreen?document.exitFullscreen():a.webkitCancelFullScreen&&a.webkitCancelFullScreen()}function fv(a){if(a.requestPointerLock){const e=a.requestPointerLock();e instanceof Promise?e.then(()=>{a.focus()}).catch(()=>{}):a.focus()}}function nP(){document.exitPointerLock&&document.exitPointerLock()}He.AudioEngineFactory=(a,e,t)=>new AV(a,e,t);class AV{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 K,this.onAudioLockedObservable=new K,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!Vs())return;typeof window.AudioContext<"u"&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch{}try{s&&s.canPlayType&&s.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()}_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,U.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 ee extends nt{static get NpmPackage(){return He.NpmPackage}static get Version(){return He.Version}static get Instances(){return We.Instances}static get LastCreatedEngine(){return We.LastCreatedEngine}static get LastCreatedScene(){return We.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,n=>{s(n)},void 0,t,i,(n,o)=>{r(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}setDepthStencilTexture(e,t,i,s){e!==void 0&&(t&&(this._boundUniforms[e]=t),!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s==null?void 0:s.texture)??null,i)}setTextureFromPostProcessOutput(e,t,i){var s;this._bindTexture(e,((s=t==null?void 0:t._outputTexture)==null?void 0:s.texture)??null,i)}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 eP(e)}_renderFrame(){for(let e=0;e1&&r){const o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=o}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_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(s=>{s&&s._outputTexture===e&&(s._outputTexture=null)})})})}_rescaleTexture(e,t,i,s,r){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 n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&ee._RescalePostProcessFactory&&(this._rescalePostProcess=ee._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(l){l._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()}))}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new of(e,this._gl),o=new $t(this,xt.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(c,s,l,o,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){U.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 wp(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 s=this._gl;return new Promise((r,n)=>{const o=()=>{const l=s.clientWaitSync(e,t,0);if(l==s.WAIT_FAILED){n();return}if(l==s.TIMEOUT_EXPIRED){setTimeout(o,i);return}r()};o()})}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const l=this._gl,h=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,s,r,n,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);const c=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(l.flush(),this._clientWaitAsync(c,0,10).then(()=>(l.deleteSync(c),l.bindBuffer(l.PIXEL_PACK_BUFFER,h),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(h),o))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),JI(this,this._renderingCanvas),super.dispose()}}ee.ALPHA_DISABLE=0;ee.ALPHA_ADD=1;ee.ALPHA_COMBINE=2;ee.ALPHA_SUBTRACT=3;ee.ALPHA_MULTIPLY=4;ee.ALPHA_MAXIMIZED=5;ee.ALPHA_ONEONE=6;ee.ALPHA_PREMULTIPLIED=7;ee.ALPHA_PREMULTIPLIED_PORTERDUFF=8;ee.ALPHA_INTERPOLATE=9;ee.ALPHA_SCREENMODE=10;ee.DELAYLOADSTATE_NONE=0;ee.DELAYLOADSTATE_LOADED=1;ee.DELAYLOADSTATE_LOADING=2;ee.DELAYLOADSTATE_NOTLOADED=4;ee.NEVER=512;ee.ALWAYS=519;ee.LESS=513;ee.EQUAL=514;ee.LEQUAL=515;ee.GREATER=516;ee.GEQUAL=518;ee.NOTEQUAL=517;ee.KEEP=7680;ee.REPLACE=7681;ee.INCR=7682;ee.DECR=7683;ee.INVERT=5386;ee.INCR_WRAP=34055;ee.DECR_WRAP=34056;ee.TEXTURE_CLAMP_ADDRESSMODE=0;ee.TEXTURE_WRAP_ADDRESSMODE=1;ee.TEXTURE_MIRROR_ADDRESSMODE=2;ee.TEXTUREFORMAT_ALPHA=0;ee.TEXTUREFORMAT_LUMINANCE=1;ee.TEXTUREFORMAT_LUMINANCE_ALPHA=2;ee.TEXTUREFORMAT_RGB=4;ee.TEXTUREFORMAT_RGBA=5;ee.TEXTUREFORMAT_RED=6;ee.TEXTUREFORMAT_R=6;ee.TEXTUREFORMAT_RG=7;ee.TEXTUREFORMAT_RED_INTEGER=8;ee.TEXTUREFORMAT_R_INTEGER=8;ee.TEXTUREFORMAT_RG_INTEGER=9;ee.TEXTUREFORMAT_RGB_INTEGER=10;ee.TEXTUREFORMAT_RGBA_INTEGER=11;ee.TEXTURETYPE_UNSIGNED_BYTE=0;ee.TEXTURETYPE_UNSIGNED_INT=0;ee.TEXTURETYPE_FLOAT=1;ee.TEXTURETYPE_HALF_FLOAT=2;ee.TEXTURETYPE_BYTE=3;ee.TEXTURETYPE_SHORT=4;ee.TEXTURETYPE_UNSIGNED_SHORT=5;ee.TEXTURETYPE_INT=6;ee.TEXTURETYPE_UNSIGNED_INTEGER=7;ee.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;ee.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;ee.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;ee.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;ee.TEXTURETYPE_UNSIGNED_INT_24_8=12;ee.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;ee.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;ee.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;ee.TEXTURE_NEAREST_SAMPLINGMODE=1;ee.TEXTURE_BILINEAR_SAMPLINGMODE=2;ee.TEXTURE_TRILINEAR_SAMPLINGMODE=3;ee.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;ee.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;ee.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;ee.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;ee.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;ee.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;ee.TEXTURE_NEAREST_LINEAR=7;ee.TEXTURE_NEAREST_NEAREST=1;ee.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;ee.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;ee.TEXTURE_LINEAR_LINEAR=2;ee.TEXTURE_LINEAR_NEAREST=12;ee.TEXTURE_EXPLICIT_MODE=0;ee.TEXTURE_SPHERICAL_MODE=1;ee.TEXTURE_PLANAR_MODE=2;ee.TEXTURE_CUBIC_MODE=3;ee.TEXTURE_PROJECTION_MODE=4;ee.TEXTURE_SKYBOX_MODE=5;ee.TEXTURE_INVCUBIC_MODE=6;ee.TEXTURE_EQUIRECTANGULAR_MODE=7;ee.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;ee.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ee.SCALEMODE_FLOOR=1;ee.SCALEMODE_NEAREST=2;ee.SCALEMODE_CEILING=3;const RV=L.Compose(T.One(),ae.FromEulerAngles(0,Math.PI,0),T.Zero());class ut extends Qt{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&ut.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!==ut.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),this._forward=new T(0,0,1),this._up=new T(0,1,0),this._right=new T(1,0,0),this._position=T.Zero(),this._rotation=T.Zero(),this._rotationQuaternion=null,this._scaling=T.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=ut.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=L.Zero(),this._usePivotMatrix=!1,this._absolutePosition=T.Zero(),this._absoluteScaling=T.Zero(),this._absoluteRotationQuaternion=ae.Identity(),this._pivotMatrix=L.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new K,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 T.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return T.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return T.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=L.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==ut.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=L.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||ae.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,s;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const r=W.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),T.TransformCoordinatesFromFloatsToRef(t,i,s,r,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=T.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=W.Matrix[0];return this._localMatrix.invertToRef(e),T.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=T.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=Wt.LOCAL){const n=ut._LookAtVectorCache,o=r===Wt.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===Wt.WORLD&&this.parent)if(this.rotationQuaternion){const l=W.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);const h=W.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(h),h.invert(),l.multiplyToRef(h,l),this.rotationQuaternion.fromRotationMatrix(l)}else{const l=W.Quaternion[0];ae.FromEulerVectorToRef(this.rotation,l);const h=W.Matrix[0];l.toRotationMatrix(h);const c=W.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),h.multiplyToRef(c,h),l.fromRotationMatrix(h),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=T.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return T.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?ae.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=Wt.LOCAL){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Wt.WORLD){const s=W.Matrix[0];i.invertToRef(s),e=T.TransformCoordinates(e,s)}return this.setPivotMatrix(L.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=T.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=T.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),T.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 s=W.Quaternion[0],r=W.Vector3[0],n=W.Vector3[1],o=W.Matrix[1];L.IdentityToRef(o);const l=W.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=ut._TmpRotation,ae.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),L.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(L.Identity()),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 s;if(!i||i===Wt.LOCAL)s=ae.RotationAxisToRef(e,t,ut._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);else{if(this.parent){const r=this.parent.getWorldMatrix(),n=W.Matrix[0];r.invertToRef(n),e=T.TransformNormal(e,n),r.determinant()<0&&(t*=-1)}s=ae.RotationAxisToRef(e,t,ut._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=ae.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=W.Vector3[0],r=W.Vector3[1],n=W.Vector3[2],o=W.Quaternion[0],l=W.Matrix[0],h=W.Matrix[1],c=W.Matrix[2],u=W.Matrix[3];return e.subtractToRef(this.position,s),L.TranslationToRef(s.x,s.y,s.z,l),L.TranslationToRef(-s.x,-s.y,-s.z,h),L.RotationAxisToRef(t,i,c),h.multiplyToRef(c,u),u.multiplyToRef(l,u),u.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(!i||i===Wt.LOCAL){const r=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(r)}else this.setAbsolutePosition(this.getAbsolutePosition().add(s));return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=W.Quaternion[1],ae.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=W.Quaternion[0];return ae.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==ut.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 s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.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 r=this._getEffectiveParent(),n=ut._TmpScaling;let o=this._position;if(this._infiniteDistance&&!this.parent&&t){const h=t.getWorldMatrix(),c=new T(h.m[12],h.m[13],h.m[14]);o=ut._TmpTranslation,o.copyFromFloats(this._position.x+c.x,this._position.y+c.y,this._position.z+c.z)}n.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(ae.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=ut._TmpRotation,ae.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){const h=W.Matrix[1];L.ScalingToRef(n.x,n.y,n.z,h);const c=W.Matrix[0];l.toRotationMatrix(c),this._pivotMatrix.multiplyToRef(h,W.Matrix[4]),W.Matrix[4].multiplyToRef(c,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else L.ComposeToRef(n,l,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),W.Matrix[7])}else W.Matrix[7].copyFrom(r.getWorldMatrix());const h=W.Vector3[5],c=W.Vector3[6],u=W.Quaternion[0];W.Matrix[7].decompose(c,u,h),L.ScalingToRef(c.x,c.y,c.z,W.Matrix[7]),W.Matrix[7].setTranslation(h),ut.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(u,h),this._localMatrix.setTranslation(h)),this._localMatrix.multiplyToRef(W.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const h=this.parent;h.getSkeleton().prepare(),this._localMatrix.multiplyToRef(h.getFinalMatrix(),W.Matrix[6]),W.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const h=W.Vector3[0];if(this._worldMatrix.getTranslationToRef(h),W.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&W.Matrix[1].multiplyToRef(RV,W.Matrix[1]),W.Matrix[1].setTranslationFromFloats(0,0,0),W.Matrix[1].invertToRef(W.Matrix[0]),(this.billboardMode&ut.BILLBOARDMODE_ALL)!==ut.BILLBOARDMODE_ALL){W.Matrix[0].decompose(void 0,W.Quaternion[0],void 0);const c=W.Vector3[1];W.Quaternion[0].toEulerAnglesToRef(c),(this.billboardMode&ut.BILLBOARDMODE_X)!==ut.BILLBOARDMODE_X&&(c.x=0),(this.billboardMode&ut.BILLBOARDMODE_Y)!==ut.BILLBOARDMODE_Y&&(c.y=0),(this.billboardMode&ut.BILLBOARDMODE_Z)!==ut.BILLBOARDMODE_Z&&(c.z=0),L.RotationYawPitchRollToRef(c.y,c.x,c.z,W.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const h=W.Vector3[0];this._worldMatrix.getTranslationToRef(h);const c=t.globalPosition;this._worldMatrix.invertToRef(W.Matrix[1]);const u=W.Vector3[1];T.TransformCoordinatesToRef(c,W.Matrix[1],u),u.normalize();const d=-Math.atan2(u.z,u.x)+Math.PI/2,f=Math.sqrt(u.x*u.x+u.z*u.z),m=-Math.atan2(u.y,f);if(ae.RotationYawPitchRollToRef(d,m,0,W.Quaternion[0]),(this.billboardMode&ut.BILLBOARDMODE_ALL)!==ut.BILLBOARDMODE_ALL){const _=W.Vector3[1];W.Quaternion[0].toEulerAnglesToRef(_),(this.billboardMode&ut.BILLBOARDMODE_X)!==ut.BILLBOARDMODE_X&&(_.x=0),(this.billboardMode&ut.BILLBOARDMODE_Y)!==ut.BILLBOARDMODE_Y&&(_.y=0),(this.billboardMode&ut.BILLBOARDMODE_Z)!==ut.BILLBOARDMODE_Z&&(_.z=0),L.RotationYawPitchRollToRef(_.y,_.x,_.z,W.Matrix[0])}else L.FromQuaternionToRef(W.Quaternion[0],W.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._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=L.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const t=this.getChildren();for(let i=0;inew ut(e,this.getScene()),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const r=this.getDescendants(!0);for(let n=0;nnew ut(e.name,t),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(L.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(L.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let r=0;r(!t||t(s))&&s instanceof ut),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 s of i)s.parent=null,s.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;const h=1/l;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}ut.BILLBOARDMODE_NONE=0;ut.BILLBOARDMODE_X=1;ut.BILLBOARDMODE_Y=2;ut.BILLBOARDMODE_Z=4;ut.BILLBOARDMODE_ALL=7;ut.BILLBOARDMODE_USE_POSITION=128;ut.BillboardUseParentOrientation=!1;ut._TmpRotation=ae.Zero();ut._TmpScaling=T.Zero();ut._TmpTranslation=T.Zero();ut._LookAtVectorCache=new T(0,0,0);ut._RotationAxisCache=new ae;v([Sr("position")],ut.prototype,"_position",void 0);v([Sr("rotation")],ut.prototype,"_rotation",void 0);v([EU("rotationQuaternion")],ut.prototype,"_rotationQuaternion",void 0);v([Sr("scaling")],ut.prototype,"_scaling",void 0);v([O("billboardMode")],ut.prototype,"_billboardMode",void 0);v([O()],ut.prototype,"scalingDeterminant",void 0);v([O("infiniteDistance")],ut.prototype,"_infiniteDistance",void 0);v([O()],ut.prototype,"ignoreNonUniformScaling",void 0);v([O()],ut.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class IV{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new T(0,0,0),this._diffPositionForCollisions=new T(0,0,0),this._collisionResponse=!0}}class PV{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=T.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class MV{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new PV,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 IV,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Ft extends ut{static get BILLBOARDMODE_NONE(){return ut.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ut.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ut.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ut.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ut.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ut.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 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._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}get _positions(){return null}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 MV,this._waitingMaterialId=null,this.cullingStrategy=Ft.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new K,this.onCollisionPositionChangeObservable=new K,this.onMaterialChangedObservable=new K,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=re.Red(),this.outlineWidth=.02,this.overlayColor=re.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new T(.5,1,.5),this.ellipsoidOffset=new T(0,0,0),this.edgesWidth=1,this.edgesColor=new Oe(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 K,this._onCollisionPositionChange=(i,s,r=null)=>{s.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>ee.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),r&&this.onCollideObservable.notifyObservers(r),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new ze(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case wo.Aggressive:this.doNotSyncBoundingInfo=!0;case wo.Intermediate: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!==ut.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 s=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_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,s){return this}updateVerticesData(e,t,i,s){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 En(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(P.MatricesIndicesKind)&&this.isVerticesDataPresent(P.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ut.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 s=new L;(this.rotationQuaternion?this.rotationQuaternion:ae.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const n=T.Zero(),o=this.definedFacingForward?-1:1;return T.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,s,n),n}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new T(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked?this:(this._refreshBoundingInfo(this._getPositionData(e,t),null),this)}_refreshBoundingInfo(e,t){if(e){const i=Lp(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new En(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i4,l=o?this.getVerticesData(P.MatricesIndicesExtraKind):null,h=o?this.getVerticesData(P.MatricesWeightsExtraKind):null,c=this.skeleton.getTransformMatrices(this),u=W.Vector3[0],d=W.Matrix[0],f=W.Matrix[1];let m=0;for(let _=0;_0&&(L.FromFloat32ArrayToRefScaled(c,Math.floor(r[m+x]*16),E,f),d.addToSelf(f));if(o)for(x=0;x<4;x++)E=h[m+x],E>0&&(L.FromFloat32ArrayToRefScaled(c,Math.floor(l[m+x]*16),E,f),d.addToSelf(f));s===P.NormalKind?T.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],d,u):T.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],d,u),u.toArray(i,_),s===P.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,P.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,P.PositionKind)}_getPositionData(e,t){var s;let i=this.getVerticesData(P.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const r=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(r.length);for(let n=0;n1||!s.IsGlobal)&&s.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 s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i){for(const n of this.getChildMeshes())if(n.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 s;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const r=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let o=r;o1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=W.Matrix[0],i=W.Matrix[1];return L.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,s=!1,r,n=!1){const o=new zs,l=this.getClassName(),h=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:T.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let u=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),f=d.length;let m=!1;for(let _=0;_1&&!n&&!x.canIntersects(e))continue;const E=x.intersects(e,this._positions,this.getIndices(),t,i);if(E&&(t||!u||E.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 h=o.getShadowGenerators();if(h){const c=h.values();for(let u=c.next();u.done!==!0;u=c.next()){const f=u.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 n=s.getEngine();if(this._occlusionQuery!==null&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),s.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:T.Zero()}e.depthSortedFacets=[];for(let o=0;oAt?r.maximum.x-r.minimum.x:At,e.bbSize.y=r.maximum.y-r.minimum.y>At?r.maximum.y-r.minimum.y:At,e.bbSize.z=r.maximum.z-r.minimum.z>At?r.maximum.z-r.minimum.z:At;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),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=r,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),T.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Se.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const o=e.depthSortedIndices.length/3|0;for(let l=0;lr.subDiv.max||o<0||o>r.subDiv.max||l<0||l>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),l=W.Matrix[5];o.invertToRef(l);const h=W.Vector3[8];T.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&T.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),c}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,l=0,h=0,c=0,u=0,d=0,f=0,m=0,_=0;const x=this.getFacetLocalPositions(),E=this.getFacetLocalNormals(),S=this.getFacetsAtLocalCoordinates(e,t,i);if(!S)return null;let C=Number.MAX_VALUE,y=C,A,I,R;for(let N=0;N=0||r&&!n&&u<=0)&&(u=I.x*R.x+I.y*R.y+I.z*R.z,d=-(I.x*e+I.y*t+I.z*i-u)/(I.x*I.x+I.y*I.y+I.z*I.z),f=e+I.x*d,m=t+I.y*d,_=i+I.z*d,l=f-e,h=m-t,c=_-i,y=l*l+h*h+c*c,ye.emitter===this)}}Ft.OCCLUSION_TYPE_NONE=0;Ft.OCCLUSION_TYPE_OPTIMISTIC=1;Ft.OCCLUSION_TYPE_STRICT=2;Ft.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;Ft.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;Ft.CULLINGSTRATEGY_STANDARD=0;Ft.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;Ft.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;Ft.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;H("BABYLON.AbstractMesh",Ft);class yl{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){Pe.Clone(()=>e,this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse(()=>this,e,t,i)}}v([O()],yl.prototype,"func",null);v([O()],yl.prototype,"funcRef",null);v([O()],yl.prototype,"funcMask",null);v([O()],yl.prototype,"opStencilFail",null);v([O()],yl.prototype,"opDepthFail",null);v([O()],yl.prototype,"opStencilDepthPass",null);v([O()],yl.prototype,"mask",null);v([O()],yl.prototype,"enabled",null);var gr;(function(a){a[a.Created=1]="Created",a[a.Disposed=2]="Disposed",a[a.GetDefineNames=4]="GetDefineNames",a[a.PrepareUniformBuffer=8]="PrepareUniformBuffer",a[a.IsReadyForSubMesh=16]="IsReadyForSubMesh",a[a.PrepareDefines=32]="PrepareDefines",a[a.BindForSubMesh=64]="BindForSubMesh",a[a.PrepareEffect=128]="PrepareEffect",a[a.GetAnimatables=256]="GetAnimatables",a[a.GetActiveTextures=512]="GetActiveTextures",a[a.HasTexture=1024]="HasTexture",a[a.FillRenderTargetTextures=2048]="FillRenderTargetTextures",a[a.HasRenderTargetTextures=4096]="HasRenderTargetTextures",a[a.HardBindForSubMesh=8192]="HardBindForSubMesh"})(gr||(gr={}));function Va(a){a.indexOf("vClipPlane")===-1&&a.push("vClipPlane"),a.indexOf("vClipPlane2")===-1&&a.push("vClipPlane2"),a.indexOf("vClipPlane3")===-1&&a.push("vClipPlane3"),a.indexOf("vClipPlane4")===-1&&a.push("vClipPlane4"),a.indexOf("vClipPlane5")===-1&&a.push("vClipPlane5"),a.indexOf("vClipPlane6")===-1&&a.push("vClipPlane6")}function vh(a,e,t){const i=!!(a.clipPlane??e.clipPlane),s=!!(a.clipPlane2??e.clipPlane2),r=!!(a.clipPlane3??e.clipPlane3),n=!!(a.clipPlane4??e.clipPlane4),o=!!(a.clipPlane5??e.clipPlane5),l=!!(a.clipPlane6??e.clipPlane6);i&&t.push("#define CLIPPLANE"),s&&t.push("#define CLIPPLANE2"),r&&t.push("#define CLIPPLANE3"),n&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function OV(a,e,t){let i=!1;const s=!!(a.clipPlane??e.clipPlane),r=!!(a.clipPlane2??e.clipPlane2),n=!!(a.clipPlane3??e.clipPlane3),o=!!(a.clipPlane4??e.clipPlane4),l=!!(a.clipPlane5??e.clipPlane5),h=!!(a.clipPlane6??e.clipPlane6);return t.CLIPPLANE!==s&&(t.CLIPPLANE=s,i=!0),t.CLIPPLANE2!==r&&(t.CLIPPLANE2=r,i=!0),t.CLIPPLANE3!==n&&(t.CLIPPLANE3=n,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==h&&(t.CLIPPLANE6=h,i=!0),i}function pa(a,e,t){let i=e.clipPlane??t.clipPlane;Wc(a,"vClipPlane",i),i=e.clipPlane2??t.clipPlane2,Wc(a,"vClipPlane2",i),i=e.clipPlane3??t.clipPlane3,Wc(a,"vClipPlane3",i),i=e.clipPlane4??t.clipPlane4,Wc(a,"vClipPlane4",i),i=e.clipPlane5??t.clipPlane5,Wc(a,"vClipPlane5",i),i=e.clipPlane6??t.clipPlane6,Wc(a,"vClipPlane6",i)}function Wc(a,e,t){t&&a.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d)}const HA=re.Black(),XA={NUM_MORPH_INFLUENCERS:0};function Ch(a,e,t){if(!a||a.LOGARITHMICDEPTH||a.indexOf&&a.indexOf("LOGARITHMICDEPTH")>=0){const i=t.activeCamera;i.mode===1&&U.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}function mc(a,e,t,i=!1){t&&a.fogEnabled&&(!e||e.applyFog)&&a.fogMode!==0&&(t.setFloat4("vFogInfos",a.fogMode,a.fogStart,a.fogEnd,a.fogDensity),i?(a.fogColor.toLinearSpaceToRef(HA,a.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",HA)):t.setColor3("vFogColor",a.fogColor))}function o_(a,e,t){XA.NUM_MORPH_INFLUENCERS=t,pv(a,e,XA)}function pv(a,e,t){const i=t.NUM_MORPH_INFLUENCERS;if(i>0&&We.LastCreatedEngine){const s=We.LastCreatedEngine.getCaps().maxVertexAttribs,r=e.morphTargetManager;if(r!=null&&r.isUsingTextureForTargets)return;const n=r&&r.supportsNormals&&t.NORMAL,o=r&&r.supportsTangents&&t.TANGENT,l=r&&r.supportsUVs&&t.UV1;for(let h=0;hs&&U.Error("Cannot add more vertex attributes for mesh "+e.name)}}function bh(a,e=!1){a.push("world0"),a.push("world1"),a.push("world2"),a.push("world3"),e&&(a.push("previousWorld0"),a.push("previousWorld1"),a.push("previousWorld2"),a.push("previousWorld3"))}function Al(a,e){const t=a.morphTargetManager;!a||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function Gg(a,e){e.bindToEffect(a,"Scene")}function Oi(a,e,t){e._needUVs=!0,e[t]=!0,a.optimizeUVAllocation&&a.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=a.coordinatesIndex+1,e["MAINUV"+(a.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function wi(a,e,t){const i=a.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function _v(a,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&a.push("bakedVertexAnimationSettingsInstanced")}function DV(a,e){return e.set(a),e}function l_(a,e,t){if(!(!e||!a)&&(a.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(a.computeBonesUsingShaders=!1),a.useBones&&a.computeBonesUsingShaders&&a.skeleton)){const i=a.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureWidth")>-1){const s=i.getTransformMatrixTexture(a);e.setTexture("boneSampler",s),e.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{const s=i.getTransformMatrices(a);s&&(e.setMatrices("mBones",s),t&&a.getScene().prePassRenderer&&a.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[a.uniqueId]||(t.previousBones[a.uniqueId]=s.slice()),e.setMatrices("mPreviousBones",t.previousBones[a.uniqueId]),DV(s,t.previousBones[a.uniqueId])))}}}function mv(a,e,t,i,s,r=!0){a._bindLight(e,t,i,s,r)}function h_(a,e,t,i,s=4){const r=Math.min(e.lightSources.length,s);for(let n=0;n0&&(i.addCPUSkinningFallback(0,e),a.push("matricesIndices"),a.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(a.push("matricesIndicesExtra"),a.push("matricesWeightsExtra")))}function zg(a,e){(e.INSTANCES||e.THIN_INSTANCES)&&bh(a,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&a.push("instanceColor")}function xv(a,e,t=4,i=0){let s=0;for(let r=0;r0&&(s=i+r,e.addFallback(s,"LIGHT"+r)),a.SHADOWS||(a["SHADOW"+r]&&e.addFallback(i,"SHADOW"+r),a["SHADOWPCF"+r]&&e.addFallback(i,"SHADOWPCF"+r),a["SHADOWPCSS"+r]&&e.addFallback(i,"SHADOWPCSS"+r),a["SHADOWPOISSON"+r]&&e.addFallback(i,"SHADOWPOISSON"+r),a["SHADOWESM"+r]&&e.addFallback(i,"SHADOWESM"+r),a["SHADOWCLOSEESM"+r]&&e.addFallback(i,"SHADOWCLOSEESM"+r));return s++}function aP(a,e){return e.fogEnabled&&a.applyFog&&e.fogMode!==0}function Wg(a,e,t,i,s,r,n,o=!1){n._areMiscDirty&&(n.LOGARITHMICDEPTH=t,n.POINTSIZE=i,n.FOG=s&&aP(a,e),n.NONUNIFORMSCALING=a.nonUniformScaling,n.ALPHATEST=r,n.DECAL_AFTER_DETAIL=o)}function c_(a,e,t,i,s=4,r=!1){if(!t._areLightsDirty)return t._needNormals;let n=0;const o={needNormals:t._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(a.lightsEnabled&&!r){for(const h of e.lightSources)if(Tv(a,e,h,n,t,i,o),n++,n===s)break}t.SPECULARTERM=o.specularEnabled,t.SHADOWS=o.shadowEnabled;for(let h=n;h0&&(n.shadowEnabled=!0,o.prepareDefines(s,i))}}t.lightmapMode!=hi.LIGHTMAP_DEFAULT?(n.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+i]=!0,s["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==hi.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+i]=!1,s["LIGHTMAPNOSPECULAR"+i]=!1)}function Hg(a,e,t,i,s,r=null,n=!1){let o=cP(a,i);r!==!1&&(o=OV(t,a,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==s&&(i.INSTANCES=s,o=!0),i.THIN_INSTANCES!==n&&(i.THIN_INSTANCES=n,o=!0),o&&i.markAsUnprocessed()}function oP(a,e){if(a.useBones&&a.computeBonesUsingShaders&&a.skeleton){e.NUM_BONE_INFLUENCERS=a.numBoneInfluencers;const t=e.BONETEXTURE!==void 0;if(a.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=a.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;const i=a.getScene().prePassRenderer;if(i&&i.enabled){const s=i.excludedSkinnedMesh.indexOf(a)===-1;e.BONES_VELOCITY_ENABLED=s}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function lP(a,e){const t=a.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 NV(a,e){const t=a.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function Xg(a,e,t,i,s=!1,r=!0,n=!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&&a.isVerticesDataPresent("normal"),e._needNormals&&a.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?a.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){const o=a.useVertexColors&&a.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=a.hasVertexAlpha&&o&&r}return a.isVerticesDataPresent("instanceColor")&&(a.hasInstances||a.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&oP(a,e),s&&lP(a,e),n&&NV(a,e),!0}function Yg(a,e){if(a.activeCamera){const t=e.MULTIVIEW;e.MULTIVIEW=a.activeCamera.outputRenderTarget!==null&&a.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function hP(a,e,t){const i=e.ORDER_INDEPENDENT_TRANSPARENCY,s=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=a.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!a.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||s!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Ev(a,e,t){const i=e.PREPASS;if(!e._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(a.prePassRenderer&&a.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=a.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=a.prePassRenderer.generateNormalsInWorldSpace;for(let r=0;r{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||We.LastCreatedScene;s&&(this._scene=s,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||Z.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Ws(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=pe.ClockWiseSideOrientation:this.sideOrientation=pe.CounterClockWiseSideOrientation,this._uniformBuffer=new ze(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),pe.OnEventObservable.notifyObservers(this,gr.Created))}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 s=t.materialDefines;return s?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===pe.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===pe.MATERIAL_OPAQUE||this._transparencyMode===pe.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 s of i.subMeshes)if(s.getMaterial()===this)for(const r of s._drawWrappers)r&&this._materialContext===r.materialContext&&(r._wasPreviouslyReady=!1,r._wasPreviouslyUsingInstances=null,r._forceRebindOnNextCall=e)}e&&this.markAsDirty(pe.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(t??this.sideOrientation)===pe.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(gr.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._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,Gg(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 s=this._scene.getEngine();this._cachedDepthWriteState=s.getDepthWrite(),s.setDepthWrite(!1)}if(this.disableColorWrite){const s=this._scene.getEngine();this._cachedColorWriteState=s.getColorWrite(),s.setColorWrite(!1)}if(this.depthFunction!==0){const s=this._scene.getEngine();this._cachedDepthFunctionState=s.getDepthFunction()||0,s.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(gr.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(gr.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(gr.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),pe._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const s of this.pluginManager._plugins){const r=e.pluginManager.getPlugin(s.name);r&&s.copyTo(r)}}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,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const l=()=>{if(!this._scene||!this._scene.getEngine())return;const h=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new nn(0,0,0,1)),this._storeEffectOnSubMeshes){let c=!0,u=null;if(e.subMeshes){const d=new xr(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,r.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?u=d.effect.getCompilationError():(c=!1,setTimeout(l,16)))}c&&(this.allowShaderHotSwapping=o,u&&s&&s(u),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);r.clipPlane&&(n.clipPlane=h)};l()}forceCompilationAsync(e,t){return new Promise((i,s)=>{this.forceCompilation(e,()=>{i()},t,r=>{s(r)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(pe._DirtyCallbackArray.length=0,e&pe.TextureDirtyFlag&&pe._DirtyCallbackArray.push(pe._TextureDirtyCallBack),e&pe.LightDirtyFlag&&pe._DirtyCallbackArray.push(pe._LightsDirtyCallBack),e&pe.FresnelDirtyFlag&&pe._DirtyCallbackArray.push(pe._FresnelDirtyCallBack),e&pe.AttributesDirtyFlag&&pe._DirtyCallbackArray.push(pe._AttributeDirtyCallBack),e&pe.MiscDirtyFlag&&pe._DirtyCallbackArray.push(pe._MiscDirtyCallBack),e&pe.PrePassDirtyFlag&&pe._DirtyCallbackArray.push(pe._PrePassDirtyCallBack),pe._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(pe._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 s of i.subMeshes)if(s.getMaterial(!1)===this)for(const r of s._drawWrappers)!r||!r.defines||!r.defines.markAllAsDirty||this._materialContext===r.materialContext&&e(r.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(pe._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(pe._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(pe._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(pe._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(pe._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(pe._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(pe._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(pe._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(pe._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(pe._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==wo.BackwardCompatible){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 s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(gr.Disposed,this._eventInfo),this._parentContainer){const r=this._parentContainer.materials.indexOf(this);r>-1&&this._parentContainer.materials.splice(r,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(const r in this.meshMap){const n=this.meshMap[r];n&&(n.material=null,this.releaseVertexArrayObject(n,e))}else{const r=s.meshes;for(const n of r)n.material===this&&!n.sourceMesh&&(n.material=null,this.releaseVertexArrayObject(n,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 s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Pe.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 U.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null;const r=Z.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _ParsePlugins(e,t,i,s){var r;if(e.plugins)for(const n in e.plugins){const o=e.plugins[n];let l=(r=t.pluginManager)==null?void 0:r.getPlugin(o.name);if(!l){const h=Z.Instantiate("BABYLON."+n);h&&(l=new h(t))}l==null||l.parse(o,i,s)}}}pe.TriangleFillMode=0;pe.WireFrameFillMode=1;pe.PointFillMode=2;pe.PointListDrawMode=3;pe.LineListDrawMode=4;pe.LineLoopDrawMode=5;pe.LineStripDrawMode=6;pe.TriangleStripDrawMode=7;pe.TriangleFanDrawMode=8;pe.ClockWiseSideOrientation=0;pe.CounterClockWiseSideOrientation=1;pe.TextureDirtyFlag=1;pe.LightDirtyFlag=2;pe.FresnelDirtyFlag=4;pe.AttributesDirtyFlag=8;pe.MiscDirtyFlag=16;pe.PrePassDirtyFlag=32;pe.AllDirtyFlag=63;pe.MATERIAL_OPAQUE=0;pe.MATERIAL_ALPHATEST=1;pe.MATERIAL_ALPHABLEND=2;pe.MATERIAL_ALPHATESTANDBLEND=3;pe.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0;pe.MATERIAL_NORMALBLENDMETHOD_RNM=1;pe.OnEventObservable=new K;pe._AllDirtyCallBack=a=>a.markAllAsDirty();pe._ImageProcessingDirtyCallBack=a=>a.markAsImageProcessingDirty();pe._TextureDirtyCallBack=a=>a.markAsTexturesDirty();pe._FresnelDirtyCallBack=a=>a.markAsFresnelDirty();pe._MiscDirtyCallBack=a=>a.markAsMiscDirty();pe._PrePassDirtyCallBack=a=>a.markAsPrePassDirty();pe._LightsDirtyCallBack=a=>a.markAsLightDirty();pe._AttributeDirtyCallBack=a=>a.markAsAttributesDirty();pe._FresnelAndMiscDirtyCallBack=a=>{pe._FresnelDirtyCallBack(a),pe._MiscDirtyCallBack(a)};pe._TextureAndMiscDirtyCallBack=a=>{pe._TextureDirtyCallBack(a),pe._MiscDirtyCallBack(a)};pe._DirtyCallbackArray=[];pe._RunDirtyCallBacks=a=>{for(const e of pe._DirtyCallbackArray)e(a)};v([O()],pe.prototype,"id",void 0);v([O()],pe.prototype,"uniqueId",void 0);v([O()],pe.prototype,"name",void 0);v([O()],pe.prototype,"metadata",void 0);v([O()],pe.prototype,"checkReadyOnEveryCall",void 0);v([O()],pe.prototype,"checkReadyOnlyOnce",void 0);v([O()],pe.prototype,"state",void 0);v([O("alpha")],pe.prototype,"_alpha",void 0);v([O("backFaceCulling")],pe.prototype,"_backFaceCulling",void 0);v([O("cullBackFaces")],pe.prototype,"_cullBackFaces",void 0);v([O()],pe.prototype,"sideOrientation",void 0);v([O("alphaMode")],pe.prototype,"_alphaMode",void 0);v([O()],pe.prototype,"_needDepthPrePass",void 0);v([O()],pe.prototype,"disableDepthWrite",void 0);v([O()],pe.prototype,"disableColorWrite",void 0);v([O()],pe.prototype,"forceDepthWrite",void 0);v([O()],pe.prototype,"depthFunction",void 0);v([O()],pe.prototype,"separateCullingPass",void 0);v([O("fogEnabled")],pe.prototype,"_fogEnabled",void 0);v([O()],pe.prototype,"pointSize",void 0);v([O()],pe.prototype,"zOffset",void 0);v([O()],pe.prototype,"zOffsetUnits",void 0);v([O()],pe.prototype,"pointsCloud",null);v([O()],pe.prototype,"fillMode",null);v([O()],pe.prototype,"useLogarithmicDepth",null);v([O()],pe.prototype,"transparencyMode",null);class Sl extends pe{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=(...s)=>{const r=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._markAllSubMeshesAsTexturesDirty(),n}}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&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Sl(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Gt&&Gt.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(s=>i.subMaterials.push(t.getLastMaterialById(s))),i}}H("BABYLON.MultiMaterial",Sl);class wV{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class uP{}class FV{constructor(){this.visibleInstances={},this.batchCache=new YA,this.batchCacheReplacementModeInFrozenMode=new YA,this.instancesBufferSize=32*16*4}}class YA{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class LV{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=32*16,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class BV{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 q extends Ft{static _GetDefaultSideOrientation(e){return e||q.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(P.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(P.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 K),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new K),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new K),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new K),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new K),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 overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new BV,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new FV,this._thinInstanceDataStorage=new LV,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=q.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(o,l,h)=>{o&&h&&(this._uniformBuffer?this.transferToEffect(l):h.bindOnlyWorldMatrix(l))},s){if(s._geometry&&s._geometry.applyToMesh(this),Tr.DeepCopy(s,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=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const o=s._ranges;for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&o[l]&&this.createAnimationRange(l,o[l].from,o[l].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Gt&&Gt.HasTags(s)&&Gt.AddTagsTo(this,Gt.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const o=s.getDescendants(!0);for(let l=0;l{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 K(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=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));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const r of this.getChildTransformNodes(!0))r.getClassName()==="InstancedMesh"&&s.getClassName()==="Mesh"&&r.sourceMesh===this?r.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):r.instantiateHierarchy(s,t,i);return s}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 U.Warn("You cannot use a mesh as LOD level twice"),this;const i=new wV(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*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n){if(n._storeEffectOnSubMeshes)for(const f of this.subMeshes){const m=f.getMaterial();if(m){if(m._storeEffectOnSubMeshes){if(!m.isReadyForSubMesh(this,f,r))return!1}else if(!m.isReady(this,r))return!1}}else if(!n.isReady(this,r))return!1}const o=i.currentRenderPassId;for(const f of this.lightSources){const m=f.getShadowGenerators();if(!m)continue;const _=m.values();for(let x=_.next();x.done!==!0;x=_.next()){const E=x.value;if(E&&(!((l=E.getShadowMap())!=null&&l.renderList)||(h=E.getShadowMap())!=null&&h.renderList&&((u=(c=E.getShadowMap())==null?void 0:c.renderList)==null?void 0:u.indexOf(this))!==-1)){const C=E.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let y=0;y0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const n of this.subMeshes){if(n.indexStart+n.indexCount>s){r=!0;break}if(n.verticesStart+n.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new xr(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)xr.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const r=new Se;r.set(t,e);const n=this.getScene();new Is(Is.RandomId(),n,r,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=Is.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(P.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(P.PositionKind,i,!1,!1),t){const s=this.getIndices(),r=this.getVerticesData(P.NormalKind);if(!r)return this;Se.ComputeNormals(i,s,r),this.updateVerticesData(P.NormalKind,r,!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(Is.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Is(Is.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const s=new Se;s.indices=e;const r=this.getScene();new Is(Is.RandomId(),r,s,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,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t);let n;if(this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case pe.PointFillMode:n=null;break;case pe.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case pe.TriangleFillMode:n=this._geometry.getIndexBuffer();break}return!s||!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,n):this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),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 r=this.getScene().getEngine();return this._unIndexed||t==pe.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==pe.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.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(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const o=this._instanceDataStorage.visibleInstances,l=i.getRenderId(),h=s?o.intermediateDefaultRenderId:o.defaultRenderId;n.visibleInstances[e]=o[l],!n.visibleInstances[e]&&h&&(n.visibleInstances[e]=o[h])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&n.visibleInstances[e]!==null&&n.visibleInstances[e]!==void 0,this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){var S;const n=i.visibleInstances[e._id],o=n?n.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize;let c=l.instancesBuffer,u=l.instancesPreviousBuffer;const f=(o+1)*16*4;for(;l.instancesBufferSizeA._distanceToCamera>I._distanceToCamera?-1:A._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=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=s.getEngine();let h=0,c=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(h=s.activeCamera.maxZ,c=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const u=e.getRenderingMesh(),d=o.hardwareInstancedRendering[e._id]||u.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,f=this._instanceDataStorage,m=e.getMaterial();if(!m)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;if(!f.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==m){if(m._storeEffectOnSubMeshes){if(!m.isReadyForSubMesh(this,e,d))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this}else if(!m.isReady(this,d))return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=m}else if(m._storeEffectOnSubMeshes&&!((N=e._drawWrapper)!=null&&N._wasPreviouslyReady)||!m._storeEffectOnSubMeshes&&!m._getDrawWrapper()._wasPreviouslyReady)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;t&&l.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let _;this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?_=e._drawWrapper:_=this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const x=(_==null?void 0:_.effect)??null;for(const k of s._beforeRenderingMeshStage)k.action(this,e,o,x);if(!_||!x)return c&&(c.maxZ=h,s.updateTransformMatrix(!0)),this;const E=i||this;let S;if(!f.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||this.overrideMaterialSideOrientation!==null||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){const k=E._getWorldMatrixDeterminant();S=this.overrideMaterialSideOrientation,S==null&&(S=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),k<0&&(S=S===pe.ClockWiseSideOrientation?pe.CounterClockWiseSideOrientation:pe.ClockWiseSideOrientation),f.sideOrientation=S}else S=f.sideOrientation;const C=this._internalMeshDataInfo._effectiveMaterial._preBind(_,S);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&l.setDepthWrite(!0);const y=this._internalMeshDataInfo._effectiveMaterial,A=y.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),d||this._bind(e,x,A,!1);const I=E.getWorldMatrix();y._storeEffectOnSubMeshes?y.bindForSubMesh(I,this,e):y.bind(I,this),!y.backFaceCulling&&y.separateCullingPass&&(l.setState(!0,y.zOffset,!1,!C,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._processRendering(this,e,x,A,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),l.setState(!0,y.zOffset,!1,C,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,x,A,o,d,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const k of s._afterRenderingMeshStage)k.action(this,e,o,x);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),c&&(c.maxZ=h,s.updateTransformMatrix(!0)),s.performancePriority===wo.Aggressive&&!f.isFrozen&&this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(P.MatricesWeightsKind)&&(this.isVerticesDataPresent(P.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(P.MatricesWeightsKind),t=e.length;for(let i=0;iE&&s++,A!==0&&C++,S+=A,E=A}if(h[C]++,C>n&&(n=C),S===0)r++;else{const y=1/S;let A=0;for(let I=0;Ic&&o++}}const u=this.skeleton.bones.length,d=this.getVerticesData(P.MatricesIndicesKind),f=this.getVerticesData(P.MatricesIndicesExtraKind);let m=0;for(let x=0;x=u||S<0)&&m++}const _="Number of Weights = "+i/4+` +Maximum influences = `+n+` +Missing Weights = `+r+` +Not Sorted = `+s+` +Not Normalized = `+o+` +WeightCounts = [`+h+`] +Number of bones = `+u+` +Bad Bone Indices = `+m;return{skinned:!0,valid:r===0&&o===0&&m===0,report:_}}_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 Z.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this),this.instances.forEach(s=>{s.refreshBoundingInfo(),s._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 s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[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(P.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(P.PositionKind);const s=T.Zero();let r;for(r=0;r{const d=u.width,f=u.height,_=this.getEngine().createCanvas(d,f).getContext("2d");_.drawImage(u,0,0);const x=_.getImageData(0,0,d,f).data;this.applyDisplacementMapFromBuffer(x,d,f,t,i,r,n,o),s&&s(this)};return Z.LoadImage(e,c,l||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,l=!1){if(!this.isVerticesDataPresent(P.PositionKind)||!this.isVerticesDataPresent(P.NormalKind)||!this.isVerticesDataPresent(P.UVKind))return U.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(P.PositionKind,!0,!0),c=this.getVerticesData(P.NormalKind),u=this.getVerticesData(P.UVKind);let d=T.Zero();const f=T.Zero(),m=ce.Zero();n=n||ce.Zero(),o=o||new ce(1,1);for(let _=0;_{const h=new Float32Array(i.length*l);let c=0;for(let u=0;u{const o=s.length-1-n,l=s[o];for(let h=0;h{for(let o=0;o-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId!==void 0&&e.skeletonId!==null&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let r=0;r4,h=l?this.getVerticesData(P.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(P.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=T.Zero(),f=new L,m=new L;let _=0,x;for(let E=0;E0&&(L.FromFloat32ArrayToRefScaled(u,Math.floor(n[_+x]*16),S,m),f.addToSelf(m));if(l)for(x=0;x<4;x++)S=c[_+x],S>0&&(L.FromFloat32ArrayToRefScaled(u,Math.floor(h[_+x]*16),S,m),f.addToSelf(m));T.TransformCoordinatesFromFloatsToRef(i._sourcePositions[E],i._sourcePositions[E+1],i._sourcePositions[E+2],f,d),d.toArray(s,E),t&&(T.TransformNormalFromFloatsToRef(i._sourceNormals[E],i._sourceNormals[E+1],i._sourceNormals[E+2],f,d),d.toArray(r,E)),f.reset()}return this.updateVerticesData(P.PositionKind,s),t&&this.updateVerticesData(P.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach(function(s){const n=s.getBoundingInfo().boundingBox;!t||!i?(t=n.minimumWorld,i=n.maximumWorld):(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld))}),!t||!i?{min:T.Zero(),max:T.Zero()}:{min:t,max:i}}static Center(e){const t=e instanceof Array?q.MinMax(e):e;return T.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return dv(q._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return qI(q._MergeMeshesCoroutine(e,t,i,s,r,n,!0),SV())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let R=0;for(l=0;l=65536)return U.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const h=new Array,c=new Array,u=new Array,d=e[0].overrideMaterialSideOrientation;for(l=0;l{const N=R.computeWorldMatrix(!0);return{vertexData:Se.ExtractFromMesh(R,!1,!1),transform:N}},{vertexData:_,transform:x}=m(f);o&&(yield);const E=new Array(e.length-1);for(let R=1;R{throw ot("GroundMesh")};q._GoldbergMeshParser=(a,e)=>{throw ot("GoldbergMesh")};q._LinesMeshParser=(a,e)=>{throw ot("LinesMesh")};q._GreasedLineMeshParser=(a,e)=>{throw ot("GreasedLineMesh")};q._GreasedLineRibbonMeshParser=(a,e)=>{throw ot("GreasedLineRibbonMesh")};q._TrailMeshParser=(a,e)=>{throw ot("TrailMesh")};H("BABYLON.Mesh",q);q._instancedMeshFactory=(a,e)=>{const t=new vv(a,e);if(e.instancedBuffers){t.instancedBuffers={};for(const i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};class vv extends Ft{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&&Z.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&&Z.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&&Z.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&&Z.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||U.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)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),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;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||U.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!==ut.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new L);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,W.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(W.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 s=i.next();s.done!==!0;s=i.next())s.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=yt.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Pe.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Pe.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)})),Pe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const s=Qt.Construct("Light_Type_"+e,t,i);return s||null}static Parse(e,t){const i=yt.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Pe.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(s.falloffType=e.falloffType),e.lightmapMode!==void 0&&(s.lightmapMode=e.lightmapMode),e.animations){for(let r=0;r{const r=t.apply(e,s);for(const n of s)n._resyncLightSource(this);return r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);for(const o of n)o._resyncLightSource(this);return n};for(const s of e)s._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const r=t.apply(e,s);return this._resyncMeshes(),r};const i=e.splice;e.splice=(s,r)=>{const n=i.apply(e,[s,r]);return this._resyncMeshes(),n},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===yt.INTENSITYMODE_AUTOMATIC&&(t===yt.LIGHTTYPEID_DIRECTIONALLIGHT?i=yt.INTENSITYMODE_ILLUMINANCE:i=yt.INTENSITYMODE_LUMINOUSINTENSITY),t){case yt.LIGHTTYPEID_POINTLIGHT:case yt.LIGHTTYPEID_SPOTLIGHT:switch(i){case yt.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case yt.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case yt.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case yt.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case yt.INTENSITYMODE_ILLUMINANCE:e=1;break;case yt.INTENSITYMODE_LUMINANCE:{let s=this.radius;s=Math.max(s,.001),e=2*Math.PI*(1-Math.cos(s));break}}break;case yt.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){const e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}yt.FALLOFF_DEFAULT=hi.FALLOFF_DEFAULT;yt.FALLOFF_PHYSICAL=hi.FALLOFF_PHYSICAL;yt.FALLOFF_GLTF=hi.FALLOFF_GLTF;yt.FALLOFF_STANDARD=hi.FALLOFF_STANDARD;yt.LIGHTMAP_DEFAULT=hi.LIGHTMAP_DEFAULT;yt.LIGHTMAP_SPECULAR=hi.LIGHTMAP_SPECULAR;yt.LIGHTMAP_SHADOWSONLY=hi.LIGHTMAP_SHADOWSONLY;yt.INTENSITYMODE_AUTOMATIC=hi.INTENSITYMODE_AUTOMATIC;yt.INTENSITYMODE_LUMINOUSPOWER=hi.INTENSITYMODE_LUMINOUSPOWER;yt.INTENSITYMODE_LUMINOUSINTENSITY=hi.INTENSITYMODE_LUMINOUSINTENSITY;yt.INTENSITYMODE_ILLUMINANCE=hi.INTENSITYMODE_ILLUMINANCE;yt.INTENSITYMODE_LUMINANCE=hi.INTENSITYMODE_LUMINANCE;yt.LIGHTTYPEID_POINTLIGHT=hi.LIGHTTYPEID_POINTLIGHT;yt.LIGHTTYPEID_DIRECTIONALLIGHT=hi.LIGHTTYPEID_DIRECTIONALLIGHT;yt.LIGHTTYPEID_SPOTLIGHT=hi.LIGHTTYPEID_SPOTLIGHT;yt.LIGHTTYPEID_HEMISPHERICLIGHT=hi.LIGHTTYPEID_HEMISPHERICLIGHT;v([Vi()],yt.prototype,"diffuse",void 0);v([Vi()],yt.prototype,"specular",void 0);v([O()],yt.prototype,"falloffType",void 0);v([O()],yt.prototype,"intensity",void 0);v([O()],yt.prototype,"range",null);v([O()],yt.prototype,"intensityMode",null);v([O()],yt.prototype,"radius",null);v([O()],yt.prototype,"_renderPriority",void 0);v([_e("_reorderLightsInScene")],yt.prototype,"renderPriority",void 0);v([O("shadowEnabled")],yt.prototype,"_shadowEnabled",void 0);v([O("excludeWithLayerMask")],yt.prototype,"_excludeWithLayerMask",void 0);v([O("includeOnlyWithLayerMask")],yt.prototype,"_includeOnlyWithLayerMask",void 0);v([O("lightmapMode")],yt.prototype,"_lightmapMode",void 0);class UV extends xs{}class VV{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 Kg extends xs{constructor(e){super(),this._wasAddedToScene=!1,e=e||We.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,h=i.dependsOn.get(l);if(o instanceof vv){const u=o.sourceMesh;t.has(u.uniqueId)&&(h.add(u.uniqueId),i.dependedBy.get(u.uniqueId).add(l))}const c=i.dependedBy.get(l);for(const u of o.getDescendants()){const d=u.uniqueId;t.has(d)&&(c.add(d),i.dependsOn.get(d).add(l))}}const s=[],r=[];for(const o of e){const l=o.uniqueId;i.dependsOn.get(l).size===0&&(r.push(o),t.delete(l))}const n=r;for(;n.length>0;){const o=n.shift();s.push(o);const l=i.dependedBy.get(o.uniqueId);for(const h of Array.from(l.values())){const c=i.dependsOn.get(h);c.delete(o.uniqueId),c.size===0&&t.get(h)&&(n.push(t.get(h)),t.delete(h))}}return t.size>0&&(U.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>U.Error(o.name))),s}_addNodeAndDescendantsToList(e,t,i,s){if(!(!i||s&&!s(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Ft&&this.meshes.indexOf(e)!==-1||e instanceof ut&&this.transformNodes.indexOf(e)!==-1||e instanceof yt&&this.lights.indexOf(e)!==-1||e instanceof Ve&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return U.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 U.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 U.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 U.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Z.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new VV,o=[],l=[],h={doNotInstantiate:!0,...i},c=(_,x)=>{if(s[_.uniqueId]=x.uniqueId,r[x.uniqueId]=x,e&&(x.name=e(_.name)),x instanceof q){const E=x;if(E.morphTargetManager){const S=_.morphTargetManager;E.morphTargetManager=S.clone();for(let C=0;C{if(c(_,x),_.parent){const E=s[_.parent.uniqueId],S=r[E];S?x.parent=S:x.parent=_.parent}if(x.position&&_.position&&x.position.copyFrom(_.position),x.rotationQuaternion&&_.rotationQuaternion&&x.rotationQuaternion.copyFrom(_.rotationQuaternion),x.rotation&&_.rotation&&x.rotation.copyFrom(_.rotation),x.scaling&&_.scaling&&x.scaling.copyFrom(_.scaling),x.material){const E=x;if(E.material)if(t){const S=_.material;if(l.indexOf(S)===-1){let C=S.clone(e?e(S.name):"Clone of "+S.name);if(l.push(S),s[S.uniqueId]=C.uniqueId,r[C.uniqueId]=C,S.getClassName()==="MultiMaterial"){const y=S;for(const A of y.subMaterials)A&&(C=A.clone(e?e(A.name):"Clone of "+A.name),l.push(A),s[A.uniqueId]=C.uniqueId,r[C.uniqueId]=C);y.subMaterials=y.subMaterials.map(A=>A&&r[s[A.uniqueId]])}}E.getClassName()!=="InstancedMesh"&&(E.material=r[s[S.uniqueId]])}else E.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(E.material)===-1&&this.scene.addMultiMaterial(E.material):this.scene.materials.indexOf(E.material)===-1&&this.scene.addMaterial(E.material)}x.parent===null&&n.rootNodes.push(x)};return f.forEach(_=>{if(_.getClassName()==="InstancedMesh"){const x=_,E=x.sourceMesh,S=s[E.uniqueId],y=(typeof S=="number"?r[S]:E).createInstance(x.name);m(x,y)}else{let x=!0;_.getClassName()==="TransformNode"||_.getClassName()==="Node"||_.skeleton||!_.getTotalVertices||_.getTotalVertices()===0?x=!1:h.doNotInstantiate&&(typeof h.doNotInstantiate=="function"?x=!h.doNotInstantiate(_):x=!h.doNotInstantiate);const E=x?_.createInstance(`instance of ${_.name}`):_.clone(`Clone of ${_.name}`,null,!0);if(!E)throw new Error(`Could not clone or instantiate node on Asset Container ${_.name}`);m(_,E)}}),this.skeletons.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const x=_.clone(e?e(_.name):"Clone of "+_.name);for(const E of this.meshes)if(E.skeleton===_&&!E.isAnInstance){const S=r[s[E.uniqueId]];if(!S||S.isAnInstance||(S.skeleton=x,o.indexOf(x)!==-1))continue;o.push(x);for(const C of x.bones)C._linkedTransformNode&&(C._linkedTransformNode=r[s[C._linkedTransformNode.uniqueId]])}n.skeletons.push(x)}),this.animationGroups.forEach(_=>{if(h.predicate&&!h.predicate(_))return;const x=_.clone(e?e(_.name):"Clone of "+_.name,E=>r[s[E.uniqueId]]||E);n.animationGroups.push(x)}),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Z.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()||Z.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 s of e){let r=!0;if(i){for(const n of i)if(s===n){r=!1;break}}r&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new UV);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 q("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=We.LastCreatedScene,t,i=null){if(!e)return U.Error("No scene available to merge animations to"),[];const s=i||(o=>{let l=null;const h=o.animations.length?o.animations[0].targetProperty:"",c=o.name.split(".").join("").split("_primitive")[0];switch(h){case"position":case"rotationQuaternion":l=e.getTransformNodeByName(o.name)||e.getTransformNodeByName(c);break;case"influence":l=e.getMorphTargetByName(o.name)||e.getMorphTargetByName(c);break;default:l=e.getNodeByName(o.name)||e.getNodeByName(c)}return l});this.getNodes().forEach(o=>{const l=s(o);if(l!==null){for(const h of o.animations){const c=l.animations.filter(u=>u.targetProperty===h.targetProperty);for(const u of c){const d=l.animations.indexOf(u,0);d>-1&&l.animations.splice(d,1)}}l.animations=l.animations.concat(o.animations)}});const n=[];return this.animationGroups.slice().forEach(o=>{n.push(o.clone(o.name,s)),o.animatables.forEach(l=>{l.stop()})}),t.forEach(o=>{const l=s(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))}),n}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 s=t.pop();if(s instanceof q?(s.geometry&&this.geometries.indexOf(s.geometry)===-1&&this.geometries.push(s.geometry),this.meshes.push(s)):s instanceof ut?this.transformNodes.push(s):s instanceof yt?this.lights.push(s):s instanceof Ve&&this.cameras.push(s),s instanceof Ft){if(s.material&&this.materials.indexOf(s.material)===-1){this.materials.push(s.material);for(const r of s.material.getActiveTextures())this.textures.indexOf(r)===-1&&this.textures.push(r)}s.skeleton&&this.skeletons.indexOf(s.skeleton)===-1&&this.skeletons.push(s.skeleton),s.morphTargetManager&&this.morphTargetManagers.indexOf(s.morphTargetManager)===-1&&this.morphTargetManagers.push(s.morphTargetManager)}for(const r of s.getChildren())i.has(r)||t.push(r);i.add(s)}this.populateRootNodes()}}class no{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=ee.audioEngine)!=null&&e.audioContext&&(this.isPlaying||this.isPaused)){const t=this.isPaused?0:ee.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,s=null,r){var n;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 K,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=T.Zero(),this._localDirection=new T(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||We.LastCreatedScene,!!i)if(this._scene=i,no._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(o,l,h,c,u)=>l0&&(h=!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 c=0;c{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(u,d=>{this._soundLoaded(d)},void 0,!0,!0,d=>{d&&U.Error("XHR "+d.status+" error on: "+u+"."),U.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:o=!1;break}o?h||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):U.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch{U.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),ee.audioEngine&&!ee.audioEngine.WarnedWebAudioUnsupported&&(U.Error("Web Audio is not supported by your browser."),ee.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(e=ee.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=ee.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=ee.audioEngine)!=null&&t.audioContext&&ee.audioEngine.audioContext.decodeAudioData(e,i=>{this._audioBufferLoaded(i)},i=>{U.Error("Error while decoding audio data for: "+this.name+" / Error: "+i)})}setAudioBuffer(e){var t;(t=ee.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=ee.audioEngine)!=null&&e.canUseWebAudio&&ee.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??ee.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=ee.audioEngine)!=null&&e.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(t=ee.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 h=()=>{var c,u;if((c=ee.audioEngine)!=null&&c.unlocked){const d=this._htmlAudioElement.play();d!==void 0&&d.catch(()=>{var f,m;(f=ee.audioEngine)==null||f.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(m=ee.audioEngine)==null?void 0:m.onAudioUnlockedObservable.addOnce(()=>{h()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=(u=ee.audioEngine)==null?void 0:u.onAudioUnlockedObservable.addOnce(()=>{h()}))};h()}}else{const h=()=>{var c,u,d;if((c=ee.audioEngine)!=null&&c.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=(u=ee.audioEngine)==null?void 0:u.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=ee.audioEngine)==null?void 0:d.audioContext.currentTime)+e:ee.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=ee.audioEngine)==null?void 0:o.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var c;((c=ee.audioEngine)==null?void 0:c.audioContext.state)==="suspended"?(ee.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=ee.audioEngine.onAudioUnlockedObservable.addOnce(()=>{h()}))):h()},500):h()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(l){U.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=ee.audioEngine)!=null&&t.audioContext&&this._soundSource){const i=e?ee.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=ee.audioEngine)!=null&&e.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=ee.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(i=ee.audioEngine)!=null&&i.canUseWebAudio&&this._soundGain&&(t&&ee.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(ee.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,ee.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,ee.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 s=e.getBoundingInfo();this.setPosition(s.boundingSphere.centerWorld)}(t=ee.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 no(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,s){const r=e.name;let n;e.url?n=i+e.url:n=i+r;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(!s)l=new no(r,n,t,()=>{t.removePendingData(l)},o),t.addPendingData(l);else{const h=()=>{s._isReadyToPlay?(l._audioBuffer=s.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(h,300)};l=new no(r,new ArrayBuffer(0),t,null,o),h()}if(e.position){const h=T.FromArray(e.position);l.setPosition(h)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const h=T.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(h)}if(e.connectedMeshId){const h=t.getMeshById(e.connectedMeshId);h&&l.attachToMesh(h)}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=ee.audioEngine)==null||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}no._SceneComponentInitialization=a=>{throw ot("AudioSceneComponent")};class kV{constructor(e,t={}){this.id=-1,this._isInitialized=!1,e=e||We.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=ee.audioEngine)!=null&&e.canUseWebAudio&&ee.audioEngine.audioContext&&(this._outputAudioNode=ee.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(ee.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(ee.audioEngine&&ee.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=ee.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=ee.audioEngine)!=null&&t.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if((e=ee.audioEngine)!=null&&e.canUseWebAudio)for(let t=0;t{var n;let s=[],r;if(t.sounds=t.sounds||[],a.sounds!==void 0&&a.sounds!==null)for(let o=0,l=a.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&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const n=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(n.x||0,n.y||0,n.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const n=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(n.x||0,n.y||0,n.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),T.TransformNormalToRef(Sn._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 r;for(r=0;r{let e=a._getComponent(ve.NAME_AUDIO);e||(e=new Sn(a),a._addComponent(e))};class GV{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 s=0;for(const n of i)s+=n;const r=s>0?1/s:0;for(let n=0;n{this._onended()})}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee,this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse(()=>this,e,t,i)}}v([Dt(),_e("_markSubMeshesAsAttributesDirty")],hf.prototype,"texture",void 0);v([O(),_e("_markSubMeshesAsAttributesDirty")],hf.prototype,"isEnabled",void 0);v([O()],hf.prototype,"animationParameters",void 0);v([O()],hf.prototype,"time",void 0);class Zh{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=aa.Zero(),this._cachedBaseSize=aa.Zero(),this._initialSamplingMode=2,this._texture=Zh._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)}}class Kt extends Zh{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=La()),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=Kt.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 K,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Kt._IsScene(e)?this._scene=e:this._engine=e:this._scene=We.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 L.IdentityReadOnly}getReflectionTextureMatrix(){return L.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const l=o._getUseSRGBBuffer(!!r,t),h=o.getLoadedTexturesCache();for(let c=0;c=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=Pe.Serialize(this);return Pe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let s=0;s{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}}Kt.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;v([O()],Kt.prototype,"uniqueId",void 0);v([O()],Kt.prototype,"name",void 0);v([O()],Kt.prototype,"metadata",void 0);v([O("hasAlpha")],Kt.prototype,"_hasAlpha",void 0);v([O("getAlphaFromRGB")],Kt.prototype,"_getAlphaFromRGB",void 0);v([O()],Kt.prototype,"level",void 0);v([O("coordinatesIndex")],Kt.prototype,"_coordinatesIndex",void 0);v([O()],Kt.prototype,"optimizeUVAllocation",void 0);v([O("coordinatesMode")],Kt.prototype,"_coordinatesMode",void 0);v([O()],Kt.prototype,"wrapU",null);v([O()],Kt.prototype,"wrapV",null);v([O()],Kt.prototype,"wrapR",void 0);v([O()],Kt.prototype,"anisotropicFilteringLevel",void 0);v([O()],Kt.prototype,"isCube",null);v([O()],Kt.prototype,"is3D",null);v([O()],Kt.prototype,"is2DArray",null);v([O()],Kt.prototype,"gammaSpace",null);v([O()],Kt.prototype,"invertZ",void 0);v([O()],Kt.prototype,"lodLevelInAlpha",void 0);v([O()],Kt.prototype,"lodGenerationOffset",null);v([O()],Kt.prototype,"lodGenerationScale",null);v([O()],Kt.prototype,"linearSpecularLOD",null);v([Dt()],Kt.prototype,"irradianceTexture",null);v([O()],Kt.prototype,"isRenderTarget",void 0);function dP(a,e,t=!1){const i=e.width,s=e.height;if(a instanceof Float32Array){let h=a.byteLength/a.BYTES_PER_ELEMENT;const c=new Uint8Array(h);for(;--h>=0;){let u=a[h];u<0?u=0:u>1&&(u=1),c[h]=u*255}a=c}const r=document.createElement("canvas");r.width=i,r.height=s;const n=r.getContext("2d");if(!n)return null;const o=n.createImageData(i,s);if(o.data.set(a),n.putImageData(o,0,0),t){const h=document.createElement("canvas");h.width=i,h.height=s;const c=h.getContext("2d");return c?(c.translate(0,s),c.scale(1,-1),c.drawImage(r,0,0),h.toDataURL("image/png")):null}return r.toDataURL("image/png")}function zV(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=a._readPixelsSync(e,t);return s?dP(s,a.getSize(),i.invertY):null}async function WV(a,e=0,t=0){const i=a.getInternalTexture();if(!i)return null;const s=await a.readPixels(e,t);return s?dP(s,a.getSize(),i.invertY):null}class X extends Kt{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=X.TRILINEAR_SAMPLINGMODE,o={},l,h=5){throw ot("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,s,r=X.TRILINEAR_SAMPLINGMODE,n=null,o=null,l=null,h=!1,c,u,d,f,m){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 K,this._isBlocking=!0,this.name=e||"",this.url=e;let _,x=!1,E=null,S=!0;typeof i=="object"&&i!==null?(_=i.noMipmap??!1,s=i.invertY??!Ht.UseOpenGLOrientationForUV,r=i.samplingMode??X.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,l=i.buffer??null,h=i.deleteBuffer??!1,c=i.format,u=i.mimeType,d=i.loaderOptions,f=i.creationFlags,x=i.useSRGBBuffer??!1,E=i.internalTexture??null,S=i.gammaSpace??S):_=!!i,this._gammaSpace=S,this._noMipmap=_,this._invertY=s===void 0?!Ht.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=l,this._deleteBuffer=h,this._mimeType=u,this._loaderOptions=d,this._creationFlags=f,this._useSRGBBuffer=x,this._forcedExtension=m,c&&(this._format=c);const C=this.getScene(),y=this._getEngine();if(!y)return;y.onBeforeTextureInitObservable.notifyObservers(this);const A=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&C&&C.resetCachedMaterial()},I=(R,N)=>{this._loadingError=!0,this._errorObject={message:R,exception:N},o&&o(R,N),X.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!E){this._delayedOnLoad=A,this._delayedOnError=I;return}if(this._texture=E??this._getFromCache(this.url,_,r,this._invertY,x,this.isCube),this._texture)if(this._texture.isReady)Eu.SetImmediate(()=>A());else{const R=this._texture.onLoadedObservable.add(A);this._texture.onErrorObservable.add(N=>{var k;I(N.message,N.exception),(k=this._texture)==null||k.onLoadedObservable.remove(R)})}else if(!C||!C.useDelayedTextureLoading){try{this._texture=y.createTexture(this.url,_,this._invertY,C,r,A,I,this._buffer,void 0,this._format,this._forcedExtension,u,d,f,x)}catch(R){throw I("error loading",R),R}h&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=A,this._delayedOnError=I}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,r=>r.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,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?Eu.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,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,T.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.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=L.Zero(),this._rowGenerationMatrix=new L,this._t0=T.Zero(),this._t1=T.Zero(),this._t2=T.Zero()),L.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(L.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,W.Matrix[0]),L.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,W.Matrix[1]),L.ScalingToRef(this._cachedUScale,this._cachedVScale,0,W.Matrix[2]),L.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,W.Matrix[3]),W.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(W.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(W.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(W.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),L.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,s=>s.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===X.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=L.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=L.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 X.PLANAR_MODE:{L.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 X.PROJECTION_MODE:{L.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:L.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 Pe.Clone(()=>new X(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i;const e=this.name;X.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(X._SerializeInternalTextureUniqueId);return t?((X.SerializeBuffers||X.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,"+TI(this._buffer):(X.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?zV(this):WV(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,X._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 h=np.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&h.updateSamplingMode&&h._samplingMode&&h._samplingMode!==e.samplingMode&&h.updateSamplingMode(e.samplingMode),h}if(e.isCube&&!e.isRenderTarget)return X._CubeTextureParser(e,t,i);const s=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const l=t.getEngine().getLoadedTexturesCache();for(const h of l)if(h.uniqueId===e.internalTextureUniqueId){r=h;break}}const n=l=>{var h;if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){const c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c{let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const h=X._CreateMirror(e.name,e.renderTargetSize,t,l);return h._waitingRenderList=e.renderList,h.mirrorPlane=nn.FromArray(e.mirrorPlane),n(h),h}else if(e.isRenderTarget){let h=null;if(e.isCube){if(t.reflectionProbes)for(let c=0;c{n(h)},e._creationFlags??0,e._useSRGBBuffer??!1),h.name=e.name;else{let c;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?c=e.name:c=i+e.name,e.url&&(e.url.startsWith("data:")||X.UseSerializedUrlIfAny)&&(c=e.url);const u={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(h)},internalTexture:r};h=new X(c,t,u)}return h}},e,t)}static CreateFromBase64String(e,t,i,s,r,n=X.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c,u){return new X("data:"+t,i,s,r,n,o,l,e,!1,h,void 0,void 0,c,u)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=X.TRILINEAR_SAMPLINGMODE,l=null,h=null,c=5,u,d){return e.substr(0,5)!=="data:"&&(e="data:"+e),new X(e,i,r,n,o,l,h,t,s,c,void 0,void 0,u,d)}}X.SerializeBuffers=!0;X.ForceSerializeBuffers=!1;X.OnTextureLoadErrorObservable=new K;X._SerializeInternalTextureUniqueId=!1;X._CubeTextureParser=(a,e,t)=>{throw ot("CubeTexture")};X._CreateMirror=(a,e,t,i)=>{throw ot("MirrorTexture")};X._CreateRenderTargetTexture=(a,e,t,i,s)=>{throw ot("RenderTargetTexture")};X.NEAREST_SAMPLINGMODE=1;X.NEAREST_NEAREST_MIPLINEAR=8;X.BILINEAR_SAMPLINGMODE=2;X.LINEAR_LINEAR_MIPNEAREST=11;X.TRILINEAR_SAMPLINGMODE=3;X.LINEAR_LINEAR_MIPLINEAR=3;X.NEAREST_NEAREST_MIPNEAREST=4;X.NEAREST_LINEAR_MIPNEAREST=5;X.NEAREST_LINEAR_MIPLINEAR=6;X.NEAREST_LINEAR=7;X.NEAREST_NEAREST=1;X.LINEAR_NEAREST_MIPNEAREST=9;X.LINEAR_NEAREST_MIPLINEAR=10;X.LINEAR_LINEAR=2;X.LINEAR_NEAREST=12;X.EXPLICIT_MODE=0;X.SPHERICAL_MODE=1;X.PLANAR_MODE=2;X.CUBIC_MODE=3;X.PROJECTION_MODE=4;X.SKYBOX_MODE=5;X.INVCUBIC_MODE=6;X.EQUIRECTANGULAR_MODE=7;X.FIXED_EQUIRECTANGULAR_MODE=8;X.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;X.CLAMP_ADDRESSMODE=0;X.WRAP_ADDRESSMODE=1;X.MIRROR_ADDRESSMODE=2;X.UseSerializedUrlIfAny=!1;v([O()],X.prototype,"url",void 0);v([O()],X.prototype,"uOffset",void 0);v([O()],X.prototype,"vOffset",void 0);v([O()],X.prototype,"uScale",void 0);v([O()],X.prototype,"vScale",void 0);v([O()],X.prototype,"uAng",void 0);v([O()],X.prototype,"vAng",void 0);v([O()],X.prototype,"wAng",void 0);v([O()],X.prototype,"uRotationCenter",void 0);v([O()],X.prototype,"vRotationCenter",void 0);v([O()],X.prototype,"wRotationCenter",void 0);v([O()],X.prototype,"homogeneousRotationInUVTransform",void 0);v([O()],X.prototype,"isBlocking",null);H("BABYLON.Texture",X);Pe._TextureParser=X.Parse;nt.prototype.updateRawTexture=function(a,e,t,i,s=null,r=0,n=!1){if(!a)return;const o=this._getRGBABufferInternalSizedFormat(r,t,n),l=this._getInternalFormat(t),h=this._getWebGLTextureType(r);this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.type=r,a.invertY=i,a._compression=s),a.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],a.width,a.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,a.width,a.height,0,l,h,e),a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0};nt.prototype.createRawTexture=function(a,e,t,i,s,r,n,o=null,l=0,h=0,c=!1){const u=new $t(this,xt.Raw);u.baseWidth=e,u.baseHeight=t,u.width=e,u.height=t,u.format=i,u.generateMipMaps=s,u.samplingMode=n,u.invertY=r,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=a),this.updateRawTexture(u,a,i,r,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(n,s);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),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u};nt.prototype.createRawCubeTexture=function(a,e,t,i,s,r,n,o=null){const l=this._gl,h=new $t(this,xt.CubeRaw);h.isCube=!0,h.format=t,h.type=i,this._doNotHandleContextLost||(h._bufferViewArray=a);const c=this._getWebGLTextureType(i);let u=this._getInternalFormat(t);u===l.RGB&&(u=l.RGBA),c===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(s=!1,n=1,U.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(s=!1,n=1,U.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):c===l.FLOAT&&!this._caps.textureFloatRender?(s=!1,U.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):c===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(s=!1,U.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));const d=e,f=d;if(h.width=d,h.height=f,h.invertY=r,h._compression=o,!this.needPOTTextures||Np(h.width)&&Np(h.height)||(s=!1),a)this.updateRawCubeTexture(h,a,t,i,r,o);else{const x=this._getRGBABufferInternalSizedFormat(i),E=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let S=0;S<6;S++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+S,E,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+S,E,x,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),a&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const _=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.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),h.generateMipMaps=s,h.samplingMode=n,h.isReady=!0,h};nt.prototype.updateRawCubeTexture=function(a,e,t,i,s,r=null,n=0){a._bufferViewArray=e,a.format=t,a.type=i,a.invertY=s,a._compression=r;const o=this._gl,l=this._getWebGLTextureType(i);let h=this._getInternalFormat(t);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;h===o.RGB&&(h=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,a,!0),this._unpackFlipY(s===void 0?!0:!!s),a.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let f=0;f<6;f++){let m=e[f];r?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,this.getCaps().s3tc[r],a.width,a.height,0,m):(u&&(m=fP(m,a.width,a.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+f,n,c,a.width,a.height,0,h,l,m))}(!this.needPOTTextures||Np(a.width)&&Np(a.height))&&a.generateMipMaps&&n===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),a.isReady=!0};nt.prototype.createRawCubeTextureFromUrl=function(a,e,t,i,s,r,n,o,l=null,h=null,c=3,u=!1){const d=this._gl,f=this.createRawCubeTexture(null,t,i,s,!r,u,c,null);e==null||e.addPendingData(f),f.url=a,f.isReady=!1,this._internalTexturesCache.push(f);const m=(x,E)=>{e==null||e.removePendingData(f),h&&x&&h(x.status+" "+x.statusText,E)},_=x=>{const E=f.width,S=n(x);if(S){if(o){const C=this._getWebGLTextureType(s);let y=this._getInternalFormat(i);const A=this._getRGBABufferInternalSizedFormat(s);let I=!1;y===d.RGB&&(y=d.RGBA,I=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const R=o(S);for(let N=0;N>N;for(let B=0;B<6;B++){let Q=R[N][B];I&&(Q=fP(Q,k,k,s)),d.texImage2D(B,N,A,k,k,0,y,C,Q)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,S,i,s,u);f.isReady=!0,e==null||e.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(a,x=>{_(x)},void 0,e==null?void 0:e.offlineProvider,!0,m),f};function fP(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n0}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 s in this._ranges)i&&(t+=", ",i=!1),t+=s;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 s=this._isDirty;if((!t._bonesTransformMatrices||t._bonesTransformMatrices.length!==16*(this.bones.length+1))&&(t._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),s=!0),!!s){if(this._synchronizedWithMesh!==t){this._synchronizedWithMesh=t;for(const r of this.bones)r.getParent()||(r.getBindMatrix().multiplyToRef(i,W.Matrix[1]),r._updateAbsoluteBindMatrices(W.Matrix[1]));if(this.isUsingTextureForMatrices){const r=(this.bones.length+1)*4;(!t._transformMatrixTexture||t._transformMatrixTexture.getSize().width!==r)&&(t._transformMatrixTexture&&t._transformMatrixTexture.dispose(),t._transformMatrixTexture=gs.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=gs.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&&(n.animation=s.animations[0].serialize()),e.ranges=[];for(const o in this._ranges){const l=this._ranges[o];if(!l)continue;const h={};h.name=o,h.from=l.from,h.to=l.to,e.ranges.push(h)}}return e}static Parse(e,t){const i=new gh(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=T.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix;let s;for(s=0;s-1&&(o=i.bones[r.parentBoneIndex]);const l=r.rest?L.FromArray(r.rest):null,h=new mi(r.name,i,o,L.FromArray(r.matrix),l,null,n);r.id!==void 0&&r.id!==null&&(h.id=r.id),r.length&&(h.length=r.length),r.metadata&&(h.metadata=r.metadata),r.animation&&h.animations.push(te.Parse(r.animation)),r.linkedTransformNodeId!==void 0&&r.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,h._waitingTransformNodeId=r.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class HV{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===Ke.POINTERDOWN){this._isPointerDown=!0;return}i.type===Ke.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;const i=ks.Now;let s=0;this._lastFrameTime!=null&&(s=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();const r=i-this._lastInteractionTime-this._idleRotationWaitTime,n=Math.max(Math.min(r/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*n,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(s/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??ks.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){const s=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=s*.05,this.upperRadiusTransitionRange=s*.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||(rc.EasingFunction.setEasingMode(rc.EasingMode),this._radiusBounceTransition=te.CreateAnimation("radius",te.ANIMATIONTYPE_FLOAT,60,rc.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=te.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()}}rc.EasingFunction=new gV(.3);rc.EasingMode=kr.EASINGMODE_EASEOUT;class gn{constructor(){this.onTargetFramingAnimationEndObservable=new K,this._mode=gn.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();gn.EasingFunction.setEasingMode(gn.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===Ke.POINTERDOWN){this._isPointerDown=!0;return}i.type===Ke.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 s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),c&&this._animatables.push(c),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===gn.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=ks.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=te.CreateAnimation("beta",te.ANIMATIONTYPE_FLOAT,60,gn.EasingFunction));const s=te.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});s&&this._animatables.push(s)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=ks.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}}gn.EasingFunction=new xV;gn.EasingMode=kr.EASINGMODE_EASEINOUT;gn.IgnoreBoundsSizeMode=0;gn.FitFrustumSidesMode=1;class Ct{constructor(e,t,i=Number.MAX_VALUE,s=At){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Ct(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Ct._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Ct._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n=0,o=Number.MAX_VALUE,l,h,c,u;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(l=1/this.direction.x,h=(s.x-this.origin.x)*l,c=(r.x-this.origin.x)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(l=1/this.direction.y,h=(s.y-this.origin.y)*l,c=(r.y-this.origin.y)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(l=1/this.direction.z,h=(s.z-this.origin.z)*l,c=(r.z-this.origin.z)*l,c===-1/0&&(c=1/0),h>c&&(u=h,h=c,c=u),n=Math.max(h,n),o=Math.min(c,o),n>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,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,l=o*o;if(n<=l)return!0;const h=i*this.direction.x+s*this.direction.y+r*this.direction.z;return h<0?!1:n-h*h<=l}intersectsTriangle(e,t,i){const s=Ct._TmpVector3[0],r=Ct._TmpVector3[1],n=Ct._TmpVector3[2],o=Ct._TmpVector3[3],l=Ct._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),T.CrossToRef(this.direction,r,n);const h=T.Dot(s,n);if(h===0)return null;const c=1/h;this.origin.subtractToRef(e,o);const u=T.Dot(o,n)*c;if(u<-this.epsilon||u>1+this.epsilon)return null;T.CrossToRef(o,s,l);const d=T.Dot(this.direction,l)*c;if(d<-this.epsilon||u+d>1+this.epsilon)return null;const f=T.Dot(r,l)*c;return f>this.length?null:new WE(1-u-d,u,f)}intersectsPlane(e){let t;const i=T.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{const s=T.Dot(e.normal,this.origin);return t=(-e.d-s)/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 T(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 T(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 T(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=W.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Ct.TransformToRef(this,o,this._tmpRay):this._tmpRay=Ct.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=W.Vector3[0],n=W.Vector3[1],o=W.Vector3[2],l=W.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Ct._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,l);const h=T.Dot(r,r),c=T.Dot(r,o),u=T.Dot(o,o),d=T.Dot(r,l),f=T.Dot(o,l),m=h*u-c*c;let _,x=m,E,S=m;mx&&(_=x,E=f+c,S=u)),E<0?(E=0,-d<0?_=0:-d>h?_=x:(_=-d,x=h)):E>S&&(E=S,-d+c<0?_=0:-d+c>h?_=x:(_=-d+c,x=h));const C=Math.abs(_)0&&y<=this.length&&R.lengthSquared()=a.distance?null:h};Ue.prototype._internalPick=function(a,e,t,i,s){let r=null;const n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n(this._tempPickingRay||(this._tempPickingRay=Ct.Zero()),this.createPickingRayToRef(a,e,n,this._tempPickingRay,s||null),this._tempPickingRay),t,i,!0);return r&&(r.ray=this.createPickingRay(a,e,L.Identity(),s||null)),r};Object.defineProperty(Ue.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1});Ue.prototype.pick=function(a,e,t,i,s,r,n=!1){const o=this._internalPick((l,h)=>(this._tempPickingRay||(this._tempPickingRay=Ct.Zero()),this.createPickingRayToRef(a,e,l,this._tempPickingRay,s||null,!1,h),this._tempPickingRay),t,i,!1,r);return o&&(o.ray=this.createPickingRay(a,e,L.Identity(),s||null)),o};Ue.prototype.pickWithRay=function(a,e,t,i){const s=this._internalPick(r=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=L.Identity()),r.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ct.Zero()),Ct.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t,!1,i);return s&&(s.ray=a),s};Ue.prototype.multiPick=function(a,e,t,i,s){return this._internalMultiPick(r=>this.createPickingRay(a,e,r,i||null),t,s)};Ue.prototype.multiPickWithRay=function(a,e,t){return this._internalMultiPick(i=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=L.Identity()),i.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ct.Zero()),Ct.TransformToRef(a,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),e,t)};Ve.prototype.getForwardRay=function(a=100,e,t){return this.getForwardRayToRef(new Ct(T.Zero(),T.Zero(),a),a,e,t)};Ve.prototype.getForwardRayToRef=function(a,e=100,t,i){t||(t=this.getWorldMatrix()),a.length=e,i?a.origin.copyFrom(i):a.origin.copyFrom(this.position);const s=W.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);const r=W.Vector3[3];return T.TransformNormalToRef(s,t,r),T.NormalizeToRef(r,a.direction),a};function Cv(a){const e=[],t=[],i=[],s=[],r=a.width||a.size||1,n=a.height||a.size||1,o=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,l=r/2,h=n/2;t.push(-l,-h,0),i.push(0,0,-1),s.push(0,Ht.UseOpenGLOrientationForUV?1:0),t.push(l,-h,0),i.push(0,0,-1),s.push(1,Ht.UseOpenGLOrientationForUV?1:0),t.push(l,h,0),i.push(0,0,-1),s.push(1,Ht.UseOpenGLOrientationForUV?0:1),t.push(-l,h,0),i.push(0,0,-1),s.push(0,Ht.UseOpenGLOrientationForUV?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Se._ComputeSides(o,t,e,i,s,a.frontUVs,a.backUVs);const c=new Se;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function bv(a,e={},t=null){const i=new q(a,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Cv(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}Se.CreatePlane=Cv;q.CreatePlane=(a,e,t,i,s)=>bv(a,{size:e,width:e,height:e,sideOrientation:s,updatable:i},t);class Vt{}Vt.ANCHOR_SYSTEM="xr-anchor-system";Vt.BACKGROUND_REMOVER="xr-background-remover";Vt.HIT_TEST="xr-hit-test";Vt.MESH_DETECTION="xr-mesh-detection";Vt.PHYSICS_CONTROLLERS="xr-physics-controller";Vt.PLANE_DETECTION="xr-plane-detection";Vt.POINTER_SELECTION="xr-controller-pointer-selection";Vt.TELEPORTATION="xr-controller-teleportation";Vt.FEATURE_POINTS="xr-feature-points";Vt.HAND_TRACKING="xr-hand-tracking";Vt.IMAGE_TRACKING="xr-image-tracking";Vt.NEAR_INTERACTION="xr-near-interaction";Vt.DOM_OVERLAY="xr-dom-overlay";Vt.MOVEMENT="xr-controller-movement";Vt.LIGHT_ESTIMATION="xr-light-estimation";Vt.EYE_TRACKING="xr-eye-tracking";Vt.WALKING_LOCOMOTION="xr-walking-locomotion";Vt.LAYERS="xr-layers";Vt.DEPTH_SENSING="xr-depth-sensing";Vt.SPACE_WARP="xr-space-warp";Vt.RAW_CAMERA_ACCESS="xr-raw-camera-access";class qi{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,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}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()||Z.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Z.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={},s=!0,r=!0){const n=typeof e=="string"?e:e.Name;let o=0;if(typeof t=="string"){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(t==="stable"?o=qi.GetStableVersionOfFeature(n):t==="latest"?o=qi.GetLatestVersionOfFeature(n):o=+t,o===-1||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const l=qi._ConflictingFeatures[n];if(l!==void 0&&this.getEnabledFeatures().indexOf(l)!==-1)throw new Error(`Feature ${n} cannot be enabled while ${l} is enabled.`);const h=this._features[n],c=qi.ConstructFeature(n,o,this._xrSessionManager,i);if(!c)throw new Error(`feature not found - ${n}`);h&&this.disableFeature(n);const u=c();if(u.dependsOn&&!u.dependsOn.every(f=>!!this._features[f]))throw new Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Z.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u}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 s=this._features[i],r=s.featureImplementation.xrNativeFeatureName;if(r&&(s.required?(e.requiredFeatures=e.requiredFeatures||[],e.requiredFeatures.indexOf(r)===-1&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.indexOf(r)===-1&&e.optionalFeatures.push(r))),s.featureImplementation.getXRSessionInitExtension){const n=await s.featureImplementation.getXRSessionInitExtension();e={...e,...n}}}return e}}qi._AvailableFeatures={};qi._ConflictingFeatures={[Vt.TELEPORTATION]:Vt.MOVEMENT,[Vt.MOVEMENT]:Vt.TELEPORTATION};class nr{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&&U.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 K,this.onFeatureDetachObservable=new K}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)U.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 Fi{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}Fi.DistanceJoint=0;Fi.HingeJoint=1;Fi.BallAndSocketJoint=2;Fi.WheelJoint=3;Fi.SliderJoint=4;Fi.PrismaticJoint=5;Fi.UniversalJoint=6;Fi.Hinge2Joint=Fi.WheelJoint;Fi.PointToPointJoint=8;Fi.SpringJoint=9;Fi.LockJoint=10;q._PhysicsImpostorParser=function(a,e,t){return new ht(e,t.physicsImpostor,{mass:t.physicsMass,friction:t.physicsFriction,restitution:t.physicsRestitution},a)};class ht{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},s){if(this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=T.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new ae,this._tmpQuat2=new ae,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 ae),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(r=>{r(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(r=>{r(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,ht._TmpVecs[0]),this.object.translate(ht._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=r=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;const n=this._physicsEngine.getImpostorWithPhysicsBody(r.body);n&&(this.onCollideEvent&&this.onCollideEvent(this,n),this._onPhysicsCollideCallbacks.filter(o=>o.otherImpostors.indexOf(n)!==-1).forEach(o=>{o.callback(this,n,r.point,r.distance,r.impulse,r.normal)}))},!this.object){U.Error("No object was provided. A physics object is obligatory");return}this.object.parent&&i.mass!==0&&U.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=ae.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new ae),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&&U.Warn("You must affect impostors to children before affecting impostor to parent.")):U.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 Ft?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=ht.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const r=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return r.x=Math.abs(r.x),r.y=Math.abs(r.y),r.z=Math.abs(r.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),r}else return ht.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):T.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):T.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):U.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):U.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 s=-1;this._onPhysicsCollideCallbacks.some((n,o)=>{if(n.callback===t&&n.otherImpostors.length===i.length){const l=n.otherImpostors.every(h=>i.indexOf(h)>-1);return l&&(s=o),l}return!1})?this._onPhysicsCollideCallbacks.splice(s,1):U.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):ae.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 s=new Fi(t,i);return this.addJoint(e,s),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,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),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 ht(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 ae),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,s,r){const n=ht._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const l=ht._TmpQuat;o.rotationQuaternion.multiplyToRef(r,l),e.setRotationQuaternion(l,Wt.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Wt.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),s==null&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const c=ht._TmpQuat;e.getRotationQuaternionToRef(Wt.WORLD,t,c),c.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Wt.WORLD,t,o.rotationQuaternion);const l=ht._TmpVecs[0],h=ht._TmpVecs[1];n||(n=ht._TmpVecs[2],n.x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,h),e.getAbsolutePositionToRef(t,l),s==null&&i&&(s=i.length()),s!=null&&(l.x+=h.x*s,l.y+=h.y*s,l.z+=h.z*s),o.setAbsolutePosition(l)}}ht.DEFAULT_OBJECT_SIZE=new T(1,1,1);ht.IDENTITY_QUATERNION=ae.Identity();ht._TmpVecs=Os.BuildArray(3,T.Zero);ht._TmpQuat=ae.Identity();ht.NoImpostor=0;ht.SphereImpostor=1;ht.BoxImpostor=2;ht.PlaneImpostor=3;ht.MeshImpostor=4;ht.CapsuleImpostor=6;ht.CylinderImpostor=7;ht.ParticleImpostor=8;ht.HeightmapImpostor=9;ht.ConvexHullImpostor=10;ht.CustomImpostor=100;ht.RopeImpostor=101;ht.ClothImpostor=102;ht.SoftbodyImpostor=103;var $l;(function(a){a[a.Clean=0]="Clean",a[a.Stop=1]="Stop",a[a.Sync=2]="Sync",a[a.NoSync=3]="NoSync"})($l||($l={}));class ft{static get ForceFullSceneLoadingForIncremental(){return Us.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Us.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Us.ShowLoadingScreen}static set ShowLoadingScreen(e){Us.ShowLoadingScreen=e}static get loggingLevel(){return Us.loggingLevel}static set loggingLevel(e){Us.loggingLevel=e}static get CleanBoneMatrixWeights(){return Us.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Us.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return ft._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=ft._RegisteredPlugins[e];return t||(U.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),ft.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in ft._RegisteredPlugins){const i=ft._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return ft._RegisteredPlugins[t]}return ft.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");t!==-1&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return ft._GetPluginForExtension(s)}static _GetDirectLoad(e){return e.substr(0,5)==="data:"?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}static _LoadData(e,t,i,s,r,n,o,l){const h=ft._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const c=o?ft._GetPluginForExtension(o):h?ft._GetPluginForDirectLoad(e.url):ft._GetPluginForFilename(e.url);if(e.rawData&&!c.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let u;if(c.plugin.createPlugin!==void 0?u=c.plugin.createPlugin():u=c.plugin,!u)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(ft.OnPluginActivatedObservable.notifyObservers(u),h&&(u.canDirectLoad&&u.canDirectLoad(e.url)||!Bg(e.url))){if(u.directLoad){const y=u.directLoad(t,h);y.then?y.then(A=>{i(u,A)}).catch(A=>{r("Error in directLoad of _loadData: "+A,A)}):i(u,y)}else i(u,h);return u}const d=c.isBinary,f=(y,A)=>{if(t.isDisposed){r("Scene has been disposed");return}i(u,y,A)};let m=null,_=!1;const x=u.onDisposeObservable;x&&x.add(()=>{_=!0,m&&(m.abort(),m=null),n()});const E=()=>{if(_)return;const y=(A,I)=>{r(A==null?void 0:A.statusText,I)};if(!u.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";m=u.loadFile?u.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,s,d,y,l):t._loadFile(e.file||e.url,f,s,!0,d,y)},S=t.getEngine();let C=S.enableOfflineSupport;if(C){let y=!1;for(const A of t.disableOfflineSupportExceptionRules)if(A.test(e.url)){y=!0;break}C=!y}return C&&ee.OfflineProviderFactory?t.offlineProvider=ee.OfflineProviderFactory(e.url,E,S.disableManifestCheck):E(),u}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(!t)i=e,s=Z.GetFilename(e),e=Z.GetFolderPath(e);else if(t.name){const o=t;i=`file:${o.name}`,s=o.name,r=o}else if(ArrayBuffer.isView(t))i="",s=La(),n=t;else if(typeof t=="string"&&t.startsWith("data:"))i=t,s="";else{const o=t;if(o.substr(0,1)==="/")return Z.Error("Wrong sceneFilename parameter"),null;i=e+o,s=o}return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return ft._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!ft._RegisteredPlugins[e]}static RegisterPlugin(e){if(typeof e.extensions=="string"){const t=e.extensions;ft._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach(i=>{ft._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",s=We.LastCreatedScene,r=null,n=null,o=null,l=null,h=""){if(!s)return U.Error("No scene available to import mesh to"),null;const c=ft._GetFileInfo(t,i);if(!c)return null;const u={};s.addPendingData(u);const d=()=>{s.removePendingData(u)},f=(x,E)=>{const S=ft._FormatErrorMessage(c,x,E);o?o(s,S,new oo(S,ml.SceneLoaderError,E)):U.Error(S),d()},m=n?x=>{try{n(x)}catch(E){f("Error in onProgress callback: "+E,E)}}:void 0,_=(x,E,S,C,y,A,I,R)=>{if(s.importedMeshesFiles.push(c.url),r)try{r(x,E,S,C,y,A,I,R)}catch(N){f("Error in onSuccess callback: "+N,N)}s.removePendingData(u)};return ft._LoadData(c,s,(x,E,S)=>{if(x.rewriteRootURL&&(c.rootUrl=x.rewriteRootURL(c.rootUrl,S)),x.importMesh){const C=x,y=[],A=[],I=[];if(!C.importMesh(e,s,E,c.rootUrl,y,A,I,f))return;s.loadingPluginName=x.name,_(y,A,I,[],[],[],[],[])}else x.importMeshAsync(e,s,E,c.rootUrl,m,c.name).then(y=>{s.loadingPluginName=x.name,_(y.meshes,y.particleSystems,y.skeletons,y.animationGroups,y.transformNodes,y.geometries,y.lights,y.spriteManagers)}).catch(y=>{f(y.message,y)})},m,f,d,l,h)}static ImportMeshAsync(e,t,i="",s=We.LastCreatedScene,r=null,n=null,o=""){return new Promise((l,h)=>{ft.ImportMesh(e,t,i,s,(c,u,d,f,m,_,x,E)=>{l({meshes:c,particleSystems:u,skeletons:d,animationGroups:f,transformNodes:m,geometries:_,lights:x,spriteManagers:E})},r,(c,u,d)=>{h(d||new Error(u))},n,o)})}static Load(e,t="",i=We.LastCreatedEngine,s=null,r=null,n=null,o=null,l=""){return i?ft.Append(e,t,new Ue(i),s,r,n,o,l):(Z.Error("No engine available"),null)}static LoadAsync(e,t="",i=We.LastCreatedEngine,s=null,r=null,n=""){return new Promise((o,l)=>{ft.Load(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static Append(e,t="",i=We.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return U.Error("No scene available to append to"),null;const h=ft._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};ft.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));const d=(_,x)=>{const E=ft._FormatErrorMessage(h,_,x);n?n(i,E,new oo(E,ml.SceneLoaderError,x)):U.Error(E),u()},f=r?_=>{try{r(_)}catch(x){d("Error in onProgress callback",x)}}:void 0,m=()=>{if(s)try{s(i)}catch(_){d("Error in onSuccess callback",_)}i.removePendingData(c)};return ft._LoadData(h,i,(_,x)=>{if(_.load){if(!_.load(i,x,h.rootUrl,d))return;i.loadingPluginName=_.name,m()}else _.loadAsync(i,x,h.rootUrl,f,h.name).then(()=>{i.loadingPluginName=_.name,m()}).catch(S=>{d(S.message,S)})},f,d,u,o,l)}static AppendAsync(e,t="",i=We.LastCreatedScene,s=null,r=null,n=""){return new Promise((o,l)=>{ft.Append(e,t,i,h=>{o(h)},s,(h,c,u)=>{l(u||new Error(c))},r,n)})}static LoadAssetContainer(e,t="",i=We.LastCreatedScene,s=null,r=null,n=null,o=null,l=""){if(!i)return U.Error("No scene available to load asset container to"),null;const h=ft._GetFileInfo(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(_,x)=>{const E=ft._FormatErrorMessage(h,_,x);n?n(i,E,new oo(E,ml.SceneLoaderError,x)):U.Error(E),u()},f=r?_=>{try{r(_)}catch(x){d("Error in onProgress callback",x)}}:void 0,m=_=>{if(s)try{s(_)}catch(x){d("Error in onSuccess callback",x)}i.removePendingData(c)};return ft._LoadData(h,i,(_,x)=>{if(_.loadAssetContainer){const S=_.loadAssetContainer(i,x,h.rootUrl,d);if(!S)return;S.populateRootNodes(),i.loadingPluginName=_.name,m(S)}else _.loadAssetContainerAsync?_.loadAssetContainerAsync(i,x,h.rootUrl,f,h.name).then(S=>{S.populateRootNodes(),i.loadingPluginName=_.name,m(S)}).catch(S=>{d(S.message,S)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},f,d,u,o,l)}static LoadAssetContainerAsync(e,t="",i=We.LastCreatedScene,s=null,r=null){return new Promise((n,o)=>{ft.LoadAssetContainer(e,t,i,l=>{n(l)},s,(l,h,c)=>{o(c||new Error(h))},r)})}static ImportAnimations(e,t="",i=We.LastCreatedScene,s=!0,r=$l.Clean,n=null,o=null,l=null,h=null,c=null){if(!i){U.Error("No scene available to load animations to");return}if(s){for(const m of i.animatables)m.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(m=>{m.dispose()}),i.getNodes().forEach(m=>{m.animations&&(m.animations=[])})}else switch(r){case $l.Clean:i.animationGroups.slice().forEach(f=>{f.dispose()});break;case $l.Stop:i.animationGroups.forEach(f=>{f.stop()});break;case $l.Sync:i.animationGroups.forEach(f=>{f.reset(),f.restart()});break;case $l.NoSync:break;default:U.Error("Unknown animation group loading mode value '"+r+"'");return}const u=i.animatables.length,d=f=>{f.mergeAnimationsTo(i,i.animatables.slice(u),n),f.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)};this.LoadAssetContainer(e,t,i,d,l,h,c)}static ImportAnimationsAsync(e,t="",i=We.LastCreatedScene,s=!0,r=$l.Clean,n=null,o=null,l=null,h=null,c=null){return new Promise((u,d)=>{ft.ImportAnimations(e,t,i,s,r,n,f=>{u(f)},l,(f,m,_)=>{d(_||new Error(m))},c)})}}ft.NO_LOGGING=0;ft.MINIMAL_LOGGING=1;ft.SUMMARY_LOGGING=2;ft.DETAILED_LOGGING=3;ft.OnPluginActivatedObservable=new K;ft._RegisteredPlugins={};ft._ShowingLoadingScreen=!1;class cf extends pe{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new L,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){const t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}var M;(function(a){a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=4]="Vector2",a[a.Vector3=8]="Vector3",a[a.Vector4=16]="Vector4",a[a.Color3=32]="Color3",a[a.Color4=64]="Color4",a[a.Matrix=128]="Matrix",a[a.Object=256]="Object",a[a.AutoDetect=1024]="AutoDetect",a[a.BasedOnInput=2048]="BasedOnInput",a[a.All=4095]="All"})(M||(M={}));var z;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Neutral=4]="Neutral",a[a.VertexAndFragment=3]="VertexAndFragment"})(z||(z={}));class $A{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}finalize(e){const t=e.sharedData.emitComments,i=this.target===z.Fragment;this.shaderLanguage===vt.WGSL?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 s="";for(const r in this.functions)s+=this.functions[r]+` +`;if(this.compilationString=` +${s} +${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!==vt.WGSL){this.compilationString=`precision highp float; +`+this.compilationString,this.compilationString=`#if defined(WEBGL2) || defines(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 r in this.extensions){const n=this.extensions[r];this.compilationString=` +${n} +${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=""){this.samplers.indexOf(e)<0&&(this.shaderLanguage===vt.WGSL?(this._samplerDeclaration+=`var ${e}: sampler; +`,this._samplerDeclaration+=`var ${t}: texture_2d; +`):this._samplerDeclaration+=`uniform sampler2D ${e}; +`,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 M.Float:return"float";case M.Int:return"int";case M.Vector2:return"vec2";case M.Color3:case M.Vector3:return"vec3";case M.Color4:case M.Vector4:return"vec4";case M.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===vt.WGSL;switch(e){case M.Float:return t?"f32":"float";case M.Int:return t?"i32":"int";case M.Vector2:return t?"vec2":"vec2";case M.Color3:case M.Vector3:return t?"vec3":"vec3";case M.Color4:case M.Vector4:return t?"vec4":"vec4";case M.Matrix:return t?"mat4x4":"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){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`;let s=ri.IncludesShadersStore[e]+` +`;if(this.sharedData.emitComments&&(s=t+` +`+s),!i)return s;if(i.replaceStrings)for(let r=0;r${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[r]=`#include<${e}>${i!=null&&i.substitutionVars?"("+(i==null?void 0:i.substitutionVars)+")":""} +`,this.sharedData.emitComments&&(this.functions[r]=t+` +`+this.functions[r]);return}const n=j.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[r]=n[e],this.sharedData.emitComments&&(this.functions[r]=t+` +`+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,` +`)),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,` +`)),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,` +`)),i.replaceStrings)for(let o=0;o")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/,i=e.match(t);if(i){const s=i[1],r=i[2],o=i[3].replace(/var\s/g,"");return e.replace(i[0],`fn ${s}(${o}) -> ${r}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",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._convertOutParametersToWGSL(e),e=e.replace(/\[\*\]/g,"*"),e=this._convertFunctionsToWGSL(e),e=e.replace(/\s->\svoidnull/g,""),e}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),e}}class XV{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}}class Gr{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 s,r,n,o;const t=((r=(s=this._externalProperties)==null?void 0:s[e])==null?void 0:r.type)??typeof this[e],i=(o=(n=this._externalProperties)==null?void 0:n[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;te.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===z.Vertex||(e.ownerBlock.target===z.Neutral||e.ownerBlock.target===z.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===z.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===z.Vertex||e.target===z.Vertex||(e.ownerBlock.target===z.Neutral||e.ownerBlock.target===z.VertexAndFragment)&&e.ownerBlock.outputs.some(t=>t.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===z.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints)if(e.ownerBlock.target===z.Fragment||(e.ownerBlock.target===z.Neutral||e.ownerBlock.target===z.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=M.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=z.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===ra.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===z.Fragment){if(i.target===z.Vertex)return ra.TargetIncompatible;for(const n of i.outputs)if(n.ownerBlock.target!=z.Neutral&&n.isConnectedInVertexShader)return ra.TargetIncompatible}if(this.type!==e.type&&e.innerType!==M.AutoDetect)return Su.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1||e._acceptedConnectionPointType&&Su.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?ra.Compatible:ra.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return ra.TypeIncompatible;let s=i,r=t;return this.direction===Ui.Input&&(s=t,r=i),s.isAnAncestorOf(r)?ra.HierarchyIssue:ra.Compatible}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()}}class Je{get name(){return this._name}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=z.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,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===z.Neutral,this._isFinalMerger=i,this._isInput=this.getClassName()==="InputBlock",this._isTeleportOut=this.getClassName()==="NodeMaterialTeleportOutBlock",this._isTeleportIn=this.getClassName()==="NodeMaterialTeleportInBlock",this._name=e,this.uniqueId=a_.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===z.Neutral}initialize(e){}bind(e,t,i,s){}_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,s,r){return r=r??new Su(e,this,Ui.Input),r.type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return s=s??new Su(e,this,Ui.Output),s.type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===M.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===z.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),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput)||this.target===z.Vertex?!1:!!((this.target===z.VertexAndFragment||this.target===z.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,s=!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,s){e.build(t,s);const r=t._vertexState!=null,n=e._buildTarget===z.Vertex&&e.target!==z.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==z.VertexAndFragment&&n)&&(!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 h=t.shaderLanguage===vt.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+=`${h}${"v_"+o.declarationVariableName} = ${o.associatedVariableName}; +`}const l=t.shaderLanguage===vt.WGSL?"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!==z.Neutral&&(!(i.target&this.target)||!(i.target&e.target)))continue;const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&U.Log(`${e.target===z.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case z.Vertex:e.sharedData.checks.emitVertex=!0;break;case z.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 s of i.endpoints){const r=s.ownerBlock;r&&r.target&e.target&&t.indexOf(r)!==-1&&this._processBuild(r,e,s,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 r=0;do r++,this._codeVariableName=i+r;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=` +// ${this.getClassName()} +`;this.comments&&(s+=`// ${this.comments} +`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`,s+=this._dumpPropertiesCode();for(const r of this.inputs){if(!r.isConnected)continue;const o=r.connectedPoint.ownerBlock;t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}for(const r of this.outputs)if(r.hasEndpoints)for(const n of r.endpoints){const o=n.ownerBlock;o&&t.indexOf(o)===-1&&(s+=o._dumpCode(e,t))}return s}_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 s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){const i=this.serialize(),s=rs(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}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){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((s,r)=>{s.displayName&&(this.inputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.inputs[r].isExposedOnFrame=s.isExposedOnFrame,this.inputs[r].exposedPortPosition=s.exposedPortPosition)}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.exposedPortPosition)})}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class XE extends Je{constructor(e){super(e,z.Neutral),this.complementW=1,this.complementZ=0,this.target=z.Vertex,this.registerInput("vector",M.AutoDetect),this.registerInput("transform",M.Matrix),this.registerOutput("output",M.Vector4),this.registerOutput("xyz",M.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,s=e._getShaderType(M.Vector4),r=e._getShaderType(M.Vector3);if(t.connectedPoint){if(this.complementW===0){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===vt.WGSL?e.compilationString+=`let ${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 M.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case M.Vector3:case M.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`;break}}else{const n=i.associatedVariableName;switch(t.connectedPoint.type){case M.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${n} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case M.Vector3:case M.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${n} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${n} * ${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}}H("BABYLON.TransformBlock",XE);class qm extends Je{constructor(e){super(e,z.Vertex,!0),this.registerInput("vector",M.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;return e.shaderLanguage===vt.WGSL?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName}; +`:e.compilationString+=`gl_Position = ${t.associatedVariableName}; +`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",M.Float),e._emitVaryingFromString("vFragmentDepth",M.Float),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; +`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; +`),this}}H("BABYLON.VertexOutputBlock",qm);var Qe;(function(a){a[a.Boolean=0]="Boolean",a[a.Float=1]="Float",a[a.Int=2]="Int",a[a.Vector2=3]="Vector2",a[a.List=4]="List"})(Qe||(Qe={}));function it(a,e=Qe.Boolean,t="PROPERTIES",i){return(s,r)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:r,displayName:a,type:e,groupName:t,options:i??{}})}}class eh extends Je{constructor(e){super(e,z.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb",M.AutoDetect,!0),this.registerInput("a",M.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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&&Ch(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",M.Float),e._emitVaryingFromString("vFragmentDepth",M.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r);let n="gl_FragColor";e.shaderLanguage===vt.WGSL&&(n="fragmentOutputs.color");const o=e._getShaderType(M.Vector4);if(t.connectedPoint)s.isConnected?e.compilationString+=`${n} = ${o}(${t.associatedVariableName}.rgb, ${s.associatedVariableName}); +`:e.compilationString+=`${n} = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let l="1.0";s.connectedPoint&&(l=s.associatedVariableName),i.connectedPoint.type===M.Float?e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${l}); +`:e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${l}); +`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${n} = toLinearSpace(${n}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${n} = toGammaSpace(${n}); +`,e.compilationString+=`#endif +`,(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; +`),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\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([it("Convert to gamma space",Qe.Boolean,"PROPERTIES",{notifiers:{update:!0}})],eh.prototype,"convertToGammaSpace",void 0);v([it("Convert to linear space",Qe.Boolean,"PROPERTIES",{notifiers:{update:!0}})],eh.prototype,"convertToLinearSpace",void 0);v([it("Use logarithmic depth",Qe.Boolean,"PROPERTIES")],eh.prototype,"useLogarithmicDepth",void 0);H("BABYLON.FragmentOutputBlock",eh);var Ir;(function(a){a[a.Uniform=0]="Uniform",a[a.Attribute=1]="Attribute",a[a.Varying=2]="Varying",a[a.Undefined=3]="Undefined"})(Ir||(Ir={}));var It;(function(a){a[a.World=1]="World",a[a.View=2]="View",a[a.Projection=3]="Projection",a[a.ViewProjection=4]="ViewProjection",a[a.WorldView=5]="WorldView",a[a.WorldViewProjection=6]="WorldViewProjection",a[a.CameraPosition=7]="CameraPosition",a[a.FogColor=8]="FogColor",a[a.DeltaTime=9]="DeltaTime",a[a.CameraParameters=10]="CameraParameters",a[a.MaterialAlpha=11]="MaterialAlpha"})(It||(It={}));var Jl;(function(a){a[a.None=0]="None",a[a.Time=1]="Time",a[a.RealTime=2]="RealTime"})(Jl||(Jl={}));const YV={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},hE={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},KA={particle_texturemask:!0};class bt extends Je{get type(){if(this._type===M.AutoDetect){if(this.isUniform&&this.value!=null){if(!isNaN(this.value))return this._type=M.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=M.Vector2,this._type;case"Vector3":return this._type=M.Vector3,this._type;case"Vector4":return this._type=M.Vector4,this._type;case"Color3":return this._type=M.Color3,this._type;case"Color4":return this._type=M.Color4,this._type;case"Matrix":return this._type=M.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=M.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=M.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=M.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=M.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case It.World:case It.WorldView:case It.WorldViewProjection:case It.View:case It.ViewProjection:case It.Projection:return this._type=M.Matrix,this._type;case It.CameraPosition:return this._type=M.Vector3,this._type;case It.FogColor:return this._type=M.Color3,this._type;case It.DeltaTime:case It.MaterialAlpha:return this._type=M.Float,this._type;case It.CameraParameters:return this._type=M.Vector4,this._type}}return this._type}constructor(e,t=z.Vertex,i=M.AutoDetect){super(e,t,!1),this._mode=Ir.Undefined,this._animationType=Jl.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 K,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=Ir.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===M.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=Ir.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Ir.Uniform}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===Ir.Undefined}get isUniform(){return this._mode===Ir.Uniform}set isUniform(e){this._mode=e?Ir.Uniform:Ir.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Ir.Attribute}set isAttribute(e){this._mode=e?Ir.Attribute:Ir.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Ir.Varying}set isVarying(e){this._mode=e?Ir.Varying:Ir.Undefined,this.associatedVariableName=""}get isSystemValue(){return this._systemValue!=null}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Ir.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Jl.Time:{this.type===M.Float&&(this.value+=e.getAnimationRatio()*.01);break}case Jl.RealTime:{this.type===M.Float&&(this.value=(ks.Now-e.getEngine().startTime)/1e3);break}}}_emitDefine(e){return e[0]==="!"?`#ifndef ${e.substring(1)} +`:`#ifdef ${e} +`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case M.Float:this.value=0;break;case M.Vector2:this.value=ce.Zero();break;case M.Vector3:this.value=T.Zero();break;case M.Vector4:this.value=tt.Zero();break;case M.Color3:this.value=re.White();break;case M.Color4:this.value=new Oe(1,1,1,1);break;case M.Matrix:this.value=L.Identity();break}}_emitConstant(e){switch(this.type){case M.Float:return`${e._emitFloat(this.value)}`;case M.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case M.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case M.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case M.Color3:return Yt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Yt.Color3[0].toGammaSpaceToRef(Yt.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Yt.Color3[0].toLinearSpaceToRef(Yt.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${Yt.Color3[0].r}, ${Yt.Color3[0].g}, ${Yt.Color3[0].b})`;case M.Color4:return Yt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Yt.Color4[0].toGammaSpaceToRef(Yt.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Yt.Color4[0].toLinearSpaceToRef(Yt.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${Yt.Color4[0].r}, ${Yt.Color4[0].g}, ${Yt.Color4[0].b}, ${Yt.Color4[0].a})`}return""}get _noContextSwitch(){return hE[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)+` = ${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===vt.WGSL?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i}; +`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName}; +`,t&&(e._uniformDeclaration+=`#endif +`);const s=e.sharedData.hints;if(this._systemValue!==null&&this._systemValue!==void 0)switch(this._systemValue){case It.WorldView:s.needWorldViewMatrix=!0;break;case It.WorldViewProjection:s.needWorldViewProjectionMatrix=!0;break}else this._animationType!==Jl.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=YV[this.name]??this.name,this.target===z.Vertex&&e._vertexState){hE[this.name]?KA[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===vt.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t);return}if(e.attributes.indexOf(this.associatedVariableName)!==-1)return;e.attributes.push(this.associatedVariableName),hE[this.name]?KA[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===vt.WGSL?(e._attributeDeclaration+=`attribute ${this.associatedVariableName}: ${e._getShaderType(this.type)}; +`,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.associatedVariableName}; +`,t&&(e._attributeDeclaration+=`#endif +`))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this._associatedVariableName;switch(this._systemValue){case It.World:e.setMatrix(r,t);break;case It.WorldView:e.setMatrix(r,i);break;case It.WorldViewProjection:e.setMatrix(r,s);break}}_transmit(e,t,i){if(this.isAttribute)return;const s=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case It.World:case It.WorldView:case It.WorldViewProjection:return;case It.View:e.setMatrix(s,t.getViewMatrix());break;case It.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case It.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case It.CameraPosition:t.bindEyePosition(e,s,!0);break;case It.FogColor:e.setColor3(s,t.fogColor);break;case It.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case It.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case It.MaterialAlpha:e.setFloat(s,i.alpha);break}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(r!==null)switch(this.type){case M.Float:e.setFloat(s,r);break;case M.Int:e.setInt(s,r);break;case M.Color3:Yt.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Yt.Color3[0].toGammaSpaceToRef(Yt.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Yt.Color3[0].toLinearSpaceToRef(Yt.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,Yt.Color3[0]);break;case M.Color4:Yt.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Yt.Color4[0].toGammaSpaceToRef(Yt.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Yt.Color4[0].toLinearSpaceToRef(Yt.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,Yt.Color4[0]);break;case M.Vector2:e.setVector2(s,r);break;case M.Vector3:e.setVector3(s,r);break;case M.Vector4:e.setVector4(s,r);break;case M.Matrix:e.setMatrix(s,r);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.${It[this._systemValue]}); +`;if(this.isUniform){const t=[];let i="";switch(this.type){case M.Float:i=`${this.value}`;break;case M.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case M.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case M.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case M.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case M.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 M.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`;break}return t.push(`${e}.value = ${i}`),this.type===M.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Jl[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===Ir.Uniform&&(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===Ir.Attribute&&e.type===M.Vector3&&(this._type=M.Vector4),!!e.valueType)if(e.valueType==="number")this._storedValue=e.value;else{const s=rs(e.valueType);s&&(this._storedValue=s.FromArray(e.value))}}}H("BABYLON.InputBlock",bt);class mP extends Je{constructor(e){super(e,z.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,z.VertexAndFragment),this.registerOutput("rgba",M.Color4,z.Neutral),this.registerOutput("rgb",M.Color3,z.Neutral),this.registerOutput("r",M.Float,z.Neutral),this.registerOutput("g",M.Float,z.Neutral),this.registerOutput("b",M.Float,z.Neutral),this.registerOutput("a",M.Float,z.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?z.VertexAndFragment:z.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,M.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,M.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===z.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===z.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===z.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===z.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!==z.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=X.Parse(e.texture,t,i))}}H("BABYLON.CurrentScreenBlock",mP);class gP extends Je{constructor(e){super(e,z.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",M.AutoDetect,!1,z.VertexAndFragment),this.registerOutput("rgba",M.Color4,z.Neutral),this.registerOutput("rgb",M.Color3,z.Neutral),this.registerOutput("r",M.Float,z.Neutral),this.registerOutput("g",M.Float,z.Neutral),this.registerOutput("b",M.Float,z.Neutral),this.registerOutput("a",M.Float,z.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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(s=>s.isAttribute&&s.name==="particle_uv"&&t(s));i||(i=new bt("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===z.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+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); +`;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=X.Parse(e.texture,t,i))}}H("BABYLON.ParticleTextureBlock",gP);class xP extends Je{constructor(e){super(e,z.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,z.Fragment),this.registerOutput("rampColor",M.Color4,z.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"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==z.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges",M.Vector4,"RAMPGRADIENT"),e.compilationString+=` + #ifdef RAMPGRADIENT + vec4 baseColor = ${this.color.associatedVariableName}; + float alpha = ${this.color.associatedVariableName}.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; + + // Remapped alpha + float finalAlpha = baseColor.a; + baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); + + ${e._declareOutput(this.rampColor)} = baseColor; + #else + ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName}; + #endif + `,this}}H("BABYLON.ParticleRampGradientBlock",xP);class TP extends Je{constructor(e){super(e,z.Fragment),this._isUnique=!0,this.registerInput("color",M.Color4,!1,z.Fragment),this.registerInput("alphaTexture",M.Float,!1,z.Fragment),this.registerInput("alphaColor",M.Float,!1,z.Fragment),this.registerOutput("blendColor",M.Color4,z.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!==z.Vertex)return e.compilationString+=` + #ifdef BLENDMULTIPLYMODE + ${e._declareOutput(this.blendColor)}; + float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); + ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; + #else + ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName}; + #endif + `,this}}H("BABYLON.ParticleBlendMultiplyBlock",TP);class gc{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._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 s=0;s0&&(r.computeBonesUsingShaders=!1);continue}if(!(!r.computeBonesUsingShaders||r.numBoneInfluencers===0)){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(const n of r.subMeshes)if(n.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{const i=this._defines[this._currentRank];if(i)for(let s=0;s0}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 s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){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=s,this._depthStencilTexture=null,this.label=r}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,s=1,r=14,n){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},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,s,r,n;let e=null;if(this._isMulti){const o=this.textures;if(o&&o.length>0){let l=!1,h=o.length,c=-1;const u=o[o.length-1]._source;(u===xt.Depth||u===xt.DepthStencil)&&(l=!0,c=o[o.length-1].format,h--);const d=[],f=[],m=[],_=[],x=[],E=[],S=[],C={};for(let I=0;I1&&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 jV extends yv{constructor(e,t,i,s,r){super(e,t,i,s),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=r}_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,s=1,r=14,n){if(this._depthStencilBuffer){const o=this._engine,l=o._currentFramebuffer,h=this._context;o._bindUnboundFramebuffer(this._framebuffer),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_STENCIL_ATTACHMENT,h.RENDERBUFFER,null),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,null),h.framebufferRenderbuffer(h.FRAMEBUFFER,h.STENCIL_ATTACHMENT,h.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),h.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,s,r,n)}shareDepth(e){super.shareDepth(e);const t=this._context,i=this._depthStencilBuffer,s=e._MSAAFramebuffer||e._framebuffer,r=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;const n=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r._bindUnboundFramebuffer(s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i),r._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,s=0){var l,h;if(!e._hardwareTexture)return;const r=this._framebuffer,n=this._engine,o=n._currentFramebuffer;if(n._bindUnboundFramebuffer(r),n.webGLVersion>1){const c=this._context,u=c["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??((l=this.layerIndices)==null?void 0:l[t])??0,c.framebufferTextureLayer(c.FRAMEBUFFER,u,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??((h=this.faceIndices)==null?void 0:h[t])??0,c.framebufferTexture2D(c.FRAMEBUFFER,u,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):c.framebufferTexture2D(c.FRAMEBUFFER,u,c.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const c=this._context,u=c["COLOR_ATTACHMENT"+t+"_WEBGL"],d=i!==void 0?c.TEXTURE_CUBE_MAP_POSITIVE_X+i:c.TEXTURE_2D;c.framebufferTexture2D(c.FRAMEBUFFER,u,d,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=((s=this._attachments)==null?void 0:s.length)??this.textures.length;for(let r=0;r1&&(n.format===15?u=t.DEPTH_COMPONENT16:n.format===16?u=t.DEPTH_COMPONENT24:n.format===17||n.format===13?u=t.DEPTH24_STENCIL8:n.format===14?u=t.DEPTH_COMPONENT32F:n.format===18&&(u=t.DEPTH32F_STENCIL8)),n.is2DArray?t.texImage3D(r,0,u,n.width,n.height,i,0,c,h,null):n.is3D?t.texImage3D(r,0,u,n.width,n.height,s,0,c,h,null):t.texImage2D(r,0,u,n.width,n.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(n),n};nt.prototype.updateRenderTargetTextureSampleCount=function(a,e){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),a._depthStencilBuffer&&(t.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(t.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null);const i=a.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),e>1&&typeof t.renderbufferStorageMultisample=="function"){const s=t.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=s,this._bindUnboundFramebuffer(a._MSAAFramebuffer);const r=this._createRenderBuffer(a.texture.width,a.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(a.texture.type,a.texture.format,a.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(r)}else this._bindUnboundFramebuffer(a._framebuffer);return a.texture.samples=e,a._samples=e,a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e),this._bindUnboundFramebuffer(null),e};class je{static RegisterShaderCodeProcessing(e,t){if(!t){delete je._CustomShaderCodeProcessing[e??""];return}je._CustomShaderCodeProcessing[e??""]=t}static _GetShaderCodeProcessing(e){return je._CustomShaderCodeProcessing[e]??je._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)})}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,s,r,n,o=1,l,h,c=null,u=0,d="postprocess",f,m=!1,_=5,x=vt.GLSL){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._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Ps(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new ce(1,1),this._texelSize=ce.Zero(),this.onActivateObservable=new K,this.onSizeChangedObservable=new K,this.onApplyObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.name=e;let E=1,S=null;if(i&&!Array.isArray(i)){const C=i;i=C.uniforms??null,s=C.samplers??null,E=C.size??1,n=C.camera??null,o=C.samplingMode??1,l=C.engine,h=C.reusable,c=C.defines??null,u=C.textureType??0,d=C.vertexUrl??"postprocess",f=C.indexParameters,m=C.blockCompilation??!1,_=C.textureFormat??5,x=C.shaderLanguage??vt.GLSL,S=C.uniformBuffers??null}else r&&(typeof r=="number"?E=r:E={width:r.width,height:r.height});n!=null?(this._camera=n,this._scene=n.getScene(),n.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=E,this.renderTargetSamplingMode=o||1,this._reusable=h||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=x,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=S||[],this._indexParameters=f,this._drawWrapper=new Ws(this._engine),m||this.updateEffect(c)}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 Ps(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,l){const h=je._GetShaderCodeProcessing(this.name);if(h!=null&&h.defineCustomBindings){const c=(t==null?void 0:t.slice())??[];c.push(...this._parameters);const u=(i==null?void 0:i.slice())??[];u.push(...this._samplers),e=h.defineCustomBindings(this.name,e,c,u),t=c,i=u}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:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:h!=null&&h.processCodeAfterIncludes?(c,u)=>h.processCodeAfterIncludes(this.name,c,u):null,processFinalCode:h!=null&&h.processFinalCode?(c,u)=>h.processFinalCode(this.name,c,u):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let s=0;s0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let h=0;h{_.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(_,this.samples)}),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/h,l/c),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)),(m=(f=this._engine)._debugInsertMarker)==null||m.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:s.clearColor,s._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,s;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),(s=(i=je._GetShaderCodeProcessing(this.name))==null?void 0:i.bindCustomBindings)==null||s.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()}}serialize(){const e=Pe.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=je.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 s=rs(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return Pe.Parse(()=>new je(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,s)}}je._CustomShaderCodeProcessing={};v([O()],je.prototype,"uniqueId",void 0);v([O()],je.prototype,"name",void 0);v([O()],je.prototype,"width",void 0);v([O()],je.prototype,"height",void 0);v([O()],je.prototype,"renderTargetSamplingMode",void 0);v([tv()],je.prototype,"clearColor",void 0);v([O()],je.prototype,"autoClear",void 0);v([O()],je.prototype,"forceAutoClearInAlphaMode",void 0);v([O()],je.prototype,"alphaMode",void 0);v([O()],je.prototype,"alphaConstants",void 0);v([O()],je.prototype,"enablePixelPerfectMode",void 0);v([O()],je.prototype,"forceFullscreenViewport",void 0);v([O()],je.prototype,"scaleMode",void 0);v([O()],je.prototype,"alwaysForcePOT",void 0);v([O("samples")],je.prototype,"_samples",void 0);v([O()],je.prototype,"adaptScaleToCurrentViewport",void 0);H("BABYLON.PostProcess",je);class Qm extends Je{constructor(e){super(e,z.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",M.Vector4,!0),this.registerInput("xyz ",M.Vector3,!0),this.registerInput("xy ",M.Vector2,!0),this.registerInput("zw ",M.Vector2,!0),this.registerInput("x",M.Float,!0),this.registerInput("y",M.Float,!0),this.registerInput("z",M.Float,!0),this.registerInput("w",M.Float,!0),this.registerOutput("xyzw",M.Vector4),this.registerOutput("xyz",M.Vector3),this.registerOutput("xy",M.Vector2),this.registerOutput("zw",M.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,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this._outputs[0],u=this._outputs[1],d=this._outputs[2],f=this._outputs[3],m=e._getShaderType(M.Vector4),_=e._getShaderType(M.Vector3),x=e._getShaderType(M.Vector2);return h.isConnected?(c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${h.associatedVariableName}${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${h.associatedVariableName}${this._buildSwizzle(3)}; +`),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${h.associatedVariableName}${this._buildSwizzle(2)}; +`)):l.isConnected?(c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${m}(${l.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):n.isConnected?(c.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(c)+` = ${m}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=e._declareOutput(c)+` = ${m}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)}; +`),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`),f.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(f)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=e._declareOutput(f)+` = ${x}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)}; +`)):(c.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(c)+` = ${m}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=e._declareOutput(c)+` = ${m}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)}; +`),d.hasEndpoints&&(e.compilationString+=e._declareOutput(d)+` = ${x}(${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)+` = ${x}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"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}}H("BABYLON.VectorMergerBlock",Qm);class jg extends Je{constructor(e){super(e,z.Neutral),this.sourceRange=new ce(-1,1),this.targetRange=new ce(0,1),this.registerInput("input",M.AutoDetect),this.registerInput("sourceMin",M.Float,!0),this.registerInput("sourceMax",M.Float,!0),this.registerInput("targetMin",M.Float,!0),this.registerInput("targetMax",M.Float,!0),this.registerOutput("output",M.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),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${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=ce.FromArray(e.sourceRange),this.targetRange=ce.FromArray(e.targetRange)}}v([it("From",Qe.Vector2)],jg.prototype,"sourceRange",void 0);v([it("To",Qe.Vector2)],jg.prototype,"targetRange",void 0);H("BABYLON.RemapBlock",jg);class qg extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(M.Float),this.right.acceptedConnectionPointTypes.push(M.Float),this._connectionObservers=[this.left.onConnectionObservable.add(()=>this._updateInputOutputTypes()),this.left.onDisconnectionObservable.add(()=>this._updateInputOutputTypes()),this.right.onConnectionObservable.add(()=>this._updateInputOutputTypes()),this.right.onDisconnectionObservable.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===M.Int||this.left.type===M.Float&&this.right.type!==M.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=[M.Int,M.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===M.Int||t.type===M.Float)&&e.acceptedConnectionPointTypes.push(M.Vector2,M.Vector3,M.Vector4,M.Color3,M.Color4,M.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach(e=>e.remove()),this._connectionObservers.length=0}}class YE extends qg{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}}H("BABYLON.MultiplyBlock",YE);var tn;(function(a){a[a.Material=0]="Material",a[a.PostProcess=1]="PostProcess",a[a.Particle=2]="Particle",a[a.ProceduralTexture=3]="ProceduralTexture"})(tn||(tn={}));class qV extends Gr{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 Qs{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:T.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:T.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:T.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:T.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 s=0;for(const r of t){if(r.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=T.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 T(10,10,10),this.onAnimationEnd=null,this.blendMode=Qs.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 ce(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new T(0,0,0),this._useLogarithmicDepth=!1,this.gravity=T.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 Oe(1,1,1,1),this.color2=new Oe(1,1,1,1),this.colorDead=new Oe(0,0,0,1),this.textureMask=new Oe(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new qV,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 T(0,1,0),i=new T(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}Qs.BLENDMODE_ONEONE=0;Qs.BLENDMODE_STANDARD=1;Qs.BLENDMODE_ADD=2;Qs.BLENDMODE_MULTIPLY=3;Qs.BLENDMODE_MULTIPLYADD=4;class EP extends Je{constructor(e){super(e,z.Neutral),this.registerInput("rgba",M.Color4,!0),this.registerInput("rgb ",M.Color3,!0),this.registerOutput("rgb",M.Color3),this.registerOutput("r",M.Float),this.registerOutput("g",M.Float),this.registerOutput("b",M.Float),this.registerOutput("a",M.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],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb; +`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.r; +`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.g; +`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b; +`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a; +`),this}}H("BABYLON.ColorSplitterBlock",EP);nt.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),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 s=this._gl,r=new $t(this,xt.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const n=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,U.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),a,a,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,a,a),i.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,r.width=a,r.height=a,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,this._internalTexturesCache.push(r),t.setTextures(r),t};const cE={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Qg{constructor(e,t=cE){this._fullscreenViewport=new da(0,0,1,1);const i=t.positions??cE.positions,s=t.indices??cE.indices;this.engine=e,this._vertexBuffers={[P.PositionKind]:new P(e,i,P.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(s);for(const r in this._vertexBuffers)this._vertexBuffers[r]._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[P.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[P.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class xl{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.onApplyObservable=new K;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 s=e.defines?e.defines.join(` +`):"";this._drawWrapper=new Ws(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,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new ri(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const SP="passPixelShader",vP=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;j.ShadersStore[SP]=vP;const jA={name:SP,shader:vP};class Lr{static _CreateDumpRenderer(){if(!Lr._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new nt(e,!1,i)}catch{e=document.createElement("canvas"),t=new nt(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;const s=new Qg(t),r=new xl({engine:t,name:jA.name,fragmentShader:jA.shader,samplerNames:["textureSampler"]});Lr._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return Lr._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const l=await i.readPixels(0,0,e,t),h=new Uint8Array(l.buffer);Lr.DumpData(e,t,h,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,l){return new Promise(h=>{Lr.DumpData(e,t,i,c=>h(c),s,r,n,o,l)})}static DumpData(e,t,i,s,r="image/png",n,o=!1,l=!1,h){const c=Lr._CreateDumpRenderer();if(c.engine.setSize(e,t,!0),i instanceof Float32Array){const d=new Uint8Array(i.length);let f=i.length;for(;f--;){const m=i[f];d[f]=Math.round(Ne.Clamp(m)*255)}i=d}const u=c.engine.createRawTexture(i,e,t,5,!1,!o,1);c.renderer.setViewport(),c.renderer.applyEffectWrapper(c.wrapper),c.wrapper.effect._bindTexture("textureSampler",u),c.renderer.draw(),l?Z.ToBlob(c.canvas,d=>{const f=new FileReader;f.onload=m=>{const _=m.target.result;s&&s(_)},f.readAsArrayBuffer(d)},r,h):Z.EncodeScreenshotCanvasData(c.canvas,s,r,n,h),u.dispose()}static Dispose(){Lr._DumpToolsEngine&&(Lr._DumpToolsEngine.wrapper.dispose(),Lr._DumpToolsEngine.renderer.dispose(),Lr._DumpToolsEngine.engine.dispose()),Lr._DumpToolsEngine=null}}const QV=()=>{Z.DumpData=Lr.DumpData,Z.DumpDataAsync=Lr.DumpDataAsync,Z.DumpFramebuffer=Lr.DumpFramebuffer};QV();class Yi extends X{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=oI(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 s=0;s{var N;const R=this._renderList?this._renderList.length:0;(I===0&&R>0||R===0)&&((N=this.getScene())==null||N.meshes.forEach(k=>{k._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new K,this.onAfterUnbindObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.onClearObservable=new K,this.onResizeObservable=new K,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=T.Zero(),i=this.getScene(),!i)return;const y=this.getScene().getEngine();this._gammaSpace=C,this._coordinatesMode=X.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=y.onResizeObservable.add(()=>{}),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new mr(i),this._renderingManager._useSceneAutoClearSetup=!0,!u&&(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:c,samples:m,creationFlags:_,noColorAttachment:x,useSRGBBuffer:E,colorAttachment:S,label:this.name},this.samplingMode===X.NEAREST_SAMPLINGMODE&&(this.wrapU=X.CLAMP_ADDRESSMODE,this.wrapV=X.CLAMP_ADDRESSMODE),f||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=X.INVCUBIC_MODE,this._textureMatrix=L.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,m!==void 0&&(this.samples=m)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,s,r,n)}_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 s;const t=this.isCube;(s=this._renderTarget)==null||s.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 s=this.getScene();if(!s)return i;const r=s.getEngine();if(this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):(!s||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){var h,c,u;const n=this.getScene();if(!n)return;const o=n.getEngine();if((h=o._debugPushGroup)==null||h.call(o,`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(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||n.clearColor,!0,!0,!0);else{let d=null;const f=this.renderList?this.renderList:n.getActiveMeshes().data,m=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(d=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,f,m)),d?this._prepareRenderingManager(d,d.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(f,m,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),d=f);for(const x of n._beforeRenderTargetClearStage)x.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const x of n._beforeRenderTargetDrawStage)x.action(this,e,s);this._renderingManager.render(this.customRenderFunction,d,this.renderParticles,this.renderSprites);for(const x of n._afterRenderTargetDrawStage)x.action(this,e,s);const _=((c=this._texture)==null?void 0:c.generateMipMaps)??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const x of n._afterRenderTargetPostProcessStage)x.action(this,e,s);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&Lr.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&e===5&&o.generateMipMapsForCubemap(this._texture,!0),(u=o._debugPopGroup)==null||u.call(o,1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new Yi(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 s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Yi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Yi.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Yi.REFRESHRATE_RENDER_ONCE=0;Yi.REFRESHRATE_RENDER_ONEVERYFRAME=1;Yi.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2;X._CreateRenderTargetTexture=(a,e,t,i,s)=>new Yi(a,e,t,i);class ZV{constructor(e){this.name=ve.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(ve.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Z.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const JV="proceduralVertexShader",e3=`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 +}`;j.ShadersStore[JV]=e3;class Wo extends X{constructor(e,t,i,s,r=null,n=!0,o=!1,l=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new K,this.onBeforeGenerationObservable=new K,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,r!==null&&!(r instanceof X)?(this._options=r,this._fallbackTexture=r.fallbackTexture??null):(this._options={},this._fallbackTexture=r),s=this.getScene()||We.LastCreatedScene;let h=s._getComponent(ve.NAME_PROCEDURALTEXTURE);h||(h=new ZV(s),s._addComponent(h)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=n,this._drawWrapper=new Ws(this._fullEngine),this.setFragment(i);const c=this._createRtWrapper(o,t,n,l);this._texture=c.texture;const u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[P.PositionKind]=new P(this._fullEngine,u,P.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId?this._contentData:(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId),this._contentData)}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[P.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Yi.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Yi.REFRESHRATE_RENDER_ONCE)}reset(){var e;(e=this._drawWrapper.effect)==null||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}const t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:typeof this._fragment=="string"?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[P.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var s;(s=this._rtWrapper)==null||s.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 s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.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 r,n;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 o in this._textures)this._drawWrapper.effect.setTexture(o,this._textures[o]);for(const o in this._ints)this._drawWrapper.effect.setInt(o,this._ints[o]);for(const o in this._floats)this._drawWrapper.effect.setFloat(o,this._floats[o]);for(const o in this._floatsArrays)this._drawWrapper.effect.setArray(o,this._floatsArrays[o]);for(const o in this._colors3)this._drawWrapper.effect.setColor3(o,this._colors3[o]);for(const o in this._colors4){const l=this._colors4[o];this._drawWrapper.effect.setFloat4(o,l.r,l.g,l.b,l.a)}for(const o in this._vectors2)this._drawWrapper.effect.setVector2(o,this._vectors2[o]);for(const o in this._vectors3)this._drawWrapper.effect.setVector3(o,this._vectors3[o]);for(const o in this._vectors4)this._drawWrapper.effect.setVector4(o,this._vectors4[o]);for(const o in this._matrices)this._drawWrapper.effect.setMatrix(o,this._matrices[o])}if(!this._texture||!this._rtWrapper)return;(r=i._debugPushGroup)==null||r.call(i,`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let o=0;o<6;o++)i.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(pe.TriangleFillMode,0,6);else i.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(pe.TriangleFillMode,0,6);i.unBindFramebuffer(this._rtWrapper,this.isCube),s&&i.setViewport(s),this.isCube&&i.generateMipMapsForCubemap(this._texture,!0),(n=i._debugPopGroup)==null||n.call(i,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Wo(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[P.PositionKind];i&&(i.dispose(),this._vertexBuffers[P.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}v([O()],Wo.prototype,"isEnabled",void 0);v([O()],Wo.prototype,"autoClear",void 0);v([O()],Wo.prototype,"_generateMipMaps",void 0);v([O()],Wo.prototype,"_size",void 0);v([O()],Wo.prototype,"refreshRate",null);H("BABYLON.ProceduralTexture",Wo);var ws;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Exp2=4]="Exp2",a[a.Round=5]="Round",a[a.Floor=6]="Floor",a[a.Ceiling=7]="Ceiling",a[a.Sqrt=8]="Sqrt",a[a.Log=9]="Log",a[a.Tan=10]="Tan",a[a.ArcTan=11]="ArcTan",a[a.ArcCos=12]="ArcCos",a[a.ArcSin=13]="ArcSin",a[a.Fract=14]="Fract",a[a.Sign=15]="Sign",a[a.Radians=16]="Radians",a[a.Degrees=17]="Degrees"})(ws||(ws={}));class CP extends Je{constructor(e){super(e,z.Neutral),this.operation=ws.Cos,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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 ws.Cos:{i="cos";break}case ws.Sin:{i="sin";break}case ws.Abs:{i="abs";break}case ws.Exp:{i="exp";break}case ws.Exp2:{i="exp2";break}case ws.Round:{i="round";break}case ws.Floor:{i="floor";break}case ws.Ceiling:{i="ceil";break}case ws.Sqrt:{i="sqrt";break}case ws.Log:{i="log";break}case ws.Tan:{i="tan";break}case ws.ArcTan:{i="atan";break}case ws.ArcCos:{i="acos";break}case ws.ArcSin:{i="asin";break}case ws.Fract:{i="fract";break}case ws.Sign:{i="sign";break}case ws.Radians:{i="radians";break}case ws.Degrees:{i="degrees";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.${ws[this.operation]}; +`}}H("BABYLON.TrigonometryBlock",CP);const uE={effect:null,subMesh:null};class Om extends Gr{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){this[e]===void 0&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class ss extends cf{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}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={}){super(e,t||We.LastCreatedScene),this._buildId=ss._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new L,this._cachedWorldViewProjectionMatrix=new L,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new K,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=tn.Material,this.forceAlphaBlending=!1,this._options={emitComments:!1,shaderLanguage:vt.GLSL,...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 Z.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&z.Vertex&&this._addVertexOutputNode(e),e.target&z.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return e.target===null?this:(e.target&z.Vertex&&this._removeVertexOutputNode(e),e.target&z.Fragment&&this._removeFragmentOutputNode(e),this)}_addVertexOutputNode(e){if(this._vertexOutputNodes.indexOf(e)===-1)return e.target=z.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=z.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,s=!0){(e.target===z.VertexAndFragment||t.target===z.Fragment&&e.target===z.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,this.attachedBlocks.indexOf(e)===-1){if(e.isUnique){const r=e.getClassName();for(const n of this.attachedBlocks)if(n.getClassName()===r)throw`Cannot have multiple blocks of type ${r} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const o=n.ownerBlock;o!==e&&this._processInitializeOnLink(o,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const r of e.outputs)r.associatedVariableName=""}_resetDualBlocks(e,t){e.target===z.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._resetDualBlocks(r,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){!this._vertexCompilationState&&!i&&(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===tn.Particle;if(this._vertexOutputNodes.length===0&&!r)throw"You must define at least one vertexOutputNode";if(this._fragmentOutputNodes.length===0)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new $A,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=z.Vertex,this._fragmentCompilationState=new $A,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=z.Fragment,this._sharedData=new XV,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=r;const n=[],o=[];for(const c of this._vertexOutputNodes)n.push(c),this._initializeBlock(c,this._vertexCompilationState,o,i);for(const c of this._fragmentOutputNodes)o.push(c),this._initializeBlock(c,this._fragmentCompilationState,n,i);this.optimize();for(const c of n)c.build(this._vertexCompilationState,n);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 c of o)this._resetDualBlocks(c,this._buildId-1);for(const c of o)c.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=ss._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(U.Log("Vertex shader:"),U.Log(this._vertexCompilationState.compilationString),U.Log("Fragment shader:"),U.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const l=this.getScene().meshes;for(const c of l)if(c.subMeshes)for(const u of c.subMeshes){if(u.getMaterial()!==this||!u.materialDefines)continue;const d=u.materialDefines;d.markAllAsDirty(),d.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const h=this.getScene().prePassRenderer;h&&h.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(P.NormalKind),t.TANGENT=e.isVerticesDataPresent(P.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(P.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let h=1;h<=6;++h){const c=t["UV"+h];t["UV"+h]=e.isVerticesDataPresent(`uv${h===1?"":h}`),o=o||t["UV"+h]!==c}const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Ev(this.getScene(),t,!l),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate(i=>i.getClassName()==="PrePassOutputBlock"),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter(i=>i.getClassName()==="PrePassTextureBlock"),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const s of t)i.texturesRequired.includes(s)||i.texturesRequired.push(s);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==tn.PostProcess?(U.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,l=5){let h=this.name+this._buildId;const c=new Om,u=new Ft(h+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(u,c),ri.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(c.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,h,h):e=new je(this.name+"PostProcess",h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,c.toString(),o,h,{maxSimultaneousLights:this.maxSimultaneousLights},!1,l),e.nodeMaterialSource=this,e.onApplyObservable.add(f=>{d!==this._buildId&&(delete ri.ShadersStore[h+"VertexShader"],delete ri.ShadersStore[h+"PixelShader"],h=this.name+this._buildId,c.markAllAsDirty(),d=this._buildId),this._processDefines(u,c)&&(ri.RegisterShader(h,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Eu.SetImmediate(()=>e.updateEffect(c.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,h,h))),this._checkInternals(f)}),e}createProceduralTexture(e,t){if(this.mode!==tn.ProceduralTexture)return U.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new Wo(i,e,null,t),r=new Ft(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new Om,o=this._processDefines(r,n);ri.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o==null?void 0:o.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(l);let h=this._buildId;return s.onBeforeGenerationObservable.add(()=>{h!==this._buildId&&(delete ri.ShadersStore[i+"VertexShader"],delete ri.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),h=this._buildId);const c=this._processDefines(r,n);c&&(ri.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Eu.SetImmediate(()=>{l=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[P.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),c==null?void 0:c.fallbacks,void 0),s._setEffect(l)})),this._checkInternals(l)}),s}_createEffectForParticles(e,t,i,s,r,n,o,l=""){let h=this.name+this._buildId+"_"+t;n||(n=new Om),o||(o=this.getScene().getMeshByName(this.name+"Particle"),o||(o=new Ft(this.name+"Particle",this.getScene()),o.reservedDataStore={hidden:!0}));let c=this._buildId;const u=[];let d=l;if(!r){const f=this._processDefines(o,n);ri.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),d=u.join(` +`),r=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+` +`+d,f==null?void 0:f.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add(f=>{c!==this._buildId&&(delete ri.ShadersStore[h+"PixelShader"],h=this.name+this._buildId+"_"+t,n.markAllAsDirty(),c=this._buildId),u.length=0,e.fillDefines(u,t);const m=u.join(` +`);m!==d&&(n.markAllAsDirty(),d=m);const _=this._processDefines(o,n);if(_){ri.RegisterShader(h,this._fragmentCompilationState._builtCompilationString),f=this.getScene().getEngine().createEffectForParticles(h,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+` +`+d,_==null?void 0:_.fallbacks,i,s,e),e.setCustomEffect(f,t),this._createEffectForParticles(e,t,i,s,f,n,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 s of this._sharedData.animatedInputs)s.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!==tn.Particle){U.Log("Incompatible material mode");return}this._createEffectForParticles(e,Qs.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,Qs.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==tn.Material){U.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,s){let r=null;const n=this.getScene();if(cP(n,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,s)}),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 h=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(d=>{h.indexOf(d)===-1&&h.push(d)});const c=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(d=>{c.indexOf(d)===-1&&c.push(d)});const u=new gc;this._sharedData.blocksWithFallbacks.forEach(d=>{d.provideFallbacks(e,u)}),r={lightDisposed:o,uniformBuffers:l,mergedUniforms:h,mergedSamplers:c,fallbacks:u}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const h=s.getFrameId();if(this._animationFrame!==h){for(const c of this._sharedData.animatedInputs)c.animate(s);this._animationFrame=h}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Om);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some(h=>!h.isReady(e,this,n,i)))return!1;const l=this._processDefines(e,n,i,t);if(l){const h=t.effect,c=n.toString();let u=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:c,fallbacks:l.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(u)if(this._onEffectCreatedObservable&&(uE.effect=u,uE.subMesh=t,this._onEffectCreatedObservable.notifyObservers(uE)),this.allowShaderHotSwapping&&h&&!u.isReady()){if(u=h,n.markAsUnprocessed(),l.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(u,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._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 s of this._sharedData.inputBlocks)s._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const l of o.bindableBlocks)l.bind(r,this,t,i);for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);for(const l of o.inputBlocks)l._transmit(r,s,this)}else if(!this.isFrozen)for(const l of o.forcedBindableBlocks)l.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(t=>t.texture).map(t=>t.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)ss._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const s of this.getTextureBlocks().filter(r=>r.texture).map(r=>r.texture))s.dispose();for(const s of this.attachedBlocks)s.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),typeof this.BJSNODEMATERIALEDITOR>"u"){const i=e&&e.editorURL?e.editorURL:ss.EditorURL;Z.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 bt("Position");e.setAsAttribute("position");const t=new bt("World");t.setAsSystemValue(It.World);const i=new XE("WorldPos");e.connectTo(i),t.connectTo(i);const s=new bt("ViewProjection");s.setAsSystemValue(It.ViewProjection);const r=new XE("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new qm("VertexOutput");r.connectTo(n);const o=new bt("color");o.value=new Oe(.8,.8,.8,1);const l=new eh("FragmentOutput");o.connectTo(l),this.addOutputNode(n),this.addOutputNode(l),this._mode=tn.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new bt("Position");e.setAsAttribute("position2d");const t=new bt("Constant1");t.isConstant=!0,t.value=1;const i=new Qm("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new qm("VertexOutput");i.connectTo(s);const r=new bt("Scale");r.visibleInInspector=!0,r.value=new ce(1,1);const n=new jg("uv0");e.connectTo(n);const o=new YE("UV scale");n.connectTo(o),r.connectTo(o);const l=new mP("CurrentScreen");o.connectTo(l),l.texture=new X("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new eh("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(h),this._mode=tn.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new bt("Position");e.setAsAttribute("position2d");const t=new bt("Constant1");t.isConstant=!0,t.value=1;const i=new Qm("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new qm("VertexOutput");i.connectTo(s);const r=new bt("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Jl.Time,r.isConstant=!1;const n=new bt("Color3");n.value=new re(1,1,1),n.isConstant=!1;const o=new eh("FragmentOutput"),l=new Qm("VectorMerger");l.visibleInInspector=!1;const h=new CP("Cos");h.operation=ws.Cos,e.connectTo(l),r.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=tn.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new bt("uv");e.setAsAttribute("particle_uv");const t=new gP("ParticleTexture");e.connectTo(t);const i=new bt("Color");i.setAsAttribute("particle_color");const s=new YE("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new xP("ParticleRampGradient");s.connectTo(r);const n=new EP("ColorSplitter");i.connectTo(n);const o=new TP("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const l=new eh("FragmentOutput");o.connectTo(l),this.addOutputNode(l),this._mode=tn.Particle}async loadAsync(e,t=""){return ss.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,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 n of this._vertexOutputNodes)this._gatherBlocks(n,t);const s=[];for(const n of this._fragmentOutputNodes)this._gatherBlocks(n,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${tn[this.mode]}; +`;for(const n of t)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));for(const n of s)n.isInput&&e.indexOf(n)===-1&&(r+=n._dumpCode(i,e));e=[],r+=` +// Connections +`;for(const n of this._vertexOutputNodes)r+=n._dumpCodeForOutputConnections(e);for(const n of this._fragmentOutputNodes)r+=n._dumpCodeForOutputConnections(e);r+=` +// Output nodes +`;for(const n of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName}); +`;for(const n of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${n._codeVariableName}); +`;return r+=`nodeMaterial.build(); +`,r}serialize(e){const t=e?{}:Pe.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 s of this._vertexOutputNodes)this._gatherBlocks(s,i),t.outputNodes.push(s.uniqueId);for(const s of this._fragmentOutputNodes)this._gatherBlocks(s,i),t.outputNodes.indexOf(s.uniqueId)===-1&&t.outputNodes.push(s.uniqueId)}t.blocks=[];for(const s of i)t.blocks.push(s.serialize());if(!e)for(const s of this.attachedBlocks)i.indexOf(s)===-1&&t.blocks.push(s.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){i||this.clear();const s={};for(const r of e.blocks){const n=rs(r.customType);if(n){const o=new n;o._deserialize(r,this.getScene(),t),s[r.id]=o,this.attachedBlocks.push(o)}}for(const r of this.attachedBlocks)if(r.isTeleportOut){const n=r,o=n._tempEntryPointUniqueId;o&&s[o].attachToEndpoint(n)}for(let r=0;rnew ss(e,this.getScene(),this.options),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach(t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((s,r)=>{i.onLoadedObservable.addOnce(()=>{s()}),i.onErrorObservable.addOnce(n=>{r(n)})}))}),Promise.all(e)}static Parse(e,t,i="",s=vt.GLSL){const r=Pe.Parse(()=>new ss(e.name,t,{shaderLanguage:s}),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,s="",r=!1,n){const o=n??new ss(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return o.parseSerializedObject(h,s),r||o.build(),o}static ParseFromSnippetAsync(e,t=We.LastCreatedScene,i="",s,r=!1,n=!1){return e==="_BLANK"?Promise.resolve(ss.CreateDefault("blank",t)):new Promise((o,l)=>{const h=new hs;h.addEventListener("readystatechange",()=>{if(h.readyState==4)if(h.status==200){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||(s=Pe.Parse(()=>new ss(e,t),u,t,i),s.uniqueId=t.getUniqueId()),s.parseSerializedObject(u),s.snippetId=e;try{r||s.build()}catch(d){l(d)}n?s.whenTexturesReadyAsync().then(()=>{o(s)}).catch(d=>{l(d)}):o(s)}else l("Unable to load the snippet "+e)}),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()})}static CreateDefault(e,t){const i=new ss(e,t);return i.setToDefault(),i.build(),i}}ss._BuildIdGenerator=0;ss.EditorURL=`${Z._DefaultCdnUrl}/v${He.Version}/nodeEditor/babylon.nodeEditor.js`;ss.SnippetUrl="https://snippet.babylonjs.com";ss.IgnoreTexturesAtLoadTime=!1;v([O()],ss.prototype,"ignoreAlpha",void 0);v([O()],ss.prototype,"maxSimultaneousLights",void 0);v([O("mode")],ss.prototype,"_mode",void 0);v([O("comment")],ss.prototype,"comment",void 0);v([O()],ss.prototype,"forceAlphaBlending",void 0);H("BABYLON.NodeMaterial",ss);function Av(a){const e=a.sideOrientation||Se.DEFAULTSIDE,t=a.radius||1,i=a.flat===void 0?!0:a.flat,s=(a.subdivisions||4)|0,r=a.radiusX||t,n=a.radiusY||t,o=a.radiusZ||t,l=(1+Math.sqrt(5))/2,h=[-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],c=[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],u=[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,m=239/1024,_=60/1024,x=26/1024,E=-40/1024,S=20/1024,C=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],y=[],A=[],I=[],R=[];let N=0;const k=new Array(3),B=new Array(3);let Q;for(Q=0;Q<3;Q++)k[Q]=T.Zero(),B[Q]=ce.Zero();for(let de=0;de<20;de++){for(Q=0;Q<3;Q++){const fe=c[3*de+Q];k[Q].copyFromFloats(h[3*u[fe]],h[3*u[fe]+1],h[3*u[fe]+2]),k[Q].normalize(),B[Q].copyFromFloats(d[2*fe]*f+_+C[de]*E,d[2*fe+1]*m+x+C[de]*S)}const ge=(fe,Ee,De,Te)=>{const ue=T.Lerp(k[0],k[2],Ee/s),oe=T.Lerp(k[1],k[2],Ee/s),F=s===Ee?k[2]:T.Lerp(ue,oe,fe/(s-Ee));F.normalize();let ie;if(i){const et=T.Lerp(k[0],k[2],Te/s),ye=T.Lerp(k[1],k[2],Te/s);ie=T.Lerp(et,ye,De/(s-Te))}else ie=new T(F.x,F.y,F.z);ie.x/=r,ie.y/=n,ie.z/=o,ie.normalize();const he=ce.Lerp(B[0],B[2],Ee/s),ke=ce.Lerp(B[1],B[2],Ee/s),Ye=s===Ee?B[2]:ce.Lerp(he,ke,fe/(s-Ee));A.push(F.x*r,F.y*n,F.z*o),I.push(ie.x,ie.y,ie.z),R.push(Ye.x,Ht.UseOpenGLOrientationForUV?1-Ye.y:Ye.y),y.push(N),N++};for(let fe=0;febP(a,e,t);var Kl;(function(a){a.WRIST="wrist",a.THUMB="thumb",a.INDEX="index",a.MIDDLE="middle",a.RING="ring",a.LITTLE="little"})(Kl||(Kl={}));var ct;(function(a){a.WRIST="wrist",a.THUMB_METACARPAL="thumb-metacarpal",a.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",a.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",a.THUMB_TIP="thumb-tip",a.INDEX_FINGER_METACARPAL="index-finger-metacarpal",a.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",a.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",a.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",a.INDEX_FINGER_TIP="index-finger-tip",a.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",a.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",a.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",a.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",a.MIDDLE_FINGER_TIP="middle-finger-tip",a.RING_FINGER_METACARPAL="ring-finger-metacarpal",a.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",a.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",a.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",a.RING_FINGER_TIP="ring-finger-tip",a.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",a.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",a.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",a.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",a.PINKY_FINGER_TIP="pinky-finger-tip"})(ct||(ct={}));const $a=[ct.WRIST,ct.THUMB_METACARPAL,ct.THUMB_PHALANX_PROXIMAL,ct.THUMB_PHALANX_DISTAL,ct.THUMB_TIP,ct.INDEX_FINGER_METACARPAL,ct.INDEX_FINGER_PHALANX_PROXIMAL,ct.INDEX_FINGER_PHALANX_INTERMEDIATE,ct.INDEX_FINGER_PHALANX_DISTAL,ct.INDEX_FINGER_TIP,ct.MIDDLE_FINGER_METACARPAL,ct.MIDDLE_FINGER_PHALANX_PROXIMAL,ct.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ct.MIDDLE_FINGER_PHALANX_DISTAL,ct.MIDDLE_FINGER_TIP,ct.RING_FINGER_METACARPAL,ct.RING_FINGER_PHALANX_PROXIMAL,ct.RING_FINGER_PHALANX_INTERMEDIATE,ct.RING_FINGER_PHALANX_DISTAL,ct.RING_FINGER_TIP,ct.PINKY_FINGER_METACARPAL,ct.PINKY_FINGER_PHALANX_PROXIMAL,ct.PINKY_FINGER_PHALANX_INTERMEDIATE,ct.PINKY_FINGER_PHALANX_DISTAL,ct.PINKY_FINGER_TIP],t3={[Kl.WRIST]:[ct.WRIST],[Kl.THUMB]:[ct.THUMB_METACARPAL,ct.THUMB_PHALANX_PROXIMAL,ct.THUMB_PHALANX_DISTAL,ct.THUMB_TIP],[Kl.INDEX]:[ct.INDEX_FINGER_METACARPAL,ct.INDEX_FINGER_PHALANX_PROXIMAL,ct.INDEX_FINGER_PHALANX_INTERMEDIATE,ct.INDEX_FINGER_PHALANX_DISTAL,ct.INDEX_FINGER_TIP],[Kl.MIDDLE]:[ct.MIDDLE_FINGER_METACARPAL,ct.MIDDLE_FINGER_PHALANX_PROXIMAL,ct.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ct.MIDDLE_FINGER_PHALANX_DISTAL,ct.MIDDLE_FINGER_TIP],[Kl.RING]:[ct.RING_FINGER_METACARPAL,ct.RING_FINGER_PHALANX_PROXIMAL,ct.RING_FINGER_PHALANX_INTERMEDIATE,ct.RING_FINGER_PHALANX_DISTAL,ct.RING_FINGER_TIP],[Kl.LITTLE]:[ct.PINKY_FINGER_METACARPAL,ct.PINKY_FINGER_PHALANX_PROXIMAL,ct.PINKY_FINGER_PHALANX_INTERMEDIATE,ct.PINKY_FINGER_PHALANX_DISTAL,ct.PINKY_FINGER_TIP]};class i3{get handMesh(){return this._handMesh}getHandPartMeshes(e){return t3[e].map(t=>this._jointMeshes[$a.indexOf(t)])}getJointMesh(e){return this._jointMeshes[$a.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new K,this._jointTransforms=new Array($a.length),this._jointTransformMatrices=new Float32Array($a.length*16),this._tempJointMatrix=new L,this._jointRadii=new Float32Array($a.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(s=>{s.alwaysSelectAsActiveMesh=!0}),this._handMesh.skeleton){const s=this._handMesh.skeleton;$a.forEach((r,n)=>{const o=s.getBoneIndexByName(t?t[r]:r);o!==-1&&s.bones[o].linkTransformNode(this._jointTransforms[n])})}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=$a.map(o=>s[o]||i.get(o));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let o=0;o{const h=this._jointTransforms[l];L.FromArrayToRef(this._jointTransformMatrices,l*16,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,h.rotationQuaternion,h.position);const c=this._jointRadii[l]*this._jointScaleFactor,u=this._jointMeshes[l];u.isVisible=!this._handMesh&&!this._jointsInvisible,u.position.copyFrom(h.position),u.rotationQuaternion.copyFrom(h.rotationQuaternion),u.scaling.setAll(c),this._scene.useRightHandedSystem||(u.position.z*=-1,u.rotationQuaternion.z*=-1,u.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(h.position.z*=-1,h.rotationQuaternion.z*=-1,h.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 ci extends nr{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map(i=>{var n,o,l,h,c;const s=[],r=((n=e.jointMeshes)==null?void 0:n.sourceMesh)||bP("jointParent",ci._ICOSPHERE_PARAMS);r.isVisible=!!((o=e.jointMeshes)!=null&&o.keepOriginalVisible);for(let u=0;u<$a.length;++u){let d=r.createInstance(`${i}-handJoint-${u}`);if((l=e.jointMeshes)!=null&&l.onHandJointMeshGenerated){const f=e.jointMeshes.onHandJointMeshGenerated(d,u,i);f&&f!==d&&(d.dispose(),d=f)}if(d.isPickable=!1,(h=e.jointMeshes)!=null&&h.enablePhysics){const f=((c=e.jointMeshes)==null?void 0:c.physicsProps)||{};d.scaling.setAll(.02);const m=f.impostorType!==void 0?f.impostorType:ht.SphereImpostor;d.physicsImpostor=new ht(d,m,{mass:0,...f})}d.rotationQuaternion=new ae,d.isVisible=!1,s.push(d)}t[i]=s}),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t,i){return new Promise(async s=>{var d,f,m,_,x,E;const r={};(f=(d=ci._RightHandGLB)==null?void 0:d.meshes[1])!=null&&f.isDisposed()&&(ci._RightHandGLB=null),(_=(m=ci._LeftHandGLB)==null?void 0:m.meshes[1])!=null&&_.isDisposed()&&(ci._LeftHandGLB=null);const n=!!(ci._RightHandGLB&&ci._LeftHandGLB),o=await Promise.all([ci._RightHandGLB||ft.ImportMeshAsync("",ci.DEFAULT_HAND_MODEL_BASE_URL,ci.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ci._LeftHandGLB||ft.ImportMeshAsync("",ci.DEFAULT_HAND_MODEL_BASE_URL,ci.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ci._RightHandGLB=o[0],ci._LeftHandGLB=o[1];const l=await ss.ParseFromFileAsync("handShader",ci.DEFAULT_HAND_MODEL_SHADER_URL,e);l.needDepthPrePass=!0,l.transparencyMode=pe.MATERIAL_ALPHABLEND,l.alphaMode=2,l.build(!1);const h={base:re.FromInts(116,63,203),fresnel:re.FromInts(149,102,229),fingerColor:re.FromInts(177,130,255),tipFresnel:re.FromInts(220,200,255),...(x=i==null?void 0:i.handMeshes)==null?void 0:x.customColors},c={base:l.getBlockByName("baseColor"),fresnel:l.getBlockByName("fresnelColor"),fingerColor:l.getBlockByName("fingerColor"),tipFresnel:l.getBlockByName("tipFresnelColor")};c.base.value=h.base,c.fresnel.value=h.fresnel,c.fingerColor.value=h.fingerColor,c.tipFresnel.value=h.tipFresnel;const u=(E=t._getBaseLayerWrapper())==null?void 0:E.isMultiview;["left","right"].forEach(S=>{const C=S=="left"?ci._LeftHandGLB:ci._RightHandGLB;if(!C)throw new Error("Could not load hand model");const y=C.meshes[1];y._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,u||(y.material=l.clone(`${S}HandShaderClone`,!0)),y.isVisible=!1,r[S]=y,!n&&!e.useRightHandedSystem&&C.meshes[1].rotate(Vr.Y,Math.PI)}),l.dispose(),s({left:r.left,right:r.right})})}static _GenerateDefaultHandMeshRigMapping(e){const t=e=="right"?"R":"L";return{[ct.WRIST]:`wrist_${t}`,[ct.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ct.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ct.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ct.THUMB_TIP]:`thumb_tip_${t}`,[ct.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ct.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ct.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ct.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ct.INDEX_FINGER_TIP]:`index_tip_${t}`,[ct.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ct.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ct.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ct.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ct.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ct.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ct.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ct.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ct.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ct.RING_FINGER_TIP]:`ring_tip_${t}`,[ct.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ct.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ct.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ct.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ct.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 K,this.onHandRemovedObservable=new K,this._attachHand=r=>{var l,h,c;if(!r.inputSource.hand||r.inputSource.handedness=="none"||!this._handResources.jointMeshes)return;const n=r.inputSource.handedness,o=new i3(r,this._handResources.jointMeshes[n],this._handResources.handMeshes&&this._handResources.handMeshes[n],this._handResources.rigMappings&&this._handResources.rigMappings[n],(l=this.options.handMeshes)==null?void 0:l.meshesUseLeftHandedCoordinates,(h=this.options.jointMeshes)==null?void 0:h.invisible,(c=this.options.jointMeshes)==null?void 0:c.scaleFactor);this._attachedHands[r.uniqueId]=o,this._trackingHands[n]=o,this.onHandAddedObservable.notifyObservers(o)},this._detachHand=r=>{this._detachHandById(r.uniqueId)},this.xrNativeFeatureName="hand-tracking";const s=t.jointMeshes;if(s&&(typeof s.disableDefaultHandMesh<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=s.disableDefaultHandMesh),typeof s.handMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=s.handMeshes),typeof s.leftHandedSystemMeshes<"u"&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=s.leftHandedSystemMeshes),typeof s.rigMapping<"u")){t.handMeshes=t.handMeshes||{};const r={},n={};[[s.rigMapping.left,r],[s.rigMapping.right,n]].forEach(o=>{const l=o[0],h=o[1];l.forEach((c,u)=>{h[$a[u]]=c})}),t.handMeshes.customRigMappings={left:r,right:n}}}attach(){var e,t,i,s;return super.attach()?(this._handResources={jointMeshes:ci._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)&&!((s=this.options.handMeshes)!=null&&s.disableDefaultMeshes)&&(ci._GenerateDefaultHandMeshesAsync(We.LastCreatedScene,this._xrSessionManager,this.options).then(r=>{var n,o;this._handResources.handMeshes=r,this._handResources.rigMappings={left:ci._GenerateDefaultHandMeshRigMapping("left"),right:ci._GenerateDefaultHandMeshRigMapping("right")},(n=this._trackingHands.left)==null||n.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(r=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(r.newScaleFactor/r.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(r.newScaleFactor/r.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 s;const i=this.getHandByControllerId(e);if(i){const r=i.xrController.inputSource.handedness=="left"?"left":"right";((s=this._trackingHands[r])==null?void 0:s.xrController.uniqueId)===e&&(this._trackingHands[r]=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(),ci._RightHandGLB=null,ci._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(t=>t.dispose()),this._handResources.jointMeshes.right.forEach(t=>t.dispose()))}}ci.Name=Vt.HAND_TRACKING;ci.Version=1;ci.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/";ci.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb";ci.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb";ci.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json";ci._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2};ci._RightHandGLB=null;ci._LeftHandGLB=null;qi.AddWebXRFeature(ci.Name,(a,e)=>()=>new ci(a,e),ci.Version,!1);var qA;(function(a){a[a.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",a[a.RADIAL_SIDE=1]="RADIAL_SIDE",a[a.ULNAR_SIDE=2]="ULNAR_SIDE",a[a.BELOW_WRIST=3]="BELOW_WRIST"})(qA||(qA={}));var QA;(function(a){a[a.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",a[a.HAND_ROTATION=1]="HAND_ROTATION"})(QA||(QA={}));var ZA;(function(a){a[a.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",a[a.PALM_UP=1]="PALM_UP",a[a.GAZE_FOCUS=2]="GAZE_FOCUS",a[a.PALM_AND_GAZE=3]="PALM_AND_GAZE"})(ZA||(ZA={}));T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero(),T.Zero();ae.Identity();L.Identity(),L.Identity();Os.BuildArray(10,T.Zero);ae.Identity();Os.BuildArray(5,L.Identity);class s3{constructor(e,t,i=3,s){this._engine=e,this._label=s,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i,s){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,s)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);t!==-1&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}const Kf=(()=>{const a=new Uint8Array(4),e=new Uint32Array(a.buffer);return!!((e[0]=1)&a[0])})();Object.defineProperty(P.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0});Object.defineProperty(P.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0});P.prototype._rebuild=function(){var a,e;(a=this._buffer)==null||a._rebuild(),(e=this._alignedBuffer)==null||e._rebuild()};P.prototype.dispose=function(){var a;this._ownsBuffer&&this._buffer.dispose(),(a=this._alignedBuffer)==null||a.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0};P.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer};P.prototype._alignBuffer=function(){var u;const a=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4===0&&this.byteOffset%4===0||!a)return;const e=P.GetTypeByteLength(this.type),t=this.byteStride+3&-4,i=t/e,s=this._maxVerticesCount,n=s*t/e;let o;if(Array.isArray(a)){const d=new Float32Array(a);o=new DataView(d.buffer,d.byteOffset,d.byteLength)}else a instanceof ArrayBuffer?o=new DataView(a,0,a.byteLength):o=new DataView(a.buffer,a.byteOffset,a.byteLength);let l;this.type===P.BYTE?l=new Int8Array(n):this.type===P.UNSIGNED_BYTE?l=new Uint8Array(n):this.type===P.SHORT?l=new Int16Array(n):this.type===P.UNSIGNED_SHORT?l=new Uint16Array(n):this.type===P.INT?l=new Int32Array(n):this.type===P.UNSIGNED_INT?l=new Uint32Array(n):l=new Float32Array(n);const h=this.getSize();let c=this.byteOffset;for(let d=0;d{if(t.type!==Ke.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===lf.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ke.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([O()],Zg.prototype,"wheelPrecisionX",void 0);v([O()],Zg.prototype,"wheelPrecisionY",void 0);v([O()],Zg.prototype,"wheelPrecisionZ",void 0);class Rv{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Z.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=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 u,d;const l=o.event,h=l.pointerType==="touch";if(o.type!==Ke.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;const c=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,m=l.movementY;this.onTouch(null,f,m),this._pointA=null,this._pointB=null}else{if(o.type!==Ke.POINTERDOWN&&h&&((u=this._pointA)==null?void 0:u.pointerId)!==l.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==l.pointerId)return;if(o.type===Ke.POINTERDOWN&&(this._currentActiveButton===-1||h)){try{c==null||c.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&&!h&&(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===Ke.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===Ke.POINTERUP&&(this._currentActiveButton===l.button||h)){try{c==null||c.releasePointerCapture(l.pointerId)}catch{}h||(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,(s!==0||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===Ke.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){const f=l.clientX-this._pointA.x,m=l.clientY-this._pointA.y;this.onTouch(this._pointA,f,m),this._pointA.x=l.clientX,this._pointA.y=l.clientY}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 m=this._pointA.x-this._pointB.x,_=this._pointA.y-this._pointB.y,x=m*m+_*_,E={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,s,x,r,E),r=E,s=x}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ke.POINTERDOWN|Ke.POINTERUP|Ke.POINTERMOVE|Ke.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Z.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Z.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,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}v([O()],Rv.prototype,"buttons",void 0);var Dr={};class Jg{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();if(this.attached[t]){U.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=Ve.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 s=this.attached[i],r=Pe.Serialize(s);t[s.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const i in t){const s=Dr[i];if(s){const r=t[i],n=Pe.Parse(()=>new s,r,null);this.add(n)}}}else for(const i in this.attached){const s=Dr[this.attached[i].getClassName()];if(s){const r=Pe.Parse(()=>new s,e,null);this.remove(this.attached[i]),this.add(r)}}}}class tr{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=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=tr.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,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(){}}tr.GAMEPAD=0;tr.GENERIC=1;tr.XBOX=2;tr.POSE_ENABLED=3;tr.DUALSHOCK=4;class r3 extends tr{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.type=tr.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!==tr.POSE_ENABLED&&(!this.gamepad||t.type===tr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(tr.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 s=t.x/this.gamepadRotationSensibility;s!=0&&Math.abs(s)>.005&&(e.inertialAlphaOffset+=s)}if(t.y!=0){const s=t.y/this.gamepadRotationSensibility*this._yAxisScale;s!=0&&Math.abs(s)>.005&&(e.inertialBetaOffset+=s)}}const i=this.gamepad.leftStick;if(i&&i.y!=0){const s=i.y/this.gamepadMoveSensibility;s!=0&&Math.abs(s)>.005&&(this.camera.inertialRadiusOffset-=s)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}v([O()],ex.prototype,"gamepadRotationSensibility",void 0);v([O()],ex.prototype,"gamepadMoveSensibility",void 0);Dr.ArcRotateCameraGamepadInput=ex;class ho{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=Z.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===mh.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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=s/(1+this.wheelDeltaPercentage):i=s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Z.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ke.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===lf.DOM_DELTA_LINE?n3:1,n=-(i.deltaY*r);if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+s;for(let h=0;h<20&&Math.abs(l)>.001;h++)o-=l,l*=this.camera.inertia;o=Ne.Clamp(o,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,o)}}else s=n/(this.wheelPrecision*40);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ke.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=nn.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,L.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=T.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_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 r=e/i/t.radius,n=this._getPosition(),o=W.Vector3[6];n.subtractToRef(t.target,o),o.scaleInPlace(r),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}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}}bn.MinimumRadiusForPinch=.001;v([O()],bn.prototype,"buttons",void 0);v([O()],bn.prototype,"angularSensibilityX",void 0);v([O()],bn.prototype,"angularSensibilityY",void 0);v([O()],bn.prototype,"pinchPrecision",void 0);v([O()],bn.prototype,"pinchDeltaPercentage",void 0);v([O()],bn.prototype,"useNaturalPinchZoom",void 0);v([O()],bn.prototype,"pinchZoom",void 0);v([O()],bn.prototype,"panningSensibility",void 0);v([O()],bn.prototype,"multiTouchPanning",void 0);v([O()],bn.prototype,"multiTouchPanAndZoom",void 0);Dr.ArcRotateCameraPointersInput=bn;class Iv extends Jg{constructor(e){super(e)}addMouseWheel(){return this.add(new u_),this}addPointers(){return this.add(new bn),this}addKeyboard(){return this.add(new ho),this}}Iv.prototype.addVRDeviceOrientation=function(){return this.add(new yP),this};class yP{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=Z.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):Z.Warn("Permission not granted.")}).catch(i=>{Z.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"}}Dr.ArcRotateCameraVRDeviceOrientationInput=yP;class yh{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=Z.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===mh.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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)},Ke.POINTERDOWN|Ke.POINTERUP|Ke.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,s=this.camera.getEngine();if(!this.touchEnabled&&t.pointerType==="touch"||e.type!==Ke.POINTERMOVE&&this.buttons.indexOf(t.button)===-1)return;const r=t.target;if(e.type===Ke.POINTERDOWN){try{r==null||r.setPointerCapture(t.pointerId)}catch{}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),s.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Ke.POINTERUP){try{r==null||r.releasePointerCapture(t.pointerId)}catch{}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Ke.POINTERMOVE){if(!this._previousPosition){s.isPointerLock&&this._onMouseMove(e.event);return}const n=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(n,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const s=e.movementX,r=e.movementY;this._rotateCamera(s,r),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=i._calculateHandednessMultiplier();e*=s;const r=e/this.angularSensibility,n=t/this.angularSensibility,o=ae.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let l;if(this.buttonsPitch.some(h=>h===this.activeButton)&&(l=ae.RotationAxis(Vr.X,n),o.multiplyInPlace(l)),this.buttonsYaw.some(h=>h===this.activeButton)){l=ae.RotationAxis(Vr.Y,r),o.multiplyInPlace(l);const h=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-hh===this.activeButton)&&(l=ae.RotationAxis(Vr.Z,-r),i._trackRoll-=r,o.multiplyInPlace(l)),o.toEulerAnglesToRef(i.rotation)}}v([O()],tx.prototype,"buttons",void 0);v([O()],tx.prototype,"angularSensibility",void 0);Dr.FlyCameraMouseInput=tx;class vr{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=Z.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===mh.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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([O()],vr.prototype,"keysHeightOffsetIncr",void 0);v([O()],vr.prototype,"keysHeightOffsetDecr",void 0);v([O()],vr.prototype,"keysHeightOffsetModifierAlt",void 0);v([O()],vr.prototype,"keysHeightOffsetModifierCtrl",void 0);v([O()],vr.prototype,"keysHeightOffsetModifierShift",void 0);v([O()],vr.prototype,"keysRotationOffsetIncr",void 0);v([O()],vr.prototype,"keysRotationOffsetDecr",void 0);v([O()],vr.prototype,"keysRotationOffsetModifierAlt",void 0);v([O()],vr.prototype,"keysRotationOffsetModifierCtrl",void 0);v([O()],vr.prototype,"keysRotationOffsetModifierShift",void 0);v([O()],vr.prototype,"keysRadiusIncr",void 0);v([O()],vr.prototype,"keysRadiusDecr",void 0);v([O()],vr.prototype,"keysRadiusModifierAlt",void 0);v([O()],vr.prototype,"keysRadiusModifierCtrl",void 0);v([O()],vr.prototype,"keysRadiusModifierShift",void 0);v([O()],vr.prototype,"heightSensibility",void 0);v([O()],vr.prototype,"rotationSensibility",void 0);v([O()],vr.prototype,"radiusSensibility",void 0);Dr.FollowCameraKeyboardMoveInput=vr;class xc{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Z.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ke.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&U.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=r*.01*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=r*.01*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=r*.01*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Ke.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}v([O()],xc.prototype,"axisControlRadius",void 0);v([O()],xc.prototype,"axisControlHeight",void 0);v([O()],xc.prototype,"axisControlRotation",void 0);v([O()],xc.prototype,"wheelPrecision",void 0);v([O()],xc.prototype,"wheelDeltaPercentage",void 0);Dr.FollowCameraMouseWheelInput=xc;class yn extends Rv{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,s,r,n){if(i===0&&r===null||s===0&&n===null)return;let o=(s-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&&U.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&U.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&U.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}v([O()],yn.prototype,"angularSensibilityX",void 0);v([O()],yn.prototype,"angularSensibilityY",void 0);v([O()],yn.prototype,"pinchPrecision",void 0);v([O()],yn.prototype,"pinchDeltaPercentage",void 0);v([O()],yn.prototype,"axisXControlRadius",void 0);v([O()],yn.prototype,"axisXControlHeight",void 0);v([O()],yn.prototype,"axisXControlRotation",void 0);v([O()],yn.prototype,"axisYControlRadius",void 0);v([O()],yn.prototype,"axisYControlHeight",void 0);v([O()],yn.prototype,"axisYControlRotation",void 0);v([O()],yn.prototype,"axisPinchControlRadius",void 0);v([O()],yn.prototype,"axisPinchControlHeight",void 0);v([O()],yn.prototype,"axisPinchControlRotation",void 0);Dr.FollowCameraPointersInput=yn;class _a{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=Z.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===mh.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 s=this._keys.indexOf(i.keyCode);s>=0&&this._keys.splice(s,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 r=s.event,n=r.pointerType==="touch";if(!this.touchEnabled&&n||s.type!==Ke.POINTERMOVE&&this.buttons.indexOf(r.button)===-1)return;const o=r.target;if(s.type===Ke.POINTERDOWN){if(n&&this._activePointerId!==-1||!n&&this._currentActiveButton!==-1)return;this._activePointerId=r.pointerId;try{o==null||o.setPointerCapture(r.pointerId)}catch{}this._currentActiveButton===-1&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===Ke.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o==null||o.releasePointerCapture(r.pointerId)}catch{}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===Ke.POINTERMOVE&&(this._activePointerId===r.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const l=this.camera._calculateHandednessMultiplier(),h=(r.clientX-this._previousPosition.x)*l,c=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=h/this.angularSensibility,this.camera.cameraRotation.x+=c/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:h,offsetY:c}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}}),this._onMouseMove=s=>{if(!t.isPointerLock)return;const r=this.camera._calculateHandednessMultiplier(),n=s.movementX*r;this.camera.cameraRotation.y+=n/this.angularSensibility;const o=s.movementY;this.camera.cameraRotation.x+=o/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ke.POINTERDOWN|Ke.POINTERUP|Ke.POINTERMOVE),i&&(this._contextMenuBind=s=>this.onContextMenu(s),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([O()],ix.prototype,"buttons",void 0);v([O()],ix.prototype,"angularSensibility",void 0);Dr.FreeCameraMouseInput=ix;var Pi;(function(a){a[a.MoveRelative=0]="MoveRelative",a[a.RotateRelative=1]="RotateRelative",a[a.MoveScene=2]="MoveScene"})(Pi||(Pi={}));class co extends Zg{constructor(){super(...arguments),this._moveRelative=T.Zero(),this._rotateRelative=T.Zero(),this._moveScene=T.Zero(),this._wheelXAction=Pi.MoveRelative,this._wheelXActionCoordinate=Yh.X,this._wheelYAction=Pi.MoveRelative,this._wheelYActionCoordinate=Yh.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Pi.MoveRelative||(this._wheelXAction=Pi.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Pi.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Pi.MoveRelative||(this._wheelYAction=Pi.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Pi.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Pi.MoveRelative||(this._wheelZAction=Pi.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Pi.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Pi.RotateRelative||(this._wheelXAction=Pi.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Pi.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Pi.RotateRelative||(this._wheelYAction=Pi.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Pi.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Pi.RotateRelative||(this._wheelZAction=Pi.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Pi.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Pi.MoveScene||(this._wheelXAction=Pi.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Pi.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Pi.MoveScene||(this._wheelYAction=Pi.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Pi.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Pi.MoveScene||(this._wheelZAction=Pi.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Pi.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=L.Zero();this.camera.getViewMatrix().invertToRef(e);const t=T.Zero();T.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 s=null;switch(t){case Pi.MoveRelative:s=this._moveRelative;break;case Pi.RotateRelative:s=this._rotateRelative;break;case Pi.MoveScene:s=this._moveScene;break}switch(i){case Yh.X:s.set(e,0,0);break;case Yh.Y:s.set(0,e,0);break;case Yh.Z:s.set(0,0,e);break}}}v([O()],co.prototype,"wheelXMoveRelative",null);v([O()],co.prototype,"wheelYMoveRelative",null);v([O()],co.prototype,"wheelZMoveRelative",null);v([O()],co.prototype,"wheelXRotateRelative",null);v([O()],co.prototype,"wheelYRotateRelative",null);v([O()],co.prototype,"wheelZRotateRelative",null);v([O()],co.prototype,"wheelXMoveScene",null);v([O()],co.prototype,"wheelYMoveScene",null);v([O()],co.prototype,"wheelZMoveScene",null);Dr.FreeCameraMouseWheelInput=co;class sx{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=Z.IsSafari()}attachControl(e){e=Z.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r=s.pointerType==="mouse"||this._isSafari&&typeof s.pointerType>"u";if(!(!this.allowMouse&&r)){if(i.type===Ke.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),this._pointerPressed.length!==1)return;t={x:s.clientX,y:s.clientY}}else if(i.type===Ke.POINTERUP){e||s.preventDefault();const n=this._pointerPressed.indexOf(s.pointerId);if(n===-1||(this._pointerPressed.splice(n,1),n!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===Ke.POINTERMOVE){if(e||s.preventDefault(),!t||this._pointerPressed.indexOf(s.pointerId)!=0)return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ke.POINTERDOWN|Ke.POINTERUP|Ke.POINTERMOVE),this._onLostFocus){const s=this.camera.getEngine().getInputElement();s&&s.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 s=e._computeLocalCameraSpeed(),r=new T(0,0,this.touchMoveSensibility!==0?s*this._offsetY/this.touchMoveSensibility:0);L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(T.TransformCoordinates(r,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}v([O()],sx.prototype,"touchAngularSensibility",void 0);v([O()],sx.prototype,"touchMoveSensibility",void 0);Dr.FreeCameraTouchInput=sx;class rx extends Jg{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new _a),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ix(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new co,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new sx),this}clear(){super.clear(),this._mouseInput=null}}rx.prototype.addDeviceOrientation=function(a){return this._deviceOrientationInput||(this._deviceOrientationInput=new AP,a&&(this._deviceOrientationInput.smoothFactor=a),this.add(this._deviceOrientationInput)),this};class AP{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout(()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))},e),typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(n=>{n=="granted"?window.addEventListener("deviceorientation",r):Z.Warn("Permission not granted.")}).catch(n=>{Z.Error(n)}):window.addEventListener("deviceorientation",r)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new ae,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new K,this._orientationChanged=()=>{this._screenOrientationAngle=window.orientation!==void 0?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Z.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?Z.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=e.beta!==null?Z.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=e.gamma!==null?Z.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._constantTranform=new ae(-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 ae),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():Z.Warn("Permission not granted.")}).catch(i=>{Z.Error(i)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(ae.RotationYawPitchRollToRef(Z.ToRadians(this._alpha),Z.ToRadians(this._beta),-Z.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Dr.FreeCameraDeviceOrientationInput=AP;class nx{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=L.Identity(),this._deltaTransform=T.Zero(),this._vector3=T.Zero(),this._vector2=ce.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!==tr.POSE_ENABLED&&(!this.gamepad||t.type===tr.XBOX)&&(this.gamepad=t)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(t=>{this.gamepad===t&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(tr.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):L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=e._computeLocalCameraSpeed()*50;this._vector3.copyFromFloats(t.x*s,0,-t.y*s),T.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([O()],nx.prototype,"gamepadAngularSensibility",void 0);v([O()],nx.prototype,"gamepadMoveSensibility",void 0);Dr.FreeCameraGamepadInput=nx;var js;(function(a){a[a.X=0]="X",a[a.Y=1]="Y",a[a.Z=2]="Z"})(js||(js={}));class st{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={...st._GetDefaultOptions(),...t};if(e?this._leftJoystick=!0:this._leftJoystick=!1,st._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=js.X,this._axisTargetedByUpAndDown=js.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new GE,this.deltaPosition=T.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{st._VJCanvasWidth=window.innerWidth,st._VJCanvasHeight=window.innerHeight,st.Canvas&&(st.Canvas.width=st._VJCanvasWidth,st.Canvas.height=st._VJCanvasHeight),st._HalfWidth=st._VJCanvasWidth/2},!st.Canvas){window.addEventListener("resize",this._onResize,!1),st.Canvas=document.createElement("canvas"),st._VJCanvasWidth=window.innerWidth,st._VJCanvasHeight=window.innerHeight,st.Canvas.width=window.innerWidth,st.Canvas.height=window.innerHeight,st.Canvas.style.width="100%",st.Canvas.style.height="100%",st.Canvas.style.position="absolute",st.Canvas.style.backgroundColor="transparent",st.Canvas.style.top="0px",st.Canvas.style.left="0px",st.Canvas.style.zIndex="5",st.Canvas.style.touchAction="none",st.Canvas.setAttribute("touch-action","none");const s=st.Canvas.getContext("2d");if(!s)throw new Error("Unable to create canvas for virtual joystick");st._VJCanvasContext=s,st._VJCanvasContext.strokeStyle="#ffffff",st._VJCanvasContext.lineWidth=2,document.body.appendChild(st.Canvas)}st._HalfWidth=st.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&&st._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new ce(0,0),this._joystickPreviousPointerPos=new ce(0,0),this._joystickPointerStartPos=new ce(0,0),this._deltaJoystickVector=new ce(0,0),this._onPointerDownHandlerRef=s=>{this._onPointerDown(s)},this._onPointerMoveHandlerRef=s=>{this._onPointerMove(s)},this._onPointerUpHandlerRef=s=>{this._onPointerUp(s)},st.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),st.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),st.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),st.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),st.Canvas.addEventListener("contextmenu",s=>{s.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.clientXst._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)):st._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 n=new ce(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),o=n.length();o>this.containerSize&&n.scaleInPlace(this.containerSize/o),this._joystickPointerPos.x=this._joystickPointerStartPos.x+n.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+n.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?st._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,this.containerSize*2,this.containerSize*2):(st._VJCanvasContext.beginPath(),st._VJCanvasContext.strokeStyle=this._joystickColor,st._VJCanvasContext.lineWidth=2,st._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,Math.PI*2,!0),st._VJCanvasContext.stroke(),st._VJCanvasContext.closePath(),st._VJCanvasContext.beginPath(),st._VJCanvasContext.lineWidth=6,st._VJCanvasContext.strokeStyle=this._joystickColor,st._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,Math.PI*2,!0),st._VJCanvasContext.stroke(),st._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?st._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,this.puckSize*2,this.puckSize*2):(st._VJCanvasContext.beginPath(),st._VJCanvasContext.strokeStyle=this._joystickColor,st._VJCanvasContext.lineWidth=2,st._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,Math.PI*2,!0),st._VJCanvasContext.stroke(),st._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()):(st._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),st._VJCanvasContext.beginPath(),st._VJCanvasContext.fillStyle="white",st._VJCanvasContext.beginPath(),st._VJCanvasContext.strokeStyle="red",st._VJCanvasContext.lineWidth=6,st._VJCanvasContext.arc(t.x,t.y,40,0,Math.PI*2,!0),st._VJCanvasContext.stroke(),st._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){st.Canvas&&(st.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),st.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),st.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),st.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(st.Canvas),st.Canvas=null),this._released=!0}}st._GlobalJoystickIndex=0;st._AlwaysVisibleSticks=0;rx.prototype.addVirtualJoystick=function(){return this.add(new RP),this};class RP{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=e._computeLocalCameraSpeed()*50,i=L.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=T.TransformCoordinates(new T(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),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 st(!0),this._leftjoystick.setAxisForUpDown(js.Z),this._leftjoystick.setAxisForLeftRight(js.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new st(!1),this._rightjoystick.setAxisForUpDown(js.X),this._rightjoystick.setAxisForLeftRight(js.Y),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"}}Dr.FreeCameraVirtualJoystickInput=RP;Qt.AddNodeConstructor("TargetCamera",(a,e)=>()=>new ls(a,T.Zero(),e));class ls extends Ve{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=T.Zero(),this._tmpTargetVector=T.Zero(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new ce(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new ae,this.rotation=new T(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=T.Zero(),this._initialFocalDistance=1,this._viewMatrix=L.Zero(),this._camMatrix=L.Zero(),this._cameraTransformMatrix=L.Zero(),this._cameraRotationMatrix=L.Zero(),this._referencePoint=new T(0,0,1),this._transformedReferencePoint=T.Zero(),this._deferredPositionUpdate=new T,this._deferredRotationQuaternionUpdate=new ae,this._deferredRotationUpdate=new T,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=T.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 T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new ae(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+=At),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),L.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&&ae.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(W.Matrix[0]),T.TransformNormalToRef(this.cameraDirection,W.Matrix[0],W.Vector3[0]),this._deferredPositionUpdate.addInPlace(W.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()&&(ae.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(n),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>ee.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 rx(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Z.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0),this.cameraRotation=new ce(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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 s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=T.Zero(),this._transformedDirection=T.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([Sr()],ln.prototype,"ellipsoid",void 0);v([Sr()],ln.prototype,"ellipsoidOffset",void 0);v([O()],ln.prototype,"checkCollisions",void 0);v([O()],ln.prototype,"applyGravity",void 0);Qt.AddNodeConstructor("TouchCamera",(a,e)=>()=>new IP(a,T.Zero(),e));class IP extends ln{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=!1:e.allowMouse=!0}}Qt.AddNodeConstructor("ArcRotateCamera",(a,e)=>()=>new Ii(a,0,0,1,T.Zero(),e));class Ii extends ls{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 L,this._upToYMatrix=new L,this._upVector=T.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){L.RotationAlignToRef(T.UpReadOnly,this._upVector,this._yToUpMatrix),L.RotationAlignToRef(this._upVector,T.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 rc,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 gn,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 HV,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,T.Zero(),n,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=T.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=ce.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new L,this.panningAxis=new T(1,1,0),this._transformedDirection=new T,this.mapPanning=!1,this.onMeshTargetChangedObservable=new K,this.checkCollisions=!1,this.collisionRadius=new T(.5,.5,.5),this._previousPosition=T.Zero(),this._collisionVelocity=T.Zero(),this._newPosition=T.Zero(),this._computationVector=T.Zero(),this._onCollisionPositionChange=(l,h,c=null)=>{c?(this.setPosition(h),this.onCollide&&this.onCollide(c)):this._previousPosition.copyFrom(this._position);const u=Math.cos(this.alpha),d=Math.sin(this.alpha),f=Math.cos(this.beta);let m=Math.sin(this.beta);m===0&&(m=1e-4);const _=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*u*m,this.radius*f,this.radius*d*m),_.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let x=this.upVector;this.allowUpsideDown&&this.beta<0&&(x=x.clone(),x=x.negate()),this._computeViewMatrix(this._position,_,x),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=T.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Iv(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new T(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=ce.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 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,s=2){const r=arguments;t=Z.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,typeof r[0]=="boolean"&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[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.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)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)&&T.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,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,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 r=e,n=this._getTargetPosition();if(n&&!i&&n.equals(r))return;this._targetHost=null,this._target=r,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);s===0&&(s=1e-4),this.radius===0&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&T.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const n=this.getScene().collisionCoordinator;this._collider||(this._collider=n.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,n.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let n=this.upVector;this.allowUpsideDown&&s<0&&(n=n.negate()),this._computeViewMatrix(this._position,r,n),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=q.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(e.min===void 0){const r=e||this.getScene().meshes;i=q.MinMax(r),s=T.Distance(i.min,i.max)}else{const r=e;i=r,s=r.distance}this._target=q.Center(i),t||(this.maxZ=s*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case Ve.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}const s=new Ii(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Ve.RIG_MODE_STEREOSCOPIC_INTERLACED:case Ve.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Ve.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 s=T.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*n,c=s*.5*i,u=c*Math.sqrt(1+1/(l*l)),d=c*Math.sqrt(1+1/(o*o));return Math.max(u,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}v([O()],Ii.prototype,"alpha",void 0);v([O()],Ii.prototype,"beta",void 0);v([O()],Ii.prototype,"radius",void 0);v([O()],Ii.prototype,"overrideCloneAlphaBetaRadius",void 0);v([Sr("target")],Ii.prototype,"_target",void 0);v([i_("targetHost")],Ii.prototype,"_targetHost",void 0);v([O()],Ii.prototype,"inertialAlphaOffset",void 0);v([O()],Ii.prototype,"inertialBetaOffset",void 0);v([O()],Ii.prototype,"inertialRadiusOffset",void 0);v([O()],Ii.prototype,"lowerAlphaLimit",void 0);v([O()],Ii.prototype,"upperAlphaLimit",void 0);v([O()],Ii.prototype,"lowerBetaLimit",void 0);v([O()],Ii.prototype,"upperBetaLimit",void 0);v([O()],Ii.prototype,"lowerRadiusLimit",void 0);v([O()],Ii.prototype,"upperRadiusLimit",void 0);v([O()],Ii.prototype,"inertialPanningX",void 0);v([O()],Ii.prototype,"inertialPanningY",void 0);v([O()],Ii.prototype,"pinchToPanMaxDistance",void 0);v([O()],Ii.prototype,"panningDistanceLimit",void 0);v([Sr()],Ii.prototype,"panningOriginTarget",void 0);v([O()],Ii.prototype,"panningInertia",void 0);v([O()],Ii.prototype,"zoomToMouseLocation",null);v([O()],Ii.prototype,"zoomOnFactor",void 0);v([ev()],Ii.prototype,"targetScreenOffset",void 0);v([O()],Ii.prototype,"allowUpsideDown",void 0);v([O()],Ii.prototype,"useInputToRestoreState",void 0);Qt.AddNodeConstructor("DeviceOrientationCamera",(a,e)=>()=>new Pv(a,T.Zero(),e));class Pv extends ln{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new ae,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new ae,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(s=>{this._dragFactor!=0&&(this._initialQuaternion||(this._initialQuaternion=new ae),ae.FromEulerAnglesToRef(0,s.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=Vr.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new ae),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 a3 extends Jg{constructor(e){super(e)}addKeyboard(){return this.add(new yh),this}addMouse(){return this.add(new tx),this}}class ax extends ls{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,s=!0){super(e,t,i,s),this.ellipsoid=new T(1,1,1),this.ellipsoidOffset=new T(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=T.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=T.Zero(),this._diffPosition=T.Zero(),this._newPosition=T.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(r,n,o=null)=>{(h=>{this._newPosition.copyFrom(h),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>ee.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&o&&this.onCollide(o))})(n)},this.inputs=new a3(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Z.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new T(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=T.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 s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=T.Zero(),this._transformedDirection=T.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,s=t-i,r=.001;Math.abs(s)>=r&&(this.rotation.z+=s/e,Math.abs(t-this.rotation.z)<=r&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}v([Sr()],ax.prototype,"ellipsoid",void 0);v([Sr()],ax.prototype,"ellipsoidOffset",void 0);v([O()],ax.prototype,"checkCollisions",void 0);v([O()],ax.prototype,"applyGravity",void 0);class o3 extends Jg{constructor(e){super(e)}addKeyboard(){return this.add(new vr),this}addMouseWheel(){return this.add(new xc),this}addPointers(){return this.add(new yn),this}addVRDeviceOrientation(){return U.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Qt.AddNodeConstructor("FollowCamera",(a,e)=>()=>new ma(a,T.Zero(),e));Qt.AddNodeConstructor("ArcFollowCamera",(a,e)=>()=>new l3(a,0,0,1,null,e));class ma extends ls{constructor(e,t,i,s=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=s,this.inputs=new o3(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=W.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Z.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,l=n-this.position.x,h=r.y+this.heightOffset-this.position.y,c=o-this.position.z;let u=l*this.cameraAcceleration*2,d=h*this.cameraAcceleration,f=c*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<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 T(this.position.x+u,this.position.y+d,this.position.z+f),this.setTarget(r)}attachControl(e,t){t=Z.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([O()],ma.prototype,"radius",void 0);v([O()],ma.prototype,"lowerRadiusLimit",void 0);v([O()],ma.prototype,"upperRadiusLimit",void 0);v([O()],ma.prototype,"rotationOffset",void 0);v([O()],ma.prototype,"lowerRotationOffsetLimit",void 0);v([O()],ma.prototype,"upperRotationOffsetLimit",void 0);v([O()],ma.prototype,"heightOffset",void 0);v([O()],ma.prototype,"lowerHeightOffsetLimit",void 0);v([O()],ma.prototype,"upperHeightOffsetLimit",void 0);v([O()],ma.prototype,"cameraAcceleration",void 0);v([O()],ma.prototype,"maxCameraSpeed",void 0);v([i_("lockedTargetId")],ma.prototype,"lockedTarget",void 0);class l3 extends ls{constructor(e,t,i,s,r,n){super(e,T.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=T.Zero(),this.setMeshTarget(r)}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"}}var Un;(function(a){a[a.A=0]="A",a[a.B=1]="B",a[a.X=2]="X",a[a.Y=3]="Y",a[a.LB=4]="LB",a[a.RB=5]="RB",a[a.Back=8]="Back",a[a.Start=9]="Start",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(Un||(Un={}));var Zc;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(Zc||(Zc={}));class h3 extends tr{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,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=tr.XBOX,this._isXboxOnePad=s}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,Un.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Un.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Un.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Un.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Un.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Un.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Un.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Un.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Un.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Un.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Zc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Zc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Zc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Zc.Right)}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 Da;(function(a){a[a.Cross=0]="Cross",a[a.Circle=1]="Circle",a[a.Square=2]="Square",a[a.Triangle=3]="Triangle",a[a.L1=4]="L1",a[a.R1=5]="R1",a[a.Share=8]="Share",a[a.Options=9]="Options",a[a.LeftStick=10]="LeftStick",a[a.RightStick=11]="RightStick"})(Da||(Da={}));var Jc;(function(a){a[a.Up=12]="Up",a[a.Down=13]="Down",a[a.Left=14]="Left",a[a.Right=15]="Right"})(Jc||(Jc={}));class c3 extends tr{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 K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,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=tr.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,Da.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Da.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Da.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Da.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Da.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Da.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Da.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Da.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Da.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Da.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Jc.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Jc.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Jc.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Jc.Right)}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 u3{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new K,Vs()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new K(t=>{for(const i in this._babylonGamepads){const s=this._babylonGamepads[i];s&&s._isConnected&&this.onGamepadConnectedObservable.notifyObserver(t,s)}}),this._onGamepadConnectedEvent=t=>{const i=t.gamepad;if(i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected)return;let s;this._babylonGamepads[i.index]?(s=this._babylonGamepads[i.index],s.browserGamepad=i,s._isConnected=!0):s=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(s),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=t=>{const i=t.gamepad;for(const s in this._babylonGamepads)if(this._babylonGamepads[s].index===i.index){const r=this._babylonGamepads[s];r._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(r),r.dispose&&r.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=tr.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,s=e.id.search("Xbox One")!==-1;return s||e.id.search("Xbox 360")!==-1||e.id.search("xinput")!==-1||e.id.search("045e")!==-1&&e.id.search("Surface Dock")===-1?t=new h3(e.id,e.index,e,s):i?t=new c3(e.id,e.index,e):t=new r3(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&&(Z.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&ee.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new uf(a,T.Zero(),e));class uf extends IP{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"}}Ve._CreateDefaultParsedCamera=(a,e)=>new uf(a,T.Zero(),e);Qt.AddNodeConstructor("GamepadCamera",(a,e)=>()=>new Mv(a,T.Zero(),e));class Mv extends uf{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const f3="passCubePixelShader",p3=`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 +}`;j.ShadersStore[f3]=p3;class uo extends je{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,l=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,l)}static _Parse(e,t,i,s){return Pe.Parse(()=>new uo(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,s)}}H("BABYLON.PassPostProcess",uo);He._RescalePostProcessFactory=a=>new uo("rescale",1,null,2,a,!1,0);const _3="anaglyphPixelShader",m3=`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);}`;j.ShadersStore[_3]=m3;class PP extends je{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(o=>{o.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}H("BABYLON.AnaglyphPostProcess",PP);function ox(a){a._rigCameras[0]._rigPostProcess=new uo(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new PP(a.name+"_anaglyph",1,a._rigCameras)}Qt.AddNodeConstructor("AnaglyphArcRotateCamera",(a,e,t)=>()=>new g3(a,0,0,1,T.Zero(),t.interaxial_distance,e));class g3 extends Ii{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>ox(this),this.interaxialDistance=n,this.setCameraRigMode(Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Qt.AddNodeConstructor("AnaglyphFreeCamera",(a,e,t)=>()=>new x3(a,T.Zero(),t.interaxial_distance,e));class x3 extends ln{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>ox(this),this.interaxialDistance=i,this.setCameraRigMode(Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Qt.AddNodeConstructor("AnaglyphGamepadCamera",(a,e,t)=>()=>new T3(a,T.Zero(),t.interaxial_distance,e));class T3 extends Mv{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>ox(this),this.interaxialDistance=i,this.setCameraRigMode(Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Qt.AddNodeConstructor("AnaglyphUniversalCamera",(a,e,t)=>()=>new E3(a,T.Zero(),t.interaxial_distance,e));class E3 extends uf{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>ox(this),this.interaxialDistance=i,this.setCameraRigMode(Ve.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const S3="stereoscopicInterlacePixelShader",v3=`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);} +`;j.ShadersStore[S3]=v3;class C3 extends je{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new ce(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new ce(1/this.width,1/this.height)}),this.onApplyObservable.add(l=>{l.setTextureFromPostProcess("camASampler",this._passedProcess),l.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function lx(a){const e=a.cameraRigMode===Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||a.cameraRigMode===Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t=a.cameraRigMode===Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;a.cameraRigMode===Ve.RIG_MODE_STEREOSCOPIC_INTERLACED?(a._rigCameras[0]._rigPostProcess=new uo(a.name+"_passthru",1,a._rigCameras[0]),a._rigCameras[1]._rigPostProcess=new C3(a.name+"_stereoInterlace",a._rigCameras,!1,!0)):(a._rigCameras[t?1:0].viewport=new da(0,0,e?.5:1,e?1:.5),a._rigCameras[t?0:1].viewport=new da(e?.5:0,e?0:.5,e?.5:1,e?1:.5))}Qt.AddNodeConstructor("StereoscopicArcRotateCamera",(a,e,t)=>()=>new b3(a,0,0,1,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class b3 extends Ii{constructor(e,t,i,s,r,n,o,l){super(e,t,i,s,r,l),this._setRigMode=()=>lx(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Qt.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new y3(a,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class y3 extends ln{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>lx(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Qt.AddNodeConstructor("StereoscopicGamepadCamera",(a,e,t)=>()=>new A3(a,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class A3 extends Mv{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>lx(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Qt.AddNodeConstructor("StereoscopicFreeCamera",(a,e,t)=>()=>new R3(a,T.Zero(),t.interaxial_distance,t.isStereoscopicSideBySide,e));class R3 extends uf{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>lx(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?Ve.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ve.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}Qt.AddNodeConstructor("VirtualJoysticksCamera",(a,e)=>()=>new I3(a,T.Zero(),e));class I3 extends ln{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class df{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 L.Translation(t,0,0)}get rightHMatrix(){const t=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return L.Translation(-t,0,0)}get leftPreViewMatrix(){return L.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return L.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new df;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}}const P3="vrDistortionCorrectionPixelShader",M3=`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);}}`;j.ShadersStore[P3]=M3;class JA extends je{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,X.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new ce(2,2/this.aspectRatio),this._scaleFactor=new ce(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new ce(this._isRightEye?.5-this._lensCenterOffset*.5:.5+this._lensCenterOffset*.5,.5)}),this.onApplyObservable.add(r=>{r.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),r.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),r.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),r.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}const O3="vrMultiviewToSingleviewPixelShader",D3=`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));}`;j.ShadersStore[O3]=D3;class $E extends Yi{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}}ee.prototype.createMultiviewRenderTargetTexture=function(a,e,t,i){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:a,height:e});r._framebuffer=s.createFramebuffer();const n=new $t(this,xt.Unknown,!0);return n.width=a,n.height=e,n.isMultiview=!0,t||(t=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,t),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,a,e,2)),r._colorTextureArray=t,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,a,e,2)),r._depthStencilTextureArray=i,n.isReady=!0,r.setTextures(n),r._depthStencilTexture=n,r};ee.prototype.bindMultiviewFramebuffer=function(a){const e=a,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"};ee.prototype.bindSpaceWarpFramebuffer=function(a){const e=a,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")};Ve.prototype._useMultiviewToSingleView=!1;Ve.prototype._multiviewTexture=null;Ve.prototype._resizeOrCreateMultiviewTexture=function(a,e){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=a||this._multiviewTexture.getRenderHeight()!=e)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new $E(this.getScene(),{width:a,height:e})):this._multiviewTexture=new $E(this.getScene(),{width:a,height:e})};function MP(a,e){const t=new ze(a,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 N3=Ue.prototype.createSceneUniformBuffer;Ue.prototype._transformMatrixR=L.Zero();Ue.prototype._multiviewSceneUbo=null;Ue.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=MP(this.getEngine(),"scene_multiview")};Ue.prototype.createSceneUniformBuffer=function(a){return this._multiviewSceneUbo?MP(this.getEngine(),a):N3.bind(this)(a)};Ue.prototype._updateMultiviewUbo=function(a,e){a&&e&&a.multiplyToRef(e,this._transformMatrixR),a&&e&&(a.multiplyToRef(e,W.Matrix[0]),oa.GetRightPlaneToRef(W.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))};Ue.prototype._renderMultiviewToSingleView=function(a){a._resizeOrCreateMultiviewTexture(a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.width>0?a._rigPostProcess.width:this.getEngine().getRenderWidth(!0),a._rigPostProcess&&a._rigPostProcess&&a._rigPostProcess.height>0?a._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),a.outputRenderTarget=a._multiviewTexture,this._renderForCamera(a),a.outputRenderTarget=null;for(let e=0;e{}),this.onApplyObservable.add(r=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?r.setInt("imageIndex",0):r.setInt("imageIndex",1),r.setTexture("multiviewSampler",s._multiviewTexture)})}}function Ov(a,e){const t=e.vrCameraMetrics||df.GetDefault();a._rigCameras[0]._cameraRigParams.vrMetrics=t,a._rigCameras[0].viewport=new da(0,0,.5,1),a._rigCameras[0]._cameraRigParams.vrWorkMatrix=new L,a._rigCameras[0]._cameraRigParams.vrHMatrix=t.leftHMatrix,a._rigCameras[0]._cameraRigParams.vrPreViewMatrix=t.leftPreViewMatrix,a._rigCameras[0].getProjectionMatrix=a._rigCameras[0]._getVRProjectionMatrix,a._rigCameras[1]._cameraRigParams.vrMetrics=t,a._rigCameras[1].viewport=new da(.5,0,.5,1),a._rigCameras[1]._cameraRigParams.vrWorkMatrix=new L,a._rigCameras[1]._cameraRigParams.vrHMatrix=t.rightHMatrix,a._rigCameras[1]._cameraRigParams.vrPreViewMatrix=t.rightPreViewMatrix,a._rigCameras[1].getProjectionMatrix=a._rigCameras[1]._getVRProjectionMatrix,t.multiviewEnabled&&(a.getScene().getEngine().getCaps().multiview?(a._useMultiviewToSingleView=!0,a._rigPostProcess=new w3("VRMultiviewToSingleview",a,t.postProcessScaleFactor)):(U.Warn("Multiview is not supported, falling back to standard rendering"),t.multiviewEnabled=!1)),t.compensateDistortion&&(a._rigCameras[0]._rigPostProcess=new JA("VR_Distort_Compensation_Left",a._rigCameras[0],!1,t),a._rigCameras[1]._rigPostProcess=new JA("VR_Distort_Compensation_Right",a._rigCameras[1],!0,t))}Qt.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(a,e)=>()=>new F3(a,0,0,1,T.Zero(),e));class F3 extends Ii{constructor(e,t,i,s,r,n,o=!0,l=df.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=h=>Ov(this,h),l.compensateDistortion=o,this.setCameraRigMode(Ve.RIG_MODE_VR,{vrCameraMetrics:l}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Qt.AddNodeConstructor("VRDeviceOrientationFreeCamera",(a,e)=>()=>new Dv(a,T.Zero(),e));class Dv extends Pv{constructor(e,t,i,s=!0,r=df.GetDefault()){super(e,t,i),this._setRigMode=n=>Ov(this,n),r.compensateDistortion=s,this.setCameraRigMode(Ve.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Qt.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(a,e)=>()=>new L3(a,T.Zero(),e));class L3 extends Dv{constructor(e,t,i,s=!0,r=df.GetDefault()){super(e,t,i,s,r),this._setRigMode=n=>Ov(this,n),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class pg{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&t.prePassRenderer.getIndex(2)!==-1){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const n=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==n.frameId&&(this._lastUpdateFrameId=n.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class Ce{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,ee.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,ee.MarkAllMaterialsAsDirty(1))}}Ce._DiffuseTextureEnabled=!0;Ce._DetailTextureEnabled=!0;Ce._DecalMapEnabled=!0;Ce._AmbientTextureEnabled=!0;Ce._OpacityTextureEnabled=!0;Ce._ReflectionTextureEnabled=!0;Ce._EmissiveTextureEnabled=!0;Ce._SpecularTextureEnabled=!0;Ce._BumpTextureEnabled=!0;Ce._LightmapTextureEnabled=!0;Ce._RefractionTextureEnabled=!0;Ce._ColorGradingTextureEnabled=!0;Ce._FresnelEnabled=!0;Ce._ClearCoatTextureEnabled=!0;Ce._ClearCoatBumpTextureEnabled=!0;Ce._ClearCoatTintTextureEnabled=!0;Ce._SheenTextureEnabled=!0;Ce._AnisotropicTextureEnabled=!0;Ce._ThicknessTextureEnabled=!0;Ce._RefractionIntensityTextureEnabled=!0;Ce._TranslucencyIntensityTextureEnabled=!0;Ce._TranslucencyColorTextureEnabled=!0;Ce._IridescenceTextureEnabled=!0;const B3="decalFragmentDeclaration",U3=`#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`;j.IncludesShadersStore[B3]=U3;const V3="defaultFragmentDeclaration",k3=`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 +`;j.IncludesShadersStore[V3]=k3;const G3="sceneUboDeclaration",z3=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;j.IncludesShadersStore[G3]=z3;const W3="meshUboDeclaration",H3=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;j.IncludesShadersStore[W3]=H3;const X3="defaultUboDeclaration",Y3=`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 +`;j.IncludesShadersStore[X3]=Y3;const $3="prePassDeclaration",K3=`#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`;j.IncludesShadersStore[$3]=K3;const j3="oitDeclaration",q3=`#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 +`;j.IncludesShadersStore[j3]=q3;const Q3="mainUVVaryingDeclaration",Z3=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;j.IncludesShadersStore[Q3]=Z3;const J3="helperFunctions",ek=`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;} +`;j.IncludesShadersStore[J3]=ek;const tk="lightFragmentDeclaration",ik=`#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 shadowSampler{X};uniform highp sampler2DArray depthSampler{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 shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{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 shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{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 projectionLightSampler{X}; +#endif +#endif +`;j.IncludesShadersStore[tk]=ik;const sk="lightUboDeclaration",rk=`#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 projectionLightSampler{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 shadowSampler{X};uniform highp sampler2DArray depthSampler{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 shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{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 shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;j.IncludesShadersStore[sk]=rk;const nk="lightsFragmentFunctions",ak=`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){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;j.IncludesShadersStore[nk]=ak;const ok="shadowsFragmentFunctions",lk=`#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 +/* 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(_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 +`;j.IncludesShadersStore[Sk]=vk;const Ck="clipPlaneFragmentDeclaration",bk=`#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 +`;j.IncludesShadersStore[Ck]=bk;const yk="logDepthDeclaration",Ak=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;j.IncludesShadersStore[yk]=Ak;const Rk="fogFragmentDeclaration",Ik=`#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +#define E 2.71828 +uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() +{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`;j.IncludesShadersStore[Rk]=Ik;const Pk="clipPlaneFragment",Mk=`#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 +`;j.IncludesShadersStore[Pk]=Mk;const Ok="bumpFragment",Dk=`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 +`;j.IncludesShadersStore[Ok]=Dk;const Nk="decalFragment",wk=`#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 +`;j.IncludesShadersStore[Nk]=wk;const Fk="depthPrePass",Lk=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;j.IncludesShadersStore[Fk]=Lk;const Bk="lightFragment",Uk=`#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); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#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(projectionLightSampler{X},textureProjectionMatrix{X}); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +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}],shadowSampler{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}],shadowSampler{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}],shadowSampler{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}],depthSampler{X},shadowSampler{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}],depthSampler{X},shadowSampler{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}],depthSampler{X},shadowSampler{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}],shadowSampler{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}],shadowSampler{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}],shadowSampler{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}],shadowSampler{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}],depthSampler{X},shadowSampler{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}],depthSampler{X},shadowSampler{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}],depthSampler{X},shadowSampler{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}],shadowSampler{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,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{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,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{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,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{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},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{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},depthSampler{X},shadowSampler{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},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{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,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{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 +`;j.IncludesShadersStore[Bk]=Uk;const Vk="logDepthFragment",kk=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;j.IncludesShadersStore[Vk]=kk;const Gk="fogFragment",zk=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;j.IncludesShadersStore[Gk]=zk;const Wk="oitFragment",Hk=`#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 && fragDepth +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include[SCENE_MRT_COUNT] +#include +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include[1..7] +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#else +float glossiness=0.; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULARTERM) +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`;j.ShadersStore[Xk]=Yk;const $k="decalVertexDeclaration",Kk=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;j.IncludesShadersStore[$k]=Kk;const jk="defaultVertexDeclaration",qk=`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 +`;j.IncludesShadersStore[jk]=qk;const Qk="uvAttributeDeclaration",Zk=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;j.IncludesShadersStore[Qk]=Zk;const Jk="bonesDeclaration",eG=`#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 +`;j.IncludesShadersStore[Jk]=eG;const tG="bakedVertexAnimationDeclaration",iG=`#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 +`;j.IncludesShadersStore[tG]=iG;const sG="instancesDeclaration",rG=`#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform mat4 previousWorld; +#endif +#endif +`;j.IncludesShadersStore[sG]=rG;const nG="prePassVertexDeclaration",aG=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;j.IncludesShadersStore[nG]=aG;const oG="samplerVertexDeclaration",lG=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;j.IncludesShadersStore[oG]=lG;const hG="bumpVertexDeclaration",cG=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;j.IncludesShadersStore[hG]=cG;const uG="clipPlaneVertexDeclaration",dG=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`;j.IncludesShadersStore[uG]=dG;const fG="fogVertexDeclaration",pG=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;j.IncludesShadersStore[fG]=pG;const _G="lightVxFragmentDeclaration",mG=`#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 +`;j.IncludesShadersStore[_G]=mG;const gG="lightVxUboDeclaration",xG=`#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 +`;j.IncludesShadersStore[gG]=xG;const TG="morphTargetsVertexGlobalDeclaration",EG=`#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 +`;j.IncludesShadersStore[TG]=EG;const SG="morphTargetsVertexDeclaration",vG=`#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 +`;j.IncludesShadersStore[SG]=vG;const CG="morphTargetsVertexGlobal",bG=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;j.IncludesShadersStore[CG]=bG;const yG="morphTargetsVertex",AG=`#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 +`;j.IncludesShadersStore[yG]=AG;const RG="instancesVertex",IG=`#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`;j.IncludesShadersStore[RG]=IG;const PG="bonesVertex",MG=`#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 +`;j.IncludesShadersStore[PG]=MG;const OG="bakedVertexAnimation",DG=`#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 +`;j.IncludesShadersStore[OG]=DG;const NG="prePassVertex",wG=`#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`;j.IncludesShadersStore[NG]=wG;const FG="uvVariableDeclaration",LG=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;j.IncludesShadersStore[FG]=LG;const BG="samplerVertexImplementation",UG=`#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 +`;j.IncludesShadersStore[BG]=UG;const VG="bumpVertex",kG=`#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 +`;j.IncludesShadersStore[VG]=kG;const GG="clipPlaneVertex",zG=`#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`;j.IncludesShadersStore[GG]=zG;const WG="fogVertex",HG=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;j.IncludesShadersStore[WG]=HG;const XG="shadowsVertex",YG=`#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include[1..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#include +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;j.ShadersStore[JG]=ez;const tz=new RegExp("^([gimus]+)!");class th{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let s=0;sthis._handlePluginEvent(s,r),this._plugins.push(e),this._plugins.sort((s,r)=>s.priority-r.priority),this._codeInjectionPoints={};const i={};i[th._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const s of this._plugins)s.collectDefines(i),this._collectPointNames("vertex",s.getCustomCode("vertex")),this._collectPointNames("fragment",s.getCustomCode("fragment"));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 gr.PrepareUniformBuffer:{const i=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const s of this._plugins){const r=s.getUniforms();if(r){if(r.ubo)for(const n of r.ubo){if(n.size&&n.type){const o=n.arraySize??0;i.ubo.addUniform(n.name,n.size,o),this._uboDeclaration+=`${n.type} ${n.name}${o>0?`[${o}]`:""}; +`}this._uniformList.push(n.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+` +`),r.fragment&&(this._fragmentDeclaration+=r.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,s)=>{var o,l;t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!r)return s;let n=null;for(let h in r){let c="";for(const u of this._activePlugins){let d=(l=u.getCustomCode(i))==null?void 0:l[h];if(d){if(u.resolveIncludes){if(n===null){const f=vt.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:j.GetShadersRepository(f),includesShadersStore:j.GetIncludesShadersStore(f),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment=i==="fragment",Mp(d,n,f=>d=f)}c+=d+` +`}}if(c.length>0)if(h.charAt(0)==="!"){h=h.substring(1);let u="g";if(h.charAt(0)==="!")u="",h=h.substring(1);else{const _=tz.exec(h);_&&_.length>=2&&(u=_[1],h=h.substring(u.length+1))}u.indexOf("g")<0&&(u+="g");const d=s,f=new RegExp(h,u);let m=f.exec(d);for(;m!==null;){let _=c;for(let x=0;x{sz()});const iz=[];let e0=null;function sz(){iz.length=0,pe.OnEventObservable.remove(e0),e0=null}class hn{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new th(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){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(){return{}}copyTo(e){Pe.Clone(()=>e,this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse(()=>this,e,t,i)}}v([O()],hn.prototype,"name",void 0);v([O()],hn.prototype,"priority",void 0);v([O()],hn.prototype,"resolveIncludes",void 0);v([O()],hn.prototype,"registerForExtraEvents",void 0);class rz extends Gr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Ah extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new rz,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=pe.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&&Ce.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&&Ce.DetailTextureEnabled&&this._isEnabled?(Oi(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&&Ce.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),wi(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Ce.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([Dt("detailTexture"),_e("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"texture",void 0);v([O()],Ah.prototype,"diffuseBlendLevel",void 0);v([O()],Ah.prototype,"roughnessBlendLevel",void 0);v([O()],Ah.prototype,"bumpLevel",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"normalBlendMethod",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ah.prototype,"isEnabled",void 0);const dE={effect:null,subMesh:null};class nz extends Gr{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class Ie extends cf{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){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new re(0,0,0),this.diffuseColor=new re(1,1,1),this.specularColor=new re(1,1,1),this.emissiveColor=new re(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Ps(16),this._worldViewProjectionMatrix=L.Zero(),this._globalAmbientColor=new re(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Ah(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new pg,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Ie.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),Ie.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 Ie.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||Ie.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===pe.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==pe.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 s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(gr.GetDefineNames,this._eventInfo),t.materialDefines=new nz(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=c_(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),Yg(r,n);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Ev(r,n,this.canRenderToMRT&&!l),hP(r,n,l),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let c=1;c<=6;++c)n["MAINUV"+c]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&Ie.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())Oi(this._diffuseTexture,n,"DIFFUSE");else return!1;else n.DIFFUSE=!1;if(this._ambientTexture&&Ie.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())Oi(this._ambientTexture,n,"AMBIENT");else return!1;else n.AMBIENT=!1;if(this._opacityTexture&&Ie.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())Oi(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else n.OPACITY=!1;if(this._reflectionTexture&&Ie.ReflectionTextureEnabled)if(this._reflectionTexture.isReadyOrNotBlocking()){switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===X.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case X.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case X.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case X.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case X.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case X.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case X.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case X.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case X.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case X.CUBIC_MODE:case X.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC");break}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else return!1;else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&Ie.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())Oi(this._emissiveTexture,n,"EMISSIVE");else return!1;else n.EMISSIVE=!1;if(this._lightmapTexture&&Ie.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())Oi(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else n.LIGHTMAP=!1;if(this._specularTexture&&Ie.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())Oi(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Ie.BumpTextureEnabled){if(this._bumpTexture.isReady())Oi(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&Ie.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,n.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(Ie.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),Wg(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Hg(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Xg(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(n.isDirty){const c=n._areLightsDisposed;n.markAsProcessed();const u=new gc;n.REFLECTION&&u.addFallback(0,"REFLECTION"),n.SPECULAR&&u.addFallback(0,"SPECULAR"),n.BUMP&&u.addFallback(0,"BUMP"),n.PARALLAX&&u.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&u.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&u.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&u.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&u.addFallback(1,"FOG"),n.POINTSIZE&&u.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&u.addFallback(0,"LOGARITHMICDEPTH"),xv(n,u,this._maxSimultaneousLights),n.SPECULARTERM&&u.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&u.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&u.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&u.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&u.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&u.addFallback(4,"FRESNEL"),n.MULTIVIEW&&u.addFallback(0,"MULTIVIEW");const d=[P.PositionKind];n.NORMAL&&d.push(P.NormalKind),n.TANGENT&&d.push(P.TangentKind);for(let I=1;I<=6;++I)n["UV"+I]&&d.push(`uv${I===1?"":I}`);n.VERTEXCOLOR&&d.push(P.ColorKind),gv(d,e,n,u),zg(d,n),pv(d,e,n),_v(d,e,n);let f="default";const m=["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"],_=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],x=["Material","Scene","Mesh"],E={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=u,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=m,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=x,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=E,this._callbackPluginEventGeneric(gr.PrepareEffect,this._eventInfo),pg.AddUniforms(m),Mt&&(Mt.PrepareUniforms(m,n),Mt.PrepareSamplers(_,n)),$g({uniformsNames:m,uniformBuffersNames:x,samplers:_,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),Va(m);const S={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,m,x,_,n,d,S));const C=n.toString(),y=t.effect;let A=r.getEngine().createEffect(f,{attributes:d,uniformsNames:m,uniformBuffersNames:x,samplers:_,defines:C,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:E,processFinalCode:S.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,A)if(this._onEffectCreatedObservable&&(dE.effect=A,dE.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dE)),this.allowShaderHotSwapping&&y&&!A.isReady()){if(A=y,n.markAsUnprocessed(),h=this.isFrozen,c)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(A,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!h,s._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 h;const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);l_(t,n);const l=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!l.useUbo||!this.isFrozen||!l.isSync||i._drawWrapper._forceRebindOnNextCall){if(Ie.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new re(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&Ie.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),wi(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&Ie.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),wi(this._ambientTexture,l,"ambient")),this._opacityTexture&&Ie.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),wi(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&Ie.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const c=this._reflectionTexture;l.updateVector3("vReflectionPosition",c.boundingBoxPosition),l.updateVector3("vReflectionSize",c.boundingBoxSize)}if(this._emissiveTexture&&Ie.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),wi(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&Ie.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),wi(this._lightmapTexture,l,"lightmap")),this._specularTexture&&Ie.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),wi(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&Ie.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),wi(this._bumpTexture,l,"bump"),s._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&&Ie.RefractionTextureEnabled){let c=1;if(this._refractionTexture.isCube||(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(c=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,c,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const u=this._refractionTexture;l.updateVector3("vRefractionPosition",u.boundingBoxPosition),l.updateVector3("vRefractionSize",u.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",Ie.EmissiveTextureEnabled?this.emissiveColor:re.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&Ie.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&Ie.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Ie.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&Ie.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&Ie.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Ie.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&Ie.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&Ie.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&Ie.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),pa(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&h_(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Ue.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),mc(s,t,n),r.NUM_MORPH_INFLUENCERS&&Al(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&((h=t.bakedVertexAnimationManager)==null||h.bind(n,r.INSTANCES)),this.useLogarithmicDepth&&Ch(r,n,s),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,s,r,n,o,l,h,c,u;t&&((i=this._diffuseTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(r=this._opacityTexture)==null||r.dispose(),(n=this._reflectionTexture)==null||n.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(h=this._bumpTexture)==null||h.dispose(),(c=this._lightmapTexture)==null||c.dispose(),(u=this._refractionTexture)==null||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Pe.Clone(()=>new Ie(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Pe.Parse(()=>new Ie(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),pe._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return Ce.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Ce.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Ce.DetailTextureEnabled}static set DetailTextureEnabled(e){Ce.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Ce.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Ce.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Ce.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Ce.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Ce.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Ce.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Ce.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Ce.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Ce.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Ce.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Ce.BumpTextureEnabled}static set BumpTextureEnabled(e){Ce.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Ce.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Ce.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Ce.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Ce.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Ce.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Ce.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Ce.FresnelEnabled}static set FresnelEnabled(e){Ce.FresnelEnabled=e}}v([Dt("diffuseTexture")],Ie.prototype,"_diffuseTexture",void 0);v([_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Ie.prototype,"diffuseTexture",void 0);v([Dt("ambientTexture")],Ie.prototype,"_ambientTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"ambientTexture",void 0);v([Dt("opacityTexture")],Ie.prototype,"_opacityTexture",void 0);v([_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Ie.prototype,"opacityTexture",void 0);v([Dt("reflectionTexture")],Ie.prototype,"_reflectionTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"reflectionTexture",void 0);v([Dt("emissiveTexture")],Ie.prototype,"_emissiveTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"emissiveTexture",void 0);v([Dt("specularTexture")],Ie.prototype,"_specularTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"specularTexture",void 0);v([Dt("bumpTexture")],Ie.prototype,"_bumpTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"bumpTexture",void 0);v([Dt("lightmapTexture")],Ie.prototype,"_lightmapTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"lightmapTexture",void 0);v([Dt("refractionTexture")],Ie.prototype,"_refractionTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"refractionTexture",void 0);v([Vi("ambient")],Ie.prototype,"ambientColor",void 0);v([Vi("diffuse")],Ie.prototype,"diffuseColor",void 0);v([Vi("specular")],Ie.prototype,"specularColor",void 0);v([Vi("emissive")],Ie.prototype,"emissiveColor",void 0);v([O()],Ie.prototype,"specularPower",void 0);v([O("useAlphaFromDiffuseTexture")],Ie.prototype,"_useAlphaFromDiffuseTexture",void 0);v([_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Ie.prototype,"useAlphaFromDiffuseTexture",void 0);v([O("useEmissiveAsIllumination")],Ie.prototype,"_useEmissiveAsIllumination",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useEmissiveAsIllumination",void 0);v([O("linkEmissiveWithDiffuse")],Ie.prototype,"_linkEmissiveWithDiffuse",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"linkEmissiveWithDiffuse",void 0);v([O("useSpecularOverAlpha")],Ie.prototype,"_useSpecularOverAlpha",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useSpecularOverAlpha",void 0);v([O("useReflectionOverAlpha")],Ie.prototype,"_useReflectionOverAlpha",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useReflectionOverAlpha",void 0);v([O("disableLighting")],Ie.prototype,"_disableLighting",void 0);v([_e("_markAllSubMeshesAsLightsDirty")],Ie.prototype,"disableLighting",void 0);v([O("useObjectSpaceNormalMap")],Ie.prototype,"_useObjectSpaceNormalMap",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useObjectSpaceNormalMap",void 0);v([O("useParallax")],Ie.prototype,"_useParallax",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useParallax",void 0);v([O("useParallaxOcclusion")],Ie.prototype,"_useParallaxOcclusion",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useParallaxOcclusion",void 0);v([O()],Ie.prototype,"parallaxScaleBias",void 0);v([O("roughness")],Ie.prototype,"_roughness",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"roughness",void 0);v([O()],Ie.prototype,"indexOfRefraction",void 0);v([O()],Ie.prototype,"invertRefractionY",void 0);v([O()],Ie.prototype,"alphaCutOff",void 0);v([O("useLightmapAsShadowmap")],Ie.prototype,"_useLightmapAsShadowmap",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useLightmapAsShadowmap",void 0);v([t_("diffuseFresnelParameters")],Ie.prototype,"_diffuseFresnelParameters",void 0);v([_e("_markAllSubMeshesAsFresnelDirty")],Ie.prototype,"diffuseFresnelParameters",void 0);v([t_("opacityFresnelParameters")],Ie.prototype,"_opacityFresnelParameters",void 0);v([_e("_markAllSubMeshesAsFresnelAndMiscDirty")],Ie.prototype,"opacityFresnelParameters",void 0);v([t_("reflectionFresnelParameters")],Ie.prototype,"_reflectionFresnelParameters",void 0);v([_e("_markAllSubMeshesAsFresnelDirty")],Ie.prototype,"reflectionFresnelParameters",void 0);v([t_("refractionFresnelParameters")],Ie.prototype,"_refractionFresnelParameters",void 0);v([_e("_markAllSubMeshesAsFresnelDirty")],Ie.prototype,"refractionFresnelParameters",void 0);v([t_("emissiveFresnelParameters")],Ie.prototype,"_emissiveFresnelParameters",void 0);v([_e("_markAllSubMeshesAsFresnelDirty")],Ie.prototype,"emissiveFresnelParameters",void 0);v([O("useReflectionFresnelFromSpecular")],Ie.prototype,"_useReflectionFresnelFromSpecular",void 0);v([_e("_markAllSubMeshesAsFresnelDirty")],Ie.prototype,"useReflectionFresnelFromSpecular",void 0);v([O("useGlossinessFromSpecularMapAlpha")],Ie.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"useGlossinessFromSpecularMapAlpha",void 0);v([O("maxSimultaneousLights")],Ie.prototype,"_maxSimultaneousLights",void 0);v([_e("_markAllSubMeshesAsLightsDirty")],Ie.prototype,"maxSimultaneousLights",void 0);v([O("invertNormalMapX")],Ie.prototype,"_invertNormalMapX",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"invertNormalMapX",void 0);v([O("invertNormalMapY")],Ie.prototype,"_invertNormalMapY",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"invertNormalMapY",void 0);v([O("twoSidedLighting")],Ie.prototype,"_twoSidedLighting",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ie.prototype,"twoSidedLighting",void 0);v([O("applyDecalMapAfterDetailMap")],Ie.prototype,"_applyDecalMapAfterDetailMap",void 0);v([_e("_markAllSubMeshesAsMiscDirty")],Ie.prototype,"applyDecalMapAfterDetailMap",void 0);H("BABYLON.StandardMaterial",Ie);Ue.DefaultMaterialFactory=a=>new Ie("default material",a);nt.prototype.createDynamicTexture=function(a,e,t,i){const s=new $t(this,xt.Dynamic);return s.baseWidth=a,s.baseHeight=e,t&&(a=this.needPOTTextures?on(a,this._caps.maxTextureSize):a,e=this.needPOTTextures?on(e,this._caps.maxTextureSize):e),s.width=a,s.height=e,s.isReady=!1,s.generateMipMaps=t,s.samplingMode=i,this.updateTextureSamplingMode(i,s),this._internalTexturesCache.push(s),s};nt.prototype.updateDynamicTexture=function(a,e,t,i=!1,s,r=!1,n=!1){if(!a)return;const o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,a,!0,r);this._unpackFlipY(t===void 0?a.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(a.type),u=this._getInternalFormat(s||a.format),d=this._getRGBABufferInternalSizedFormat(a.type,u);o.texImage2D(l,0,d,u,c,e),a.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(a.format=s),a._dynamicTextureSource=e,a._premulAlpha=i,a.invertY=t||!1,a.isReady=!0};class Bp extends X{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=X.CLAMP_ADDRESSMODE,this.wrapV=X.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const l=this._getEngine();if(!l)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=l.createCanvas(1,1),this._ownCanvas=!0,t.width||t.width===0?this._texture=l.createDynamicTexture(t.width,t.height,s,r):this._texture=l.createDynamicTexture(t,t,s,r));const h=this.getSize();this._canvas.width!==h.width&&(this._canvas.width=h.width),this._canvas.height!==h.height&&(this._canvas.height=h.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,s,r,n,o,l=!0){const h=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,h.width,h.height)),this._context.font=s,t==null){const c=this._context.measureText(e);t=(h.width-c.width)/2}if(i==null){const c=parseInt(s.replace(/\D/g,""));i=h.height/2+c/3.65}this._context.fillStyle=r||"",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 Bp(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()&&U.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Bp._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 Nv{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,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class wv{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new $t(this._engine,xt.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new of(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},l=n?new $E(this._scene,o):new Yi("XR renderTargetTexture",o,this._scene),h=l.renderTarget;if(h._samples=l.samples,(i||!s)&&(h._framebuffer=i),s)if(n)h._colorTextureArray=s;else{const c=this._createInternalTexture(o,s);h.setTexture(c,0),l._texture=c}return r&&(n?h._depthStencilTextureArray=r:h._depthStencilTexture=this._createInternalTexture(o,r)),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 Fv extends Nv{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new az(t.scene,this)),this.layer=e}}class az extends wv{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 s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return(!this._rtt||t!==this._framebufferDimensions.framebufferWidth||i!==this._framebufferDimensions.framebufferHeight||s!==this._framebuffer)&&(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class hx{static GetDefaults(e){const t=new hx;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 oz{constructor(e,t=hx.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new K,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()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Fv(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{Z.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>t()):Promise.resolve(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 lz extends Nv{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",t=>new hz(t,this)),this.layer=e}}class hz extends wv{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 cz{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 cx{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 K,this.onXRReferenceSpaceChanged=new K,this.onXRSessionEnded=new K,this.onXRSessionInit=new K,this.onXRReferenceSpaceInitialized=new K,this.onXRReady=new K,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new K(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{U.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 cz(this):(e=e||hx.GetDefaults(t),e.canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new oz(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 s;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&&((s=this._baseLayerRTTProvider)==null||s.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return cx.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 s;if(!(!this.inXRSession||!this._engine)&&(this.currentFrame=i,this.currentTimestamp=t,i)){this.inXRFrameLoop=!0;const r=((s=this._baseLayerRTTProvider)==null?void 0:s.getFramebufferDimensions())||null;this._engine.framebufferDimensionsObject!==r&&(this._engine.framebufferDimensionsObject=r),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=>(U.Error("XR.requestReferenceSpace failed for the following reason: "),U.Error(t),U.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(i=>{const s=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return i.getOffsetReferenceSpace(s)},i=>{throw U.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 lz(e.baseLayer):new Fv(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 s=typeof i>"u"?!0:i;return Promise.resolve(s)}).catch(i=>(U.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}}var Bs;(function(a){a[a.ENTERING_XR=0]="ENTERING_XR",a[a.EXITING_XR=1]="EXITING_XR",a[a.IN_XR=2]="IN_XR",a[a.NOT_IN_XR=3]="NOT_IN_XR"})(Bs||(Bs={}));var eu;(function(a){a[a.NOT_TRACKING=0]="NOT_TRACKING",a[a.TRACKING_LOST=1]="TRACKING_LOST",a[a.TRACKING=2]="TRACKING"})(eu||(eu={}));q._GroundMeshParser=(a,e)=>d_.Parse(a,e);class d_ extends q{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(),s=W.Matrix[5];i.invertToRef(s);const r=W.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.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 n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return T.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new T(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=W.Matrix[5];s.invertToRef(r);const n=W.Vector3[8];if(T.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return T.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,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),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return ta.maxHeight){h=!0;const u=a.maxHeight;a.maxHeight=a.minHeight,a.minHeight=u}for(r=0;r<=a.subdivisions;r++)for(n=0;n<=a.subdivisions;n++){const u=new T(n*a.width/a.subdivisions-a.width/2,0,(a.subdivisions-r)*a.height/a.subdivisions-a.height/2),d=(u.x+a.width/2)/a.width*(a.bufferWidth-1)|0,f=(1-(u.z+a.height/2)/a.height)*(a.bufferHeight-1)|0,m=(d+f*a.bufferWidth)*4;let _=a.buffer[m]/255,x=a.buffer[m+1]/255,E=a.buffer[m+2]/255;const S=a.buffer[m+3]/255;h&&(_=1-_,x=1-x,E=1-E);const C=_*o.r+x*o.g+E*o.b;S>=l?u.y=a.minHeight+(a.maxHeight-a.minHeight)*C:u.y=a.minHeight-At,a.heightBuffer&&(a.heightBuffer[r*(a.subdivisions+1)+n]=u.y),t.push(u.x,u.y,u.z),i.push(0,0,0),s.push(n/a.subdivisions,1-r/a.subdivisions)}for(r=0;r=a.minHeight,x=t[d*3+1]>=a.minHeight,E=t[f*3+1]>=a.minHeight;_&&x&&E&&(e.push(u),e.push(d),e.push(f)),t[m*3+1]>=a.minHeight&&_&&E&&(e.push(m),e.push(u),e.push(f))}Se.ComputeNormals(t,e,i);const c=new Se;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function Lv(a,e={},t){const i=new d_(a,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,ol(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function uz(a,e,t=null){const i=new q(a,t);return OP(e).applyToMesh(i,e.updatable),i}function dz(a,e,t={},i=null){const s=t.width||10,r=t.height||10,n=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,h=t.colorFilter||new re(.3,.59,.11),c=t.alphaFilter||0,u=t.updatable,d=t.onReady;i=i||We.LastCreatedScene;const f=new d_(a,i);f._subdivisionsX=n,f._subdivisionsY=n,f._width=s,f._height=r,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);let m;t.passHeightBufferInCallback&&(m=new Float32Array((n+1)*(n+1)));const _=(x,E,S)=>{DP({width:s,height:r,subdivisions:n,minHeight:o,maxHeight:l,colorFilter:h,buffer:x,bufferWidth:E,bufferHeight:S,alphaFilter:c,heightBuffer:m}).applyToMesh(f,u),d&&d(f,m),f._setReady(!0)};if(typeof e=="string"){const x=E=>{const S=E.width,C=E.height;if(i.isDisposed)return;const y=i==null?void 0:i.getEngine().resizeImageBitmap(E,S,C);_(y,S,C)};Z.LoadImage(e,x,t.onError?t.onError:()=>{},i.offlineProvider)}else _(e.data,e.width,e.height);return f}Se.CreateGround=ol;Se.CreateTiledGround=OP;Se.CreateGroundFromHeightMap=DP;q.CreateGround=(a,e,t,i,s,r)=>Lv(a,{width:e,height:t,subdivisions:i,updatable:r},s);q.CreateTiledGround=(a,e,t,i,s,r,n,o,l)=>uz(a,{xmin:e,zmin:t,xmax:i,zmax:s,subdivisions:r,precision:n,updatable:l},o);q.CreateGroundFromHeightMap=(a,e,t,i,s,r,n,o,l,h,c)=>dz(a,e,{width:t,height:i,subdivisions:s,minHeight:r,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},o);function Bv(a){const e=[],t=[],i=[],s=[],r=a.diameter||1,n=a.thickness||.5,o=(a.tessellation||16)|0,l=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,h=o+1;for(let u=0;u<=o;u++){const d=u/o,f=u*Math.PI*2/o-Math.PI/2,m=L.Translation(r/2,0,0).multiply(L.RotationY(f));for(let _=0;_<=o;_++){const x=1-_/o,E=_*Math.PI*2/o+Math.PI,S=Math.cos(E),C=Math.sin(E);let y=new T(S,C,0),A=y.scale(n/2);const I=new ce(d,x);A=T.TransformCoordinates(A,m),y=T.TransformNormal(y,m),t.push(A.x,A.y,A.z),i.push(y.x,y.y,y.z),s.push(I.x,Ht.UseOpenGLOrientationForUV?1-I.y:I.y);const R=(u+1)%h,N=(_+1)%h;e.push(u*h+_),e.push(u*h+N),e.push(R*h+_),e.push(u*h+N),e.push(R*h+N),e.push(R*h+_)}}Se._ComputeSides(l,t,e,i,s,a.frontUVs,a.backUVs);const c=new Se;return c.indices=e,c.positions=t,c.normals=i,c.uvs=s,c}function vu(a,e={},t){const i=new q(a,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Bv(e).applyToMesh(i,e.updatable),i}Se.CreateTorus=Bv;q.CreateTorus=(a,e,t,i,s,r,n)=>vu(a,{diameter:e,thickness:t,tessellation:i,sideOrientation:n,updatable:r},s);class ux{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=ux._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=vu("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const i=new Ie("targetMat",e);i.specularColor=re.Black(),i.emissiveColor=new re(.7,.7,.7),i.backFaceCulling=!1,this._gazeTracker.material=i}}_getForwardRay(e){return new Ct(T.Zero(),new T(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()}}ux._IdCounter=0;class t0 extends ux{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Ct(T.Zero(),T.Forward())}}class Cu{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 K,this.onAfterEnteringVRObservable=new K,this.onExitingVRObservable=new K,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Cu.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new T(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new T(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new re(.2,.2,1),this._pickedGazeColor=new re(0,0,1),this.onNewMeshSelected=new K,this.onNewMeshPicked=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onSelectedMeshUnselected=new K,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=s=>{s.type!==tr.POSE_ENABLED&&(s.leftStick&&s.onleftstickchanged(r=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(r,this._cameraGazer),this._checkTeleportBackwards(r,this._cameraGazer))}),s.rightStick&&s.onrightstickchanged(r=>{this._teleportationInitialized&&this._checkRotate(r,this._cameraGazer)}),s.type===tr.XBOX&&(s.onbuttondown(r=>{this._interactionsEnabled&&r===Un.A&&this._cameraGazer._selectionPointerDown()}),s.onbuttonup(r=>{this._interactionsEnabled&&r===Un.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=T.Zero(),this._workingQuaternion=ae.Identity(),this._workingMatrix=L.Identity(),U.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 T(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Pv("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 ls&&this._scene.activeCamera.rotation)){const s=this._scene.activeCamera;s.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(s.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(ae.RotationYawPitchRoll(s.rotation.y,s.rotation.x,s.rotation.z)),this._deviceOrientationCamera.rotation=s.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?cx.IsSessionSupportedAsync("immersive-vr").then(s=>{s?(U.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(r=>{this.xr=r,this.xrTestDone=!0,this._cameraGazer=new t0(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(n=>{switch(n){case Bs.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Bs.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Bs.IN_XR:this._hasEnteredVR=!0;break;case Bs.NOT_IN_XR:this._hasEnteredVR=!1;break}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Dv("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new t0(()=>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 r=".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) }";r+=".babylonVRicon.vrdisplaypresenting { display: none; }";const n=document.createElement("style");n.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(n),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=s=>{s.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())},Ke.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new mV,this._circleEase.setEasingMode(kr.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(s=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&s.event.pointerType==="mouse"&&(s.type===Ke.POINTERDOWN?this._cameraGazer._selectionPointerDown():s.type===Ke.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===Bs.IN_XR||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){U.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=ae.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){U.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===Bs.IN_XR&&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 s=this._scene.getMeshByName(e.floorMeshName);s&&i.push(s)}if(this.xr){i.forEach(s=>{this.xr.teleportation.addFloorMesh(s)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}else if(!this.xrTestDone){const s=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(s),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(s);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 Mt;t.vignetteColor=new Oe(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=ae.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),s=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,ae.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),T.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new Ct(s,this._workingVector),n=this._scene.pickWithRay(r,this._raySelectionPredicate);n&&n.pickedPoint&&n.pickedMesh&&this._isTeleportationFloor(n.pickedMesh)&&n.distance<5&&this.teleportCamera(n.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Lv("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=512,t=new Bp("DynamicTexture",e,this._scene,!0);t.hasAlpha=!0;const i=t.getContext(),s=e/2,r=e/2,n=200;i.beginPath(),i.arc(s,r,n,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 Ie("TextPlaneMaterial",this._scene);o.diffuseTexture=t,this._teleportationTarget.material=o;const l=vu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);l.isPickable=!1,l.parent=this._teleportationTarget;const h=new te("animationInnerCircle","position.y",30,te.ANIMATIONTYPE_FLOAT,te.ANIMATIONLOOPMODE_CYCLE),c=[];c.push({frame:0,value:0}),c.push({frame:30,value:.4}),c.push({frame:60,value:0}),h.setKeys(c);const u=new KI;u.setEasingMode(kr.EASINGMODE_EASEINOUT),h.setEasingFunction(u),l.animations=[],l.animations.push(h),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 ln))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=ae.FromRotationMatrix(L.RotationY(Math.PI/4*this._rotationAngle)),i=new te("animationRotation","rotationQuaternion",90,te.ANIMATIONTYPE_QUATERNION,te.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new te("animationPP","vignetteWeight",90,te.ANIMATIONTYPE_FLOAT,te.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new te("animationPP2","vignetteStretch",90,te.ANIMATIONTYPE_FLOAT,te.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 ln))return;this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector);const t=90;let i,s;if(this._teleportationMode==Cu.TELEPORTATIONMODE_CONSTANTSPEED){s=t;const d=T.Distance(this.currentVRCamera.position,this._workingVector);i=this._teleportationSpeed/d}else s=Math.round(this._teleportationTime*t/1e3),i=1;this.currentVRCamera.animations=[];const r=new te("animationCameraTeleportation","position",t,te.ANIMATIONTYPE_VECTOR3,te.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:s,value:this._workingVector}];r.setKeys(n),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];const o=Math.round(s/2),l=new te("animationPP","vignetteWeight",t,te.ANIMATIONTYPE_FLOAT,te.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:o,value:8}),h.push({frame:s,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l);const c=new te("animationPP2","vignetteStretch",t,te.ANIMATIONTYPE_FLOAT,te.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:o,value:10}),u.push({frame:s,value:0}),c.setKeys(u),this._postProcessMove.animations.push(c),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,s,!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"}}Cu.TELEPORTATIONMODE_CONSTANTTIME=0;Cu.TELEPORTATIONMODE_CONSTANTSPEED=1;const fz=(a,e,t,i)=>!(a.x>t.x+i||t.x-i>e.x||a.y>t.y+i||t.y-i>e.y||a.z>t.z+i||t.z-i>e.z),Hc=function(){const a={root:0,found:!1};return function(e,t,i,s){a.root=0,a.found=!1;const r=t*t-4*e*i;if(r<0)return a;const n=Math.sqrt(r);let o=(-t-n)/(2*e),l=(-t+n)/(2*e);if(o>l){const h=l;l=o,o=h}return o>0&&o0&&l=0)}_canDoCollision(e,t,i,s){const r=T.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!fz(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let l,h=!1;t||(t=[]),t[e]||(t[e]=new nn(0,0,0,0),t[e].copyFromPoints(i,s,r));const c=t[e];if(!n&&!c.isFrontFacingTo(this._normalizedVelocity,0))return;const u=c.signedDistanceTo(this._basePoint),d=T.Dot(c.normal,this._velocity);if(dx.DoubleSidedCheck&&d>1e-4)return;if(d==0){if(Math.abs(u)>=1)return;h=!0,l=0}else{l=(-1-u)/d;let _=(1-u)/d;if(l>_){const x=_;_=l,l=x}if(l>1||_<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let f=!1,m=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,c.normal)&&(f=!0,m=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!f){let _=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let x=2*T.Dot(this._velocity,this._tempVector),E=this._tempVector.lengthSquared()-1,S=Hc(_,x,E,m);S.found&&(m=S.root,f=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),x=2*T.Dot(this._velocity,this._tempVector),E=this._tempVector.lengthSquared()-1,S=Hc(_,x,E,m),S.found&&(m=S.root,f=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),x=2*T.Dot(this._velocity,this._tempVector),E=this._tempVector.lengthSquared()-1,S=Hc(_,x,E,m),S.found&&(m=S.root,f=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let C=this._edge.lengthSquared(),y=T.Dot(this._edge,this._velocity),A=T.Dot(this._edge,this._baseToVertex);if(_=C*-this._velocitySquaredLength+y*y,x=2*(C*T.Dot(this._velocity,this._baseToVertex)-y*A),E=C*(1-this._baseToVertex.lengthSquared())+A*A,S=Hc(_,x,E,m),S.found){const I=(y*S.root-A)/C;I>=0&&I<=1&&(m=S.root,f=!0,this._edge.scaleInPlace(I),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),y=T.Dot(this._edge,this._velocity),A=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+y*y,x=2*(C*T.Dot(this._velocity,this._baseToVertex)-y*A),E=C*(1-this._baseToVertex.lengthSquared())+A*A,S=Hc(_,x,E,m),S.found){const I=(y*S.root-A)/C;I>=0&&I<=1&&(m=S.root,f=!0,this._edge.scaleInPlace(I),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),C=this._edge.lengthSquared(),y=T.Dot(this._edge,this._velocity),A=T.Dot(this._edge,this._baseToVertex),_=C*-this._velocitySquaredLength+y*y,x=2*(C*T.Dot(this._velocity,this._baseToVertex)-y*A),E=C*(1-this._baseToVertex.lengthSquared())+A*A,S=Hc(_,x,E,m),S.found){const I=(y*S.root-A)/C;I>=0&&I<=1&&(m=S.root,f=!0,this._edge.scaleInPlace(I),r.addToRef(this._edge,this._collisionPoint))}}if(f){const _=m*m*this._velocitySquaredLength;(!this.collisionFound||_=s){r.copyFrom(e);return}const l=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const h=n&&n.surroundingMeshes||this._scene.meshes;for(let c=0;cnew pz;class bu{constructor(e,t,i,s=""){this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this.onBindObservable=new K,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=vt.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=bu._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=j.GetShadersStore(this._shaderLanguage),this._shaderRepository=j.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=j.GetIncludesShadersStore(this._shaderLanguage);let r;const n=Vs()?this._engine.getHostDocument():null;typeof e=="string"?r=e:e.computeSource?r="source:"+e.computeSource:e.computeElement?r=(n==null?void 0:n.getElementById(e.computeElement))||e.computeElement:r=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};this._loadShader(r,"Compute","",l=>{bI(o),kU(l,o,h=>{this._rawComputeSourceCode=l,t.processFinalCode&&(h=t.processFinalCode(h));const c=yI(h,"",o);this._useFinalCode(c.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,s){if(typeof HTMLElement<"u"&&e instanceof HTMLElement){const n=sv(e);s(n);return}if(e.substr(0,7)==="source:"){s(e.substr(7));return}if(e.substr(0,7)==="base64:"){const n=window.atob(e.substr(7));s(n);return}if(this._shaderStore[e+t+"Shader"]){s(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){s(this._shaderStore[e+i+"Shader"]);return}let r;e[0]==="."||e[0]==="/"||e.indexOf("http")>-1?r=e:r=this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}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,s=>{if(s&&s.numErrors>0){this._processCompilationErrors(s,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="",U.Error("Unable to compile compute effect:"),this.defines&&U.Error(`Defines: +`+this.defines),bu.LogShaderCodeOnCompilationError){const s=(i=this._pipelineContext)==null?void 0:i._getComputeShaderCode();s&&(U.Error("Compute code:"),U.Error(s))}if(typeof e=="string")this._compilationError=e,U.Error("Error: "+this._compilationError);else for(const s of e.messages){let r="";s.line!==void 0&&(r+="Line "+s.line+", "),s.offset!==void 0&&(r+="Offset "+s.offset+", "),s.length!==void 0&&(r+="Length "+s.length+", "),r+=s.type+": "+s.text,this._compilationError&&(this._compilationError+=` +`),this._compilationError+=r,U.Error(r)}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){j.GetShadersStore(vt.WGSL)[`${e}ComputeShader`]=t}}bu._UniqueIdSeed=0;bu.LogShaderCodeOnCompilationError=!0;var Si;(function(a){a[a.Texture=0]="Texture",a[a.StorageTexture=1]="StorageTexture",a[a.UniformBuffer=2]="UniformBuffer",a[a.StorageBuffer=3]="StorageBuffer",a[a.TextureWithoutSampler=4]="TextureWithoutSampler",a[a.Sampler=5]="Sampler",a[a.ExternalTexture=6]="ExternalTexture",a[a.DataBuffer=7]="DataBuffer"})(Si||(Si={}));nt.prototype.createComputeEffect=function(a,e){throw new Error("createComputeEffect: This engine does not support compute shaders!")};nt.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")};nt.prototype.createComputeContext=function(){};nt.prototype.computeDispatch=function(a,e,t,i,s,r,n){throw new Error("computeDispatch: This engine does not support compute shaders!")};nt.prototype.computeDispatchIndirect=function(a,e,t,i,s,r){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")};nt.prototype.areAllComputeEffectsReady=function(){return!0};nt.prototype.releaseComputeEffects=function(){};nt.prototype._prepareComputePipelineContext=function(a,e,t,i,s){};nt.prototype._rebuildComputeEffects=function(){};He.prototype._executeWhenComputeStateIsCompiled=function(a,e){e(null)};nt.prototype._releaseComputeEffect=function(a){};nt.prototype._deleteComputePipelineContext=function(a){};class Uv{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Xn}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()})}serialize(){const e=Pe.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],s=i.object;switch(i.type){case Si.Texture:case Si.TextureWithoutSampler:case Si.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case Si.UniformBuffer:break}}return e}static Parse(e,t,i){const s=Pe.Parse(()=>new dl(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=X.Parse(e.textures[r],t,i);n.type===Si.Texture?s.setTexture(r,o):n.type===Si.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return e.underlyingResource!==void 0}}v([O()],dl.prototype,"name",void 0);v([O()],dl.prototype,"fastMode",void 0);H("BABYLON.ComputeShader",dl);class _g{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,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=a.getBoundingInfo();!a.isBlocked&&t.boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};yu.CreationFuncForSubMeshes=(a,e)=>{a.getBoundingInfo().boundingBox.intersectsMinMax(e.minPoint,e.maxPoint)&&e.entries.push(a)};Ue.prototype.createOrUpdateSelectionOctree=function(a=64,e=2){let t=this._getComponent(ve.NAME_OCTREE);t||(t=new NP(this),this._addComponent(t)),this._selectionOctree||(this._selectionOctree=new yu(yu.CreationFuncForMeshes,a,e));const i=this.getWorldExtends();return this._selectionOctree.update(i.min,i.max,this.meshes),this._selectionOctree};Object.defineProperty(Ue.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0});Ft.prototype.createOrUpdateSubmeshesOctree=function(a=64,e=2){const t=this.getScene();let i=t._getComponent(ve.NAME_OCTREE);i||(i=new NP(t),t._addComponent(i)),this._submeshesOctree||(this._submeshesOctree=new yu(yu.CreationFuncForSubMeshes,a,e)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class NP{constructor(e){this.name=ve.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Ct(T.Zero(),new T(1,1,1)),e=e||We.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?(Ct.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 Vv(a){const e=a.height||2;let t=a.diameterTop===0?0:a.diameterTop||a.diameter||1,i=a.diameterBottom===0?0:a.diameterBottom||a.diameter||1;t=t||1e-5,i=i||1e-5;const s=(a.tessellation||24)|0,r=(a.subdivisions||1)|0,n=!!a.hasRings,o=!!a.enclose,l=a.cap===0?0:a.cap||q.CAP_ALL,h=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,c=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,u=a.faceUV||new Array(3),d=a.faceColors,f=h!==1&&o?2:0,m=n?r:1,_=2+(1+f)*m;let x;for(x=0;x<_;x++)d&&d[x]===void 0&&(d[x]=new Oe(1,1,1,1));for(x=0;x<_;x++)u&&u[x]===void 0&&(u[x]=new tt(0,0,1,1));const E=[],S=[],C=[],y=[],A=[],I=Math.PI*2*h/s;let R,N,k;const B=(i-t)/2/e,Q=T.Zero(),ne=T.Zero(),de=T.Zero(),ge=T.Zero(),fe=T.Zero(),Ee=Vr.Y;let De,Te,ue,oe=1,F=1,ie=0,he=0;for(De=0;De<=r;De++)for(N=De/r,k=(N*(t-i)+i)/2,oe=n&&De!==0&&De!==r?2:1,ue=0;ue{const Ae=ye?t/2:i/2;if(Ae===0)return;let rt,Ze,Et;const Re=ye?u[_-1]:u[0];let St=null;d&&(St=ye?d[_-1]:d[0]);const Lt=S.length/3,Ci=ye?e/2:-e/2,ki=new T(0,Ci,0);S.push(ki.x,ki.y,ki.z),C.push(0,ye?1:-1,0);const Ts=Re.y+(Re.w-Re.y)*.5;y.push(Re.x+(Re.z-Re.x)*.5,Ht.UseOpenGLOrientationForUV?1-Ts:Ts),St&&A.push(St.r,St.g,St.b,St.a);const ar=new ce(.5,.5);for(Et=0;Et<=s;Et++){rt=Math.PI*2*Et*h/s;const fo=Math.cos(-rt),Rn=Math.sin(-rt);Ze=new T(fo*Ae,Ci,Rn*Ae);const br=new ce(fo*ar.x+.5,Rn*ar.y+.5);S.push(Ze.x,Ze.y,Ze.z),C.push(0,ye?1:-1,0);const qr=Re.y+(Re.w-Re.y)*br.y;y.push(Re.x+(Re.z-Re.x)*br.x,Ht.UseOpenGLOrientationForUV?1-qr:qr),St&&A.push(St.r,St.g,St.b,St.a)}for(Et=0;Et((n===void 0||!(n instanceof Ue))&&(n!==void 0&&(l=o||q.DEFAULTSIDE,o=n),n=r,r=1),kv(a,{height:e,diameterTop:t,diameterBottom:i,tessellation:s,subdivisions:r,sideOrientation:l,updatable:o},n));Qt.AddNodeConstructor("Light_Type_3",(a,e)=>()=>new Rh(a,T.Zero(),e));class Rh extends yt{constructor(e,t,i){super(e,i),this.groundColor=new re(0,0,0),this.direction=t||T.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=T.Normalize(e.subtract(T.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=T.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=T.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=L.Identity()),this._worldMatrix}getTypeID(){return yt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}v([Vi()],Rh.prototype,"groundColor",void 0);v([Sr()],Rh.prototype,"direction",void 0);class Cs{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 Rh("shared gizmo light",new T(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=re.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return Cs._DefaultUtilityLayer==null?Cs._CreateDefaultUtilityLayerFromScene(We.LastCreatedScene):Cs._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Cs._DefaultUtilityLayer=new Cs(e),Cs._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Cs._DefaultUtilityLayer=null}),Cs._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return Cs._DefaultKeepDepthUtilityLayer==null&&(Cs._DefaultKeepDepthUtilityLayer=new Cs(We.LastCreatedScene),Cs._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Cs._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{Cs._DefaultKeepDepthUtilityLayer=null})),Cs._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 K,this.utilityLayerScene=new Ue(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!==Ke.POINTERMOVE&&i.type!==Ke.POINTERUP&&i.type!==Ke.POINTERDOWN&&i.type!==Ke.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const s=i.event;if(e.isPointerCaptured(s.pointerId)){this._pointerCaptures[s.pointerId]=!1;return}const r=o=>{let l=null;if(i.nearInteractionPickingInfo)i.nearInteractionPickingInfo.pickedMesh.getScene()==o?l=i.nearInteractionPickingInfo:l=new zs;else if(o!==this.utilityLayerScene&&i.originalPickingInfo)l=i.originalPickingInfo;else{let h=null;this._renderCamera&&(h=o._activeCamera,o._activeCamera=this._renderCamera,i.ray=null),l=i.ray?o.pickWithRay(i.ray):o.pick(e.pointerX,e.pointerY),h&&(o._activeCamera=h)}return l},n=r(this.utilityLayerScene);if(!i.ray&&n&&(i.ray=n.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(i),this.onlyCheckPointerDownEvents&&i.type!=Ke.POINTERDOWN){i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new wa(i.type,i.event,n),i.type),i.type===Ke.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)n&&n.hit&&(i.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new wa(i.type,i.event,n),i.type),i.skipOnPointerObservable=!0);else{const o=r(e),l=i.event;o&&n&&(n.distance===0&&o.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):i.type===Ke.POINTERDOWN?this._pointerCaptures[l.pointerId]=!0:(i.type===Ke.POINTERMOVE||i.type===Ke.POINTERUP)&&(this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,o,l)):!this._pointerCaptures[l.pointerId]&&(n.distance0)):!this._pointerCaptures[l.pointerId]&&n.distance>=o.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(o.pickedMesh)?(this._notifyObservers(i,o,l),i.skipOnPointerObservable=!0):((i.type===Ke.POINTERMOVE||i.type===Ke.POINTERUP)&&this._lastPointerEvents[l.pointerId]&&(this.onPointerOutObservable.notifyObservers(l.pointerId),delete this._lastPointerEvents[l.pointerId]),this._notifyObservers(i,n,l))),i.type===Ke.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 wa(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()}}Cs._DefaultUtilityLayer=null;Cs._DefaultKeepDepthUtilityLayer=null;var i0;(function(a){a[a.Origin=0]="Origin",a[a.Pivot=1]="Pivot"})(i0||(i0={}));var s0;(function(a){a[a.World=0]="World",a[a.Local=1]="Local"})(s0||(s0={}));Object.defineProperty(Ue.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new Au(this)),this._debugLayer},enumerable:!0,configurable:!0});var r0;(function(a){a[a.Properties=0]="Properties",a[a.Debug=1]="Debug",a[a.Statistics=2]="Statistics",a[a.Tools=3]="Tools",a[a.Settings=4]="Settings"})(r0||(r0={}));class Au{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new K),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new K),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||We.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={...Au.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)}show(e){return new Promise(t=>{if(typeof this.BJSINSPECTOR>"u"){const i=e&&e.inspectorURL?e.inspectorURL:Au.InspectorURL;Z.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}Au.InspectorURL=`${Z._DefaultCdnUrl}/v${ee.Version}/inspector/babylon.inspector.bundle.js`;Au.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};function Gv(a){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],s=[];let r=[];const n=a.width||a.size||1,o=a.height||a.size||1,l=a.depth||a.size||1,h=a.wrap||!1;let c=a.topBaseAt===void 0?1:a.topBaseAt,u=a.bottomBaseAt===void 0?0:a.bottomBaseAt;c=(c+4)%4,u=(u+4)%4;const d=[2,0,3,1],f=[2,0,1,3];let m=d[c],_=f[u],x=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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(h){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],x=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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 R=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],N=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const k=[17,18,19,16],B=[22,23,20,21];for(;m>0;)R.unshift(R.pop()),k.unshift(k.pop()),m--;for(;_>0;)N.unshift(N.pop()),B.unshift(B.pop()),_--;R=R.flat(),N=N.flat(),x=x.concat(R).concat(N),t.push(k[0],k[2],k[3],k[0],k[1],k[2]),t.push(B[0],B[2],B[3],B[0],B[1],B[2])}const E=[n/2,o/2,l/2];r=x.reduce((R,N,k)=>R.concat(N*E[k%3]),[]);const S=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,C=a.faceUV||new Array(6),y=a.faceColors,A=[];for(let R=0;R<6;R++)C[R]===void 0&&(C[R]=new tt(0,0,1,1)),y&&y[R]===void 0&&(y[R]=new Oe(1,1,1,1));for(let R=0;R<6;R++)if(s.push(C[R].z,Ht.UseOpenGLOrientationForUV?1-C[R].w:C[R].w),s.push(C[R].x,Ht.UseOpenGLOrientationForUV?1-C[R].w:C[R].w),s.push(C[R].x,Ht.UseOpenGLOrientationForUV?1-C[R].y:C[R].y),s.push(C[R].z,Ht.UseOpenGLOrientationForUV?1-C[R].y:C[R].y),y)for(let N=0;N<4;N++)A.push(y[R].r,y[R].g,y[R].b,y[R].a);Se._ComputeSides(S,r,t,i,s,a.frontUVs,a.backUVs);const I=new Se;if(I.indices=t,I.positions=r,I.normals=i,I.uvs=s,y){const R=S===Se.DOUBLESIDE?A.concat(A):A;I.colors=R}return I}function _z(a){const e=a.width||a.size||1,t=a.height||a.size||1,i=a.depth||a.size||1,s=(a.widthSegments||a.segments||1)|0,r=(a.heightSegments||a.segments||1)|0,n=(a.depthSegments||a.segments||1)|0,o=new L,l=new L,h=new L,c=ol({width:e,height:i,subdivisionsX:s,subdivisionsY:n});L.TranslationToRef(0,-t/2,0,l),L.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),c.transform(h);const u=ol({width:e,height:i,subdivisionsX:s,subdivisionsY:n});L.TranslationToRef(0,t/2,0,h),u.transform(h);const d=ol({width:t,height:i,subdivisionsX:r,subdivisionsY:n});L.TranslationToRef(-e/2,0,0,l),L.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);const f=ol({width:t,height:i,subdivisionsX:r,subdivisionsY:n});L.TranslationToRef(e/2,0,0,l),L.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h);const m=ol({width:e,height:t,subdivisionsX:s,subdivisionsY:r});L.TranslationToRef(0,0,-i/2,l),L.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),m.transform(h);const _=ol({width:e,height:t,subdivisionsX:s,subdivisionsY:r});return L.TranslationToRef(0,0,i/2,l),L.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h),c.merge([u,f,d,m,_],!0),c}function zv(a,e={},t=null){const i=new q(a,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Gv(e).applyToMesh(i,e.updatable),i}Se.CreateBox=Gv;q.CreateBox=(a,e,t=null,i,s)=>zv(a,{size:e,sideOrientation:s,updatable:i},t);function Wv(a){const e=(a.segments||32)|0,t=a.diameterX||a.diameter||1,i=a.diameterY||a.diameter||1,s=a.diameterZ||a.diameter||1,r=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,n=a.slice&&a.slice<=0?1:a.slice||1,o=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,l=!!a.dedupTopBottomIndices,h=new T(t/2,i/2,s/2),c=2+e,u=2*c,d=[],f=[],m=[],_=[];for(let E=0;E<=c;E++){const S=E/c,C=S*Math.PI*n;for(let y=0;y<=u;y++){const A=y/u,I=A*Math.PI*2*r,R=L.RotationZ(-C),N=L.RotationY(I),k=T.TransformCoordinates(T.Up(),R),B=T.TransformCoordinates(k,N),Q=B.multiply(h),ne=B.divide(h).normalize();f.push(Q.x,Q.y,Q.z),m.push(ne.x,ne.y,ne.z),_.push(A,Ht.UseOpenGLOrientationForUV?1-S:S)}if(E>0){const y=f.length/3;for(let A=y-2*(u+1);A+u+21&&(d.push(A),d.push(A+1),d.push(A+u+1)),(EGo(a,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:r,updatable:s},i);function Hv(a={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const e=Math.max(a.subdivisions?a.subdivisions:2,1)|0,t=Math.max(a.tessellation?a.tessellation:16,3)|0,i=Math.max(a.height?a.height:1,0),s=Math.max(a.radius?a.radius:.25,0),r=Math.max(a.capSubdivisions?a.capSubdivisions:6,1)|0,n=t,o=e,l=Math.max(a.radiusTop?a.radiusTop:s,0),h=Math.max(a.radiusBottom?a.radiusBottom:s,0),c=i-(l+h),u=0,d=2*Math.PI,f=Math.max(a.topCapSubdivisions?a.topCapSubdivisions:r,1),m=Math.max(a.bottomCapSubdivisions?a.bottomCapSubdivisions:r,1),_=Math.acos((h-l)/i);let x=[];const E=[],S=[],C=[];let y=0;const A=[],I=c*.5,R=Math.PI*.5;let N,k;const B=T.Zero(),Q=T.Zero(),ne=Math.cos(_),de=Math.sin(_),ge=new ce(l*de,I+l*ne).subtract(new ce(h*de,-I+h*ne)).length(),fe=l*_+ge+h*(R-_);let Ee=0;for(k=0;k<=f;k++){const oe=[],F=R-_*(k/f);Ee+=l*_/f;const ie=Math.cos(F),he=Math.sin(F),ke=ie*l;for(N=0;N<=n;N++){const Ye=N/n,et=Ye*d+u,ye=Math.sin(et),Ae=Math.cos(et);Q.x=ke*ye,Q.y=I+he*l,Q.z=ke*Ae,E.push(Q.x,Q.y,Q.z),B.set(ie*ye,he,ie*Ae),S.push(B.x,B.y,B.z),C.push(Ye,Ht.UseOpenGLOrientationForUV?Ee/fe:1-Ee/fe),oe.push(y),y++}A.push(oe)}const De=i-l-h+ne*l-ne*h,Te=de*(h-l)/De;for(k=1;k<=o;k++){const oe=[];Ee+=ge/o;const F=de*(k*(h-l)/o+l);for(N=0;N<=n;N++){const ie=N/n,he=ie*d+u,ke=Math.sin(he),Ye=Math.cos(he);Q.x=F*ke,Q.y=I+ne*l-k*De/o,Q.z=F*Ye,E.push(Q.x,Q.y,Q.z),B.set(ke,Te,Ye).normalize(),S.push(B.x,B.y,B.z),C.push(ie,Ht.UseOpenGLOrientationForUV?Ee/fe:1-Ee/fe),oe.push(y),y++}A.push(oe)}for(k=1;k<=m;k++){const oe=[],F=R-_-(Math.PI-_)*(k/m);Ee+=h*_/m;const ie=Math.cos(F),he=Math.sin(F),ke=ie*h;for(N=0;N<=n;N++){const Ye=N/n,et=Ye*d+u,ye=Math.sin(et),Ae=Math.cos(et);Q.x=ke*ye,Q.y=-I+he*h,Q.z=ke*Ae,E.push(Q.x,Q.y,Q.z),B.set(ie*ye,he,ie*Ae),S.push(B.x,B.y,B.z),C.push(Ye,Ht.UseOpenGLOrientationForUV?Ee/fe:1-Ee/fe),oe.push(y),y++}A.push(oe)}for(N=0;Nmz(a,e,t);Se.CreateCapsule=Hv;function wP(a){let e=a.pathArray;const t=a.closeArray||!1,i=a.closePath||!1,s=a.invertUV||!1,r=Math.floor(e[0].length/2);let n=a.offset||r;n=n>r?r:Math.floor(n);const o=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,l=a.uvs,h=a.colors,c=[],u=[],d=[],f=[],m=[],_=[],x=[],E=[];let S;const C=[],y=[];let A,I,R;if(e.length<2){const Re=[],St=[];for(I=0;I0&&(de=Q[R].subtract(Q[R-1]).length(),ge=de+x[A],m[A].push(ge),x[A]=ge),R++;i&&(R--,c.push(Q[0].x,Q[0].y,Q[0].z),de=Q[R].subtract(Q[0]).length(),ge=de+x[A],m[A].push(ge),x[A]=ge),C[A]=ne+k,y[A]=N,N+=ne+k}let fe,Ee,De=null,Te=null;for(I=0;I{let m=i[0].length;const _=o;let x=0;const E=_._originalBuilderSideOrientation===q.DOUBLESIDE?2:1;for(let S=1;S<=E;++S)for(let C=0;CRu(a,{pathArray:e,closeArray:t,closePath:i,offset:s,updatable:n,sideOrientation:o,instance:l},r);function Xv(a){const e=[],t=[],i=[],s=[],r=a.radius||.5,n=a.tessellation||64,o=a.arc&&(a.arc<=0||a.arc>1)?1:a.arc||1,l=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE;e.push(0,0,0),s.push(.5,.5);const h=Math.PI*2*o,c=o===1?h/n:h/(n-1);let u=0;for(let m=0;mFP(a,{radius:e,tessellation:t,sideOrientation:r,updatable:s},i);function Zm(a){const e=a.pattern||q.NO_FLIP,t=a.tileWidth||a.tileSize||1,i=a.tileHeight||a.tileSize||1,s=a.alignHorizontal||0,r=a.alignVertical||0,n=a.width||a.size||1,o=Math.floor(n/t);let l=n-o*t;const h=a.height||a.size||1,c=Math.floor(h/i);let u=h-c*i;const d=t*o/2,f=i*c/2;let m=0,_=0,x=0,E=0,S=0,C=0;if(l>0||u>0){switch(x=-d,E=-f,S=d,C=f,s){case q.CENTER:l/=2,x-=l,S+=l;break;case q.LEFT:S+=l,m=-l/2;break;case q.RIGHT:x-=l,m=l/2;break}switch(r){case q.CENTER:u/=2,E-=u,C+=u;break;case q.BOTTOM:C+=u,_=-u/2;break;case q.TOP:E-=u,_=u/2;break}}const y=[],A=[],I=[];I[0]=[0,0,1,0,1,1,0,1],I[1]=[0,0,1,0,1,1,0,1],(e===q.ROTATE_TILE||e===q.ROTATE_ROW)&&(I[1]=[1,1,0,1,0,0,1,0]),(e===q.FLIP_TILE||e===q.FLIP_ROW)&&(I[1]=[1,0,0,0,0,1,1,1]),(e===q.FLIP_N_ROTATE_TILE||e===q.FLIP_N_ROTATE_ROW)&&(I[1]=[0,1,1,1,1,0,0,0]);let R=[];const N=[],k=[];let B=0;for(let ge=0;ge0||u>0){const ge=u>0&&(r===q.CENTER||r===q.TOP),fe=u>0&&(r===q.CENTER||r===q.BOTTOM),Ee=l>0&&(s===q.CENTER||s===q.RIGHT),De=l>0&&(s===q.CENTER||s===q.LEFT);let Te=[],ue,oe,F,ie;if(ge&&Ee&&(y.push(x+m,E+_,0),y.push(-d+m,E+_,0),y.push(-d+m,E+u+_,0),y.push(x+m,E+u+_,0),k.push(B,B+1,B+3,B+1,B+2,B+3),B+=4,ue=1-l/t,oe=1-u/i,F=1,ie=1,Te=[ue,oe,F,oe,F,ie,ue,ie],e===q.ROTATE_ROW&&(Te=[1-ue,1-oe,1-F,1-oe,1-F,1-ie,1-ue,1-ie]),e===q.FLIP_ROW&&(Te=[1-ue,oe,1-F,oe,1-F,ie,1-ue,ie]),e===q.FLIP_N_ROTATE_ROW&&(Te=[ue,1-oe,F,1-oe,F,1-ie,ue,1-ie]),R=R.concat(Te),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ge&&De&&(y.push(d+m,E+_,0),y.push(S+m,E+_,0),y.push(S+m,E+u+_,0),y.push(d+m,E+u+_,0),k.push(B,B+1,B+3,B+1,B+2,B+3),B+=4,ue=0,oe=1-u/i,F=l/t,ie=1,Te=[ue,oe,F,oe,F,ie,ue,ie],(e===q.ROTATE_ROW||e===q.ROTATE_TILE&&o%2===0)&&(Te=[1-ue,1-oe,1-F,1-oe,1-F,1-ie,1-ue,1-ie]),(e===q.FLIP_ROW||e===q.FLIP_TILE&&o%2===0)&&(Te=[1-ue,oe,1-F,oe,1-F,ie,1-ue,ie]),(e===q.FLIP_N_ROTATE_ROW||e===q.FLIP_N_ROTATE_TILE&&o%2===0)&&(Te=[ue,1-oe,F,1-oe,F,1-ie,ue,1-ie]),R=R.concat(Te),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),fe&&Ee&&(y.push(x+m,f+_,0),y.push(-d+m,f+_,0),y.push(-d+m,C+_,0),y.push(x+m,C+_,0),k.push(B,B+1,B+3,B+1,B+2,B+3),B+=4,ue=1-l/t,oe=0,F=1,ie=u/i,Te=[ue,oe,F,oe,F,ie,ue,ie],(e===q.ROTATE_ROW&&c%2===1||e===q.ROTATE_TILE&&c%1===0)&&(Te=[1-ue,1-oe,1-F,1-oe,1-F,1-ie,1-ue,1-ie]),(e===q.FLIP_ROW&&c%2===1||e===q.FLIP_TILE&&c%2===0)&&(Te=[1-ue,oe,1-F,oe,1-F,ie,1-ue,ie]),(e===q.FLIP_N_ROTATE_ROW&&c%2===1||e===q.FLIP_N_ROTATE_TILE&&c%2===0)&&(Te=[ue,1-oe,F,1-oe,F,1-ie,ue,1-ie]),R=R.concat(Te),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),fe&&De&&(y.push(d+m,f+_,0),y.push(S+m,f+_,0),y.push(S+m,C+_,0),y.push(d+m,C+_,0),k.push(B,B+1,B+3,B+1,B+2,B+3),B+=4,ue=0,oe=0,F=l/t,ie=u/i,Te=[ue,oe,F,oe,F,ie,ue,ie],(e===q.ROTATE_ROW&&c%2===1||e===q.ROTATE_TILE&&(c+o)%2===1)&&(Te=[1-ue,1-oe,1-F,1-oe,1-F,1-ie,1-ue,1-ie]),(e===q.FLIP_ROW&&c%2===1||e===q.FLIP_TILE&&(c+o)%2===1)&&(Te=[1-ue,oe,1-F,oe,1-F,ie,1-ue,ie]),(e===q.FLIP_N_ROTATE_ROW&&c%2===1||e===q.FLIP_N_ROTATE_TILE&&(c+o)%2===1)&&(Te=[ue,1-oe,F,1-oe,F,1-ie,ue,1-ie]),R=R.concat(Te),N.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),A.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),ge){const he=[];ue=0,oe=1-u/i,F=1,ie=1,he[0]=[ue,oe,F,oe,F,ie,ue,ie],he[1]=[ue,oe,F,oe,F,ie,ue,ie],(e===q.ROTATE_TILE||e===q.ROTATE_ROW)&&(he[1]=[1-ue,1-oe,1-F,1-oe,1-F,1-ie,1-ue,1-ie]),(e===q.FLIP_TILE||e===q.FLIP_ROW)&&(he[1]=[1-ue,oe,1-F,oe,1-F,ie,1-ue,ie]),(e===q.FLIP_N_ROTATE_TILE||e===q.FLIP_N_ROTATE_ROW)&&(he[1]=[ue,1-oe,F,1-oe,F,1-ie,ue,1-ie]);for(let ke=0;kehe+Q)),Q+=R[F].length,i)for(let he=0;he<4;he++)I.push(i[F].r,i[F].g,i[F].b,i[F].a)}const ne=new T(0,0,_),de=L.RotationY(Math.PI);S=R[0].map(F=>T.TransformNormal(F,de).add(ne)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]),C=N[0].map(F=>T.TransformNormal(F,de)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]),S=S.concat(R[1].map(F=>F.subtract(ne)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),C=C.concat(N[1].map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]));const ge=new T(f,0,0),fe=L.RotationY(-Math.PI/2);S=S.concat(R[2].map(F=>T.TransformNormal(F,fe).add(ge)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),C=C.concat(N[2].map(F=>T.TransformNormal(F,fe)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]));const Ee=L.RotationY(Math.PI/2);S=S.concat(R[3].map(F=>T.TransformNormal(F,Ee).subtract(ge)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),C=C.concat(N[3].map(F=>T.TransformNormal(F,Ee)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]));const De=new T(0,m,0),Te=L.RotationX(Math.PI/2);S=S.concat(R[4].map(F=>T.TransformNormal(F,Te).add(De)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),C=C.concat(N[4].map(F=>T.TransformNormal(F,Te)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[]));const ue=L.RotationX(-Math.PI/2);S=S.concat(R[5].map(F=>T.TransformNormal(F,ue).subtract(De)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),C=C.concat(N[5].map(F=>T.TransformNormal(F,ue)).map(F=>[F.x,F.y,F.z]).reduce((F,ie)=>F.concat(ie),[])),Se._ComputeSides(d,S,A,C,y);const oe=new Se;if(oe.indices=A,oe.positions=S,oe.normals=C,oe.uvs=y,i){const F=d===Se.DOUBLESIDE?I.concat(I):I;oe.colors=F}return oe}Se.CreateTiledBox=gz;function LP(a){const e=[],t=[],i=[],s=[],r=a.radius||2,n=a.tube||.5,o=a.radialSegments||32,l=a.tubularSegments||32,h=a.p||2,c=a.q||3,u=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,d=x=>{const E=Math.cos(x),S=Math.sin(x),C=c/h*x,y=Math.cos(C),A=r*(2+y)*.5*E,I=r*(2+y)*S*.5,R=r*Math.sin(C)*.5;return new T(A,I,R)};let f,m;for(f=0;f<=o;f++){const E=f%o/o*2*h*Math.PI,S=d(E),C=d(E+.01),y=C.subtract(S);let A=C.add(S);const I=T.Cross(y,A);for(A=T.Cross(I,y),I.normalize(),A.normalize(),m=0;mxz(a,{radius:e,tube:t,radialSegments:i,tubularSegments:s,p:r,q:n,sideOrientation:h,updatable:l},o);const fE={effect:null,subMesh:null};class vn extends cf{constructor(e,t,i,s={},r=!0){super(e,t,r),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 L,this._cachedWorldViewProjectionMatrix=new L,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,...s}}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,s)=>(s.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,s)=>(s.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,s)=>(s.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 s=0;sr===e||r.startsWith(i));return s>=0&&this.options.defines.splice(s,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 s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const A=s?i._drawWrapper:this._drawWrapper;if(A.effect&&A._wasPreviouslyReady&&A._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],l=[],h=new gc;let c=this._shaderPath,u=this._options.uniforms,d=this._options.uniformBuffers,f=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),u.indexOf("viewProjection")!==-1&&u.indexOf("viewProjectionR")===-1&&u.push("viewProjectionR"));for(let A=0;A4&&(l.push(P.MatricesIndicesExtraKind),l.push(P.MatricesWeightsExtraKind));const A=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h.addCPUSkinningFallback(0,e),A.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),u.indexOf("boneTextureWidth")===-1&&u.push("boneTextureWidth"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(A.bones.length+1)),u.indexOf("mBones")===-1&&u.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let m=0;const _=e?e.morphTargetManager:null;if(_){const A=_.supportsUVs&&o.indexOf("#define UV1")!==-1,I=_.supportsTangents&&o.indexOf("#define TANGENT")!==-1,R=_.supportsNormals&&o.indexOf("#define NORMAL")!==-1;m=_.numMaxInfluencers||_.numInfluencers,A&&o.push("#define MORPHTARGETS_UV"),I&&o.push("#define MORPHTARGETS_TANGENT"),R&&o.push("#define MORPHTARGETS_NORMAL"),m>0&&o.push("#define MORPHTARGETS"),_.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),u.indexOf("morphTargetTextureIndices")===-1&&u.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+m);for(let N=0;N0&&(u=u.slice(),u.push("morphTargetInfluences"),u.push("morphTargetCount"),u.push("morphTargetTextureInfo"),u.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const A=e.bakedVertexAnimationManager;A&&A.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),u.indexOf("bakedVertexAnimationSettings")===-1&&u.push("bakedVertexAnimationSettings"),u.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&u.push("bakedVertexAnimationTextureSizeInverted"),u.indexOf("bakedVertexAnimationTime")===-1&&u.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture")),_v(l,e,o)}for(const A in this._textures)if(!this._textures[A].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(Va(u),vh(this,r,o)),r.fogEnabled&&(e!=null&&e.applyFog)&&r.fogMode!==Ue.FOGMODE_NONE&&(o.push("#define FOG"),u.indexOf("view")===-1&&u.push("view"),u.indexOf("vFogInfos")===-1&&u.push("vFogInfos"),u.indexOf("vFogColor")===-1&&u.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),u.indexOf("logarithmicDepthConstant")===-1&&u.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(u=u.slice(),d=d.slice(),f=f.slice(),c=this.customShaderNameResolve(this.name,u,d,f,o,l));const x=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,E=(x==null?void 0:x.effect)??null,S=(x==null?void 0:x.defines)??null,C=o.join(` +`);let y=E;return S!==C&&(y=n.createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:f,defines:C,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(y,C,this._materialContext):x&&x.setEffect(y,C),this._onEffectCreatedObservable&&(fE.effect=y,fE.subMesh=i??(e==null?void 0:e.subMeshes[0])??null,this._onEffectCreatedObservable.notifyObservers(fE))),x._wasPreviouslyUsingInstances=!!t,y!=null&&y.isReady()?(E!==y&&r.resetCachedMaterial(),x._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(this._options.uniforms.indexOf("world")!==-1&&s.setMatrix("world",e),this._options.uniforms.indexOf("worldView")!==-1&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),this._options.uniforms.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),this._options.uniforms.indexOf("view")!==-1&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){var s;this.bind(e,t,(s=i._drawWrapperOverride)==null?void 0:s.effect,i)}bind(e,t,i,s){var u;const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const l=this._options.uniformBuffers;let h=!1;if(n&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;d0&&Al(t,n);const f=t.bakedVertexAnimationManager;if(f&&f.isEnabled){const m=r?s._drawWrapper:this._drawWrapper;(u=t.bakedVertexAnimationManager)==null||u.bind(n,!!m._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}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 s=0;snew vn(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 s=this._options[i];Array.isArray(s)&&(this._options[i]=s.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 s;for(s in this._textures)this._textures[s].dispose();for(s in this._textureArrays){const r=this._textureArrays[s];for(let n=0;nnew vn(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);let r;e.stencil&&s.stencil.parse(e.stencil,t,i);for(r in e.textures)s.setTexture(r,X.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let l=0;l(h%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>re.FromArray(o));s.setColor3Array(r,n)}for(r in e.colors4)s.setColor4(r,Oe.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const n=e.colors4Arrays[r].reduce((o,l,h)=>(h%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>Oe.FromArray(o));s.setColor4Array(r,n)}for(r in e.vectors2)s.setVector2(r,ce.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,T.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,tt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,ae.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,L.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise((r,n)=>{const o=new hs;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=this.Parse(l,i||We.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((s,r)=>{const n=new hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),h=this.Parse(l,t||We.LastCreatedScene,i);h.snippetId=e,s(h)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}vn.SnippetUrl="https://snippet.babylonjs.com";vn.CreateFromSnippetAsync=vn.ParseFromSnippetAsync;H("BABYLON.ShaderMaterial",vn);const Tz="colorPixelShader",Ez=`#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 +}`;j.ShadersStore[Tz]=Ez;const Sz="colorVertexShader",vz=`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 +}`;j.ShadersStore[Sz]=vz;q._LinesMeshParser=(a,e)=>xh.Parse(a,e);class xh extends q{_isShaderMaterial(e){return e.getClassName()==="ShaderMaterial"}constructor(e,t=null,i=null,s=null,r,n,o,l){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new re(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const h=[],c={attributes:[P.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:h,useClipPlane:null};o===!1?c.needAlphaBlending=!1:c.defines.push("#define VERTEXALPHA"),n?(c.defines.push("#define VERTEXCOLOR"),c.attributes.push(P.ColorKind)):(c.uniforms.push("color"),this._color4=new Oe),l?this.material=l:(this.material=new vn("colorShader",this.getScene(),"color",c,!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=pe.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:s,g:r,b:n}=this.color;this._color4.set(s,r,n,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 s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(pe.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(pe.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 xh(e,this.getScene(),t,this,i)}createInstance(e){const t=new BP(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 xh(e.name,t);return i.color=re.FromArray(e.color),i.alpha=e.alpha,i}}class BP extends vv{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function UP(a){const e=[],t=[],i=a.lines,s=a.colors,r=[];let n=0;for(let l=0;l0&&(e.push(n-1),e.push(n)),n++}}const o=new Se;return o.indices=e,o.positions=t,s&&(o.colors=r),o}function VP(a){const e=a.dashSize||3,t=a.gapSize||1,i=a.dashNb||200,s=a.points,r=[],n=[],o=T.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,m=0;for(m=0;m{const u=T.Zero(),d=c.length/6;let f=0,m=0,_=0,x=0,E=0,S=0,C=0,y=0;for(C=0;CYv(a,{points:e,updatable:i,instance:s},t);q.CreateDashedLines=(a,e,t,i,s,r=null,n,o)=>bz(a,{points:e,dashSize:t,gapSize:i,dashNb:s,updatable:n,instance:o},r);class yz extends ce{constructor(e,t){super(e.x,e.y),this.index=t}}class pE{constructor(){this.elements=[]}add(e){const t=[];return e.forEach(i=>{const s=new yz(i,this.elements.length);t.push(s),this.elements.push(s)}),t}computeBounds(){const e=new ce(this.elements[0].x,this.elements[0].y),t=new ce(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}}}class Az{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){this._points=new pE,this._outlinepoints=new pE,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||We.LastCreatedScene;let r;t instanceof Vg?r=t.getPoints():r=t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),typeof this.bjsEarcut>"u"&&U.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new pE;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 s=new q(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(P.PositionKind,r.positions,e),s.setVerticesData(P.NormalKind,r.normals,e),s.setVerticesData(P.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Se,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach(c=>{s.push(0,1,0),r.push(c.x,0,c.y),n.push((c.x-o.min.x)/o.width,(c.y-o.min.y)/o.height)});const l=[],h=this.bjsEarcut(this._epoints,this._eholes,2);for(let c=0;c0){const c=r.length/3;this._points.elements.forEach(d=>{s.push(0,-1,0),r.push(d.x,-e,d.y),n.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height)});const u=l.length;for(let d=0;d{this._addSide(r,s,n,l,o,d,e,!0,t)})}return i.indices=l,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,l,h){let c=e.length/3,u=0;for(let d=0;dh?Rh?NGP(a,{shape:e,holes:i,updatable:s,sideOrientation:r},t,n);q.ExtrudePolygon=(a,e,t,i,s,r,n,o=earcut)=>Rz(a,{shape:e,holes:s,depth:t,updatable:r,sideOrientation:n},i,o);function zP(a,e,t=null){const i=e.path,s=e.shape,r=e.scale||1,n=e.rotation||0,o=e.cap===0?0:e.cap||q.NO_CAP,l=e.updatable,h=q._GetDefaultSideOrientation(e.sideOrientation),c=e.instance||null,u=e.invertUV||!1,d=e.closeShape||!1,f=e.closePath||!1;return WP(a,s,i,r,n,null,null,f,d,o,!1,t,!!l,h,c,u,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame)}function Iz(a,e,t=null){const i=e.path,s=e.shape,r=e.scaleFunction||(()=>1),n=e.rotationFunction||(()=>0),o=e.closePath||e.ribbonCloseArray||!1,l=e.closeShape||e.ribbonClosePath||!1,h=e.cap===0?0:e.cap||q.NO_CAP,c=e.updatable,u=e.firstNormal||null,d=e.adjustFrame||!1,f=q._GetDefaultSideOrientation(e.sideOrientation),m=e.instance,_=e.invertUV||!1;return WP(a,s,i,null,null,r,n,o,l,h,!0,t,!!c,f,m||null,_,e.frontUVs||null,e.backUVs||null,u,d)}function WP(a,e,t,i,s,r,n,o,l,h,c,u,d,f,m,_,x,E,S,C){const y=(k,B,Q,ne,de,ge,fe,Ee,De,Te,ue)=>{const oe=Q.getTangents(),F=Q.getNormals(),ie=Q.getBinormals(),he=Q.getDistances();if(ue){for(let Re=0;Re0){let St=oe[Re-1];T.Dot(St,oe[Re])<0&&oe[Re].scaleInPlace(-1),St=F[Re-1],T.Dot(St,F[Re])<0&&F[Re].scaleInPlace(-1),St=ie[Re-1],T.Dot(St,ie[Re])<0&&ie[Re].scaleInPlace(-1)}}let ke=0;const Ye=()=>de!==null?de:1,ye=Te&&Ee?Ee:()=>ge!==null?ge:0,Ae=Te&&fe?fe:Ye;let rt=De===q.NO_CAP||De===q.CAP_END?0:2;const Ze=W.Matrix[0];for(let Re=0;Re{const St=Array(),Lt=T.Zero();let Ci;for(Ci=0;Ci3?0:h,I=y(e,t,A,R,i,s,r,n,h,c,C);const N=Ru(a,{pathArray:I,closeArray:o,closePath:l,updatable:d,sideOrientation:f,invertUV:_,frontUVs:x||void 0,backUVs:E||void 0},u);return N._creationDataStorage.pathArray=I,N._creationDataStorage.path3D=A,N._creationDataStorage.cap=h,N}q.ExtrudeShape=(a,e,t,i,s,r,n=null,o,l,h)=>{const c={shape:e,path:t,scale:i,rotation:s,cap:r===0?0:r||q.NO_CAP,sideOrientation:l,instance:h,updatable:o};return zP(a,c,n)};q.ExtrudeShapeCustom=(a,e,t,i,s,r,n,o,l,h,c,u)=>{const d={shape:e,path:t,scaleFunction:i,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:n,cap:o===0?0:o||q.NO_CAP,sideOrientation:c,instance:u,updatable:h};return Iz(a,d,l)};function Pz(a,e,t=null){const i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,s=e.closed===void 0?!0:e.closed,r=e.shape,n=e.radius||1,o=e.tessellation||64,l=e.clip||0,h=e.updatable,c=q._GetDefaultSideOrientation(e.sideOrientation),u=e.cap||q.NO_CAP,d=Math.PI*2,f=[],m=e.invertUV||!1;let _=0,x=0;const E=d/o*i;let S,C;for(_=0;_<=o-l;_++){for(C=[],(u==q.CAP_START||u==q.CAP_ALL)&&(C.push(new T(0,r[0].y,0)),C.push(new T(Math.cos(_*E)*r[0].x*n,r[0].y,Math.sin(_*E)*r[0].x*n))),x=0;xPz(a,{shape:e,radius:t,tessellation:i,sideOrientation:n,updatable:r},s);function Mz(a,e,t=null){const i=e.path;let s=e.instance,r=1;e.radius!==void 0?r=e.radius:s&&(r=s._creationDataStorage.radius);const n=e.tessellation||64,o=e.radiusFunction||null;let l=e.cap||q.NO_CAP;const h=e.invertUV||!1,c=e.updatable,u=q._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;const d=(E,S,C,y,A,I,R,N)=>{const k=S.getTangents(),B=S.getNormals(),Q=S.getDistances(),de=Math.PI*2/A*N,fe=I||(()=>y);let Ee,De,Te,ue;const oe=W.Matrix[0];let F=R===q.NO_CAP||R===q.CAP_END?0:2;for(let he=0;he{const Ye=Array();for(let et=0;et3?0:l,m=d(i,f,_,r,n,o,l,e.arc);const x=Ru(a,{pathArray:m,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return x._creationDataStorage.pathArray=m,x._creationDataStorage.path3D=f,x._creationDataStorage.tessellation=n,x._creationDataStorage.cap=l,x._creationDataStorage.arc=e.arc,x._creationDataStorage.radius=r,x}q.CreateTube=(a,e,t,i,s,r,n,o,l,h)=>Mz(a,{path:e,radius:t,tessellation:i,radiusFunction:s,arc:1,cap:r,updatable:o,sideOrientation:l,instance:h},n);function HP(a){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=a.type&&(a.type<0||a.type>=e.length)?0:a.type||0,i=a.size,s=a.sizeX||i||1,r=a.sizeY||i||1,n=a.sizeZ||i||1,o=a.custom||e[t],l=o.face.length,h=a.faceUV||new Array(l),c=a.faceColors,u=a.flat===void 0?!0:a.flat,d=a.sideOrientation===0?0:a.sideOrientation||Se.DEFAULTSIDE,f=[],m=[],_=[],x=[],E=[];let S=0,C=0;const y=[];let A=0,I=0,R,N,k,B,Q,ne;if(u)for(I=0;IOz(a,e,t);const Dz=new T(1,0,0),Nz=new T(-1,0,0),wz=new T(0,1,0),Fz=new T(0,-1,0),Lz=new T(0,0,1),Bz=new T(0,0,-1);class mg{constructor(e=T.Zero(),t=T.Up(),i=ce.Zero(),s=0,r=0,n=null,o=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,s;return new mg(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(),(s=this.matrixWeightsOverride)==null?void 0:s.slice())}}function Uz(a,e,t){var De,Te,ue,oe;const i=!!e.skeleton,s=t.localMode||i,r=e.overrideMaterialSideOrientation!==null&&e.overrideMaterialSideOrientation!==void 0,n=e.getIndices(),o=i?e.getPositionData(!0,!0):e.getVerticesData(P.PositionKind),l=i?e.getNormalsData(!0,!0):e.getVerticesData(P.NormalKind),h=s?i?e.getVerticesData(P.PositionKind):o:null,c=s?i?e.getVerticesData(P.NormalKind):l:null,u=e.getVerticesData(P.UVKind),d=i?e.getVerticesData(P.MatricesIndicesKind):null,f=i?e.getVerticesData(P.MatricesWeightsKind):null,m=i?e.getVerticesData(P.MatricesIndicesExtraKind):null,_=i?e.getVerticesData(P.MatricesWeightsExtraKind):null,x=t.position||T.Zero();let E=t.normal||T.Up();const S=t.size||T.One(),C=t.angle||0;if(!E){const F=new T(0,0,1),ie=e.getScene().activeCamera,he=T.TransformCoordinates(F,ie.getWorldMatrix());E=ie.globalPosition.subtract(he)}const y=-Math.atan2(E.z,E.x)-Math.PI/2,A=Math.sqrt(E.x*E.x+E.z*E.z),I=Math.atan2(E.y,A),R=new Se;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=i?[]:null,R.matricesWeights=i?[]:null,R.matricesIndicesExtra=m?[]:null,R.matricesWeightsExtra=_?[]:null;let N=0;const k=(F,ie)=>{const he=new mg;if(!n||!o||!l)return he;const ke=n[F];if(he.vertexIdx=ke*3,he.vertexIdxForBones=ke*4,he.position=new T(o[ke*3],o[ke*3+1],o[ke*3+2]),T.TransformCoordinatesToRef(he.position,ie,he.position),he.normal=new T(l[ke*3],l[ke*3+1],l[ke*3+2]),T.TransformNormalToRef(he.normal,ie,he.normal),t.captureUVS&&u){const Ye=u[ke*2+1];he.uv=new ce(u[ke*2],Ht.UseOpenGLOrientationForUV?1-Ye:Ye)}return he},B=[0,0,0,0],Q=(F,ie)=>{if(F.length===0)return F;const he=.5*Math.abs(T.Dot(S,ie)),ke=(ye,Ae,rt,Ze)=>{for(let Et=0;Et{const rt=T.GetClipFactor(ye.position,Ae.position,ie,he);let Ze=B,Et=B;if(d&&f){const Wr=ye.matrixIndicesOverride?0:ye.vertexIdxForBones,jn=ye.matrixIndicesOverride??d,Ga=ye.matrixWeightsOverride??f,xi=Ae.matrixIndicesOverride?0:Ae.vertexIdxForBones,_o=Ae.matrixIndicesOverride??d,mo=Ae.matrixWeightsOverride??f;Ze=[0,0,0,0],Et=[0,0,0,0];let In=0;for(let Nr=0;Nr<4;++Nr)if(Ga[Wr+Nr]>0){const va=ke(_o,jn[Wr+Nr],xi,4);Ze[In]=jn[Wr+Nr],Et[In]=Ne.Lerp(Ga[Wr+Nr],va>=0?mo[va]:0,rt),In++}for(let Nr=0;Nr<4&&In<4;++Nr){const va=_o[xi+Nr];ke(jn,va,Wr,4)===-1&&(Ze[In]=va,Et[In]=Ne.Lerp(0,mo[xi+Nr],rt),In++)}const un=Et[0]+Et[1]+Et[2]+Et[3];Et[0]/=un,Et[1]/=un,Et[2]/=un,Et[3]/=un}const Re=ye.localPositionOverride?ye.localPositionOverride[0]:(h==null?void 0:h[ye.vertexIdx])??0,St=ye.localPositionOverride?ye.localPositionOverride[1]:(h==null?void 0:h[ye.vertexIdx+1])??0,Lt=ye.localPositionOverride?ye.localPositionOverride[2]:(h==null?void 0:h[ye.vertexIdx+2])??0,Ci=Ae.localPositionOverride?Ae.localPositionOverride[0]:(h==null?void 0:h[Ae.vertexIdx])??0,ki=Ae.localPositionOverride?Ae.localPositionOverride[1]:(h==null?void 0:h[Ae.vertexIdx+1])??0,Ts=Ae.localPositionOverride?Ae.localPositionOverride[2]:(h==null?void 0:h[Ae.vertexIdx+2])??0,ar=ye.localNormalOverride?ye.localNormalOverride[0]:(c==null?void 0:c[ye.vertexIdx])??0,fo=ye.localNormalOverride?ye.localNormalOverride[1]:(c==null?void 0:c[ye.vertexIdx+1])??0,Rn=ye.localNormalOverride?ye.localNormalOverride[2]:(c==null?void 0:c[ye.vertexIdx+2])??0,br=Ae.localNormalOverride?Ae.localNormalOverride[0]:(c==null?void 0:c[Ae.vertexIdx])??0,qr=Ae.localNormalOverride?Ae.localNormalOverride[1]:(c==null?void 0:c[Ae.vertexIdx+1])??0,po=Ae.localNormalOverride?Ae.localNormalOverride[2]:(c==null?void 0:c[Ae.vertexIdx+2])??0,Rl=ar+(br-ar)*rt,Sa=fo+(qr-fo)*rt,Il=Rn+(po-Rn)*rt,zr=Math.sqrt(Rl*Rl+Sa*Sa+Il*Il);return new mg(T.Lerp(ye.position,Ae.position,rt),T.Lerp(ye.normal,Ae.normal,rt).normalize(),ce.Lerp(ye.uv,Ae.uv,rt),-1,-1,h?[Re+(Ci-Re)*rt,St+(ki-St)*rt,Lt+(Ts-Lt)*rt]:null,c?[Rl/zr,Sa/zr,Il/zr]:null,Ze,Et)};let et=null;F.length>3&&(et=[]);for(let ye=0;ye0,Ts=Lt>0,ar=Ci>0;switch(Ae=(ki?1:0)+(Ts?1:0)+(ar?1:0),Ae){case 0:F.length>3?(et.push(F[ye]),et.push(F[ye+1]),et.push(F[ye+2])):et=F;break;case 1:if(et=et??new Array,ki&&(rt=F[ye+1],Ze=F[ye+2],Et=Ye(F[ye],rt),Re=Ye(F[ye],Ze)),Ts){rt=F[ye],Ze=F[ye+2],Et=Ye(F[ye+1],rt),Re=Ye(F[ye+1],Ze),et.push(Et),et.push(Ze.clone()),et.push(rt.clone()),et.push(Ze.clone()),et.push(Et.clone()),et.push(Re);break}ar&&(rt=F[ye],Ze=F[ye+1],Et=Ye(F[ye+2],rt),Re=Ye(F[ye+2],Ze)),rt&&Ze&&Et&&Re&&(et.push(rt.clone()),et.push(Ze.clone()),et.push(Et),et.push(Re),et.push(Et.clone()),et.push(Ze.clone()));break;case 2:et=et??new Array,ki||(rt=F[ye].clone(),Ze=Ye(rt,F[ye+1]),Et=Ye(rt,F[ye+2]),et.push(rt),et.push(Ze),et.push(Et)),Ts||(rt=F[ye+1].clone(),Ze=Ye(rt,F[ye+2]),Et=Ye(rt,F[ye]),et.push(rt),et.push(Ze),et.push(Et)),ar||(rt=F[ye+2].clone(),Ze=Ye(rt,F[ye]),Et=Ye(rt,F[ye+1]),et.push(rt),et.push(Ze),et.push(Et));break}}return et},ne=e instanceof q?e:null,de=ne==null?void 0:ne._thinInstanceDataStorage.matrixData,ge=(ne==null?void 0:ne.thinInstanceCount)||1,fe=W.Matrix[0];fe.copyFrom(L.IdentityReadOnly);for(let F=0;FUz(a,e,{position:t,normal:i,size:s,angle:r});q._GoldbergMeshParser=(a,e)=>$v.Parse(a,e);class $v extends q{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&&(U.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(U.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(U.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&&(u=1),h.push(u,d);for(let f=0;f<6;f++)u=n.x+o*Math.cos(l+f*Math.PI/3),d=n.y+o*Math.sin(l+f*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,d);for(let f=s;fOe.FromArray(r)),i.faceCenters=i.faceCenters.map(r=>T.FromArray(r)),i.faceZaxis=i.faceZaxis.map(r=>T.FromArray(r)),i.faceXaxis=i.faceXaxis.map(r=>T.FromArray(r)),i.faceYaxis=i.faceYaxis.map(r=>T.FromArray(r));const s=new $v(e.name,t);return s.goldbergData=i,s}}class Vz{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new Vg(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,s){this._currentPath.addQuadraticCurveTo(e,t,i,s,this._resolution)}bezierCurveTo(e,t,i,s,r,n){this._currentPath.addBezierCurveTo(e,t,i,s,r,n,this._resolution)}extractHoles(){for(const e of this._tempPaths)e.area()>0?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 kz(a,e,t,i,s,r){const n=r.glyphs[a]||r.glyphs["?"];if(!n)return null;const o=new Vz(s);if(n.o){const l=n.o.split(" ");for(let h=0,c=l.length;h{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},n=(o,l)=>{s&&o&&s(o.status+" "+o.statusText,l)};this._loadFile(a,r,void 0,void 0,!0,n)};He.prototype._cascadeLoadFiles=function(a,e,t,i=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(t[r],r,s,e,i)};He.prototype._cascadeLoadImgs=function(a,e,t,i,s=null,r){const n=[];n._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,n,a,e,t,s,r)};He.prototype._partialLoadImg=function(a,e,t,i,s,r,n=null,o){const l=La();r_(a,u=>{t[e]=u,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&r&&r(s,t)},(u,d)=>{i&&i.removePendingData(l),n&&n(u,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};He.prototype.createCubeTextureBase=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d=null,f=null,m=!1){const _=u||new $t(this,xt.Cube);_.isCube=!0,_.url=a,_.generateMipMaps=!i,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=!!m&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),_!==u&&(_.label=a.substring(0,60)),this._doNotHandleContextLost||(_._extension=o,_._files=t);const x=a;this._transformTextureUrl&&!u&&(a=this._transformTextureUrl(a));const E=a.split("?")[0],S=E.lastIndexOf("."),C=o||(S>-1?E.substring(S).toLowerCase():"");let y=null;for(const I of He._TextureLoaders)if(I.canLoad(C)){y=I;break}const A=(I,R)=>{a===x?r&&I&&r(I.status+" "+I.statusText,R):(U.Warn(`Failed to load ${a}, falling back to the ${x}`),this.createCubeTextureBase(x,e,t,!!i,s,r,n,o,l,h,c,_,d,f,m))};if(y){const I=R=>{d&&d(_,R),y.loadCubeData(R,_,l,s,r)};t&&t.length===6?y.supportCascades?this._cascadeLoadFiles(e,R=>I(R.map(N=>new Uint8Array(N))),t,r):r?r("Textures type does not support cascades."):U.Warn("Texture loader does not support cascades."):this._loadFile(a,R=>I(new Uint8Array(R)),void 0,void 0,!0,A)}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,_,(I,R)=>{f&&f(I,R)},t,r)}return this._internalTexturesCache.push(_),_};class zz{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Ft.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Ft.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}He.prototype.getGPUFrameTimeCounter=function(){return null};He.prototype.captureGPUFrameTime=function(a){};He.prototype.createQuery=function(){return null};He.prototype.deleteQuery=function(a){return this};He.prototype.isQueryResultAvailable=function(a){return!1};He.prototype.getQueryResult=function(a){return 0};He.prototype.beginOcclusionQuery=function(a,e){return!1};He.prototype.endOcclusionQuery=function(a){return this};Object.defineProperty(Ft.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(a){this._occlusionDataStorage.isOcclusionQueryInProgress=a},enumerable:!1,configurable:!0});Object.defineProperty(Ft.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new zz),this.__occlusionDataStorage},enumerable:!1,configurable:!0});Object.defineProperty(Ft.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(a){this._occlusionDataStorage.isOccluded=a},enumerable:!0,configurable:!0});Object.defineProperty(Ft.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(a){this._occlusionDataStorage.occlusionQueryAlgorithmType=a},enumerable:!0,configurable:!0});Object.defineProperty(Ft.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(a){this._occlusionDataStorage.occlusionType=a},enumerable:!0,configurable:!0});Object.defineProperty(Ft.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(a){this._occlusionDataStorage.occlusionRetryCount=a},enumerable:!0,configurable:!0});Object.defineProperty(Ft.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(a){this._occlusionDataStorage.forceRenderingWhenOccluded=a},enumerable:!0,configurable:!0});Ft.prototype._checkOcclusionQuery=function(){const a=this._occlusionDataStorage;if(a.occlusionType===Ft.OCCLUSION_TYPE_NONE)return a.isOccluded=!1,!1;const e=this.getEngine();if(!e.getCaps().supportOcclusionQuery||!e.isQueryResultAvailable)return a.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery!==null&&this._occlusionQuery!==void 0)if(e.isQueryResultAvailable(this._occlusionQuery)){const s=e.getQueryResult(this._occlusionQuery);a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=!(s>0)}else if(a.occlusionInternalRetryCounter++,a.occlusionRetryCount!==-1&&a.occlusionInternalRetryCounter>a.occlusionRetryCount)a.isOcclusionQueryInProgress=!1,a.occlusionInternalRetryCounter=0,a.isOccluded=a.occlusionType===Ft.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;else return a.occlusionType===Ft.OCCLUSION_TYPE_OPTIMISTIC?!1:a.isOccluded;const t=this.getScene();if(t.getBoundingBoxRenderer){const i=t.getBoundingBoxRenderer();this._occlusionQuery===null&&(this._occlusionQuery=e.createQuery()),this._occlusionQuery&&e.beginOcclusionQuery(a.occlusionQueryAlgorithmType,this._occlusionQuery)&&(i.renderOcclusionBoundingBox(this),e.endOcclusionQuery(a.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return a.isOccluded};He.prototype.setAlphaEquation=function(a){if(this._alphaEquation!==a){switch(a){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=a}};He.prototype._debugPushGroup=function(a,e){};He.prototype._debugPopGroup=function(a){};He.prototype._debugInsertMarker=function(a,e){};He.prototype._debugFlushPendingCommands=function(){};class Wz{constructor(){this._timeElapsedQueryEnded=!1}}ee.prototype.createQuery=function(){const a=this._gl.createQuery();if(!a)throw new Error("Unable to create Occlusion Query");return a};ee.prototype.deleteQuery=function(a){return this._gl.deleteQuery(a),this};ee.prototype.isQueryResultAvailable=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT_AVAILABLE)};ee.prototype.getQueryResult=function(a){return this._gl.getQueryParameter(a,this._gl.QUERY_RESULT)};ee.prototype.beginOcclusionQuery=function(a,e){const t=this._getGlAlgorithmType(a);return this._gl.beginQuery(t,e),!0};ee.prototype.endOcclusionQuery=function(a){const e=this._getGlAlgorithmType(a);return this._gl.endQuery(e),this};ee.prototype._createTimeQuery=function(){const a=this.getCaps().timerQuery;return a.createQueryEXT?a.createQueryEXT():this.createQuery()};ee.prototype._deleteTimeQuery=function(a){const e=this.getCaps().timerQuery;if(e.deleteQueryEXT){e.deleteQueryEXT(a);return}this.deleteQuery(a)};ee.prototype._getTimeQueryResult=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_EXT):this.getQueryResult(a)};ee.prototype._getTimeQueryAvailability=function(a){const e=this.getCaps().timerQuery;return e.getQueryObjectEXT?e.getQueryObjectEXT(a,e.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(a)};ee.prototype.startTimeQuery=function(){const a=this.getCaps(),e=a.timerQuery;if(!e)return null;const t=new Wz;if(this._gl.getParameter(e.GPU_DISJOINT_EXT),a.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};ee.prototype.endTimeQuery=function(a){const e=this.getCaps(),t=e.timerQuery;if(!t||!a)return-1;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery)return-1;a._endTimeQuery||(a._endTimeQuery=this._createTimeQuery(),a._endTimeQuery&&t.queryCounterEXT(a._endTimeQuery,t.TIMESTAMP_EXT))}else if(!a._timeElapsedQueryEnded){if(!a._timeElapsedQuery)return-1;t.endQueryEXT?t.endQueryEXT(t.TIME_ELAPSED_EXT):(this._gl.endQuery(t.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),a._timeElapsedQueryEnded=!0}const i=this._gl.getParameter(t.GPU_DISJOINT_EXT);let s=!1;if(a._endTimeQuery?s=this._getTimeQueryAvailability(a._endTimeQuery):a._timeElapsedQuery&&(s=this._getTimeQueryAvailability(a._timeElapsedQuery)),s&&!i){let r=0;if(e.canUseTimestampForTimerQuery){if(!a._startTimeQuery||!a._endTimeQuery)return-1;const n=this._getTimeQueryResult(a._startTimeQuery);r=this._getTimeQueryResult(a._endTimeQuery)-n,this._deleteTimeQuery(a._startTimeQuery),this._deleteTimeQuery(a._endTimeQuery),a._startTimeQuery=null,a._endTimeQuery=null}else{if(!a._timeElapsedQuery)return-1;r=this._getTimeQueryResult(a._timeElapsedQuery),this._deleteTimeQuery(a._timeElapsedQuery),a._timeElapsedQuery=null,a._timeElapsedQueryEnded=!1}return r}return-1};ee.prototype._captureGPUFrameTime=!1;ee.prototype._gpuFrameTime=new Xn;ee.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime};ee.prototype.captureGPUFrameTime=function(a){a!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=a,a?(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))};ee.prototype._getGlAlgorithmType=function(a){return a===Ft.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};ee.prototype.createTransformFeedback=function(){const a=this._gl.createTransformFeedback();if(!a)throw new Error("Unable to create Transform Feedback");return a};ee.prototype.deleteTransformFeedback=function(a){this._gl.deleteTransformFeedback(a)};ee.prototype.bindTransformFeedback=function(a){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,a)};ee.prototype.beginTransformFeedback=function(a=!0){this._gl.beginTransformFeedback(a?this._gl.POINTS:this._gl.TRIANGLES)};ee.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()};ee.prototype.setTranformFeedbackVaryings=function(a,e){this._gl.transformFeedbackVaryings(a,e,this._gl.INTERLEAVED_ATTRIBS)};ee.prototype.bindTransformFeedbackBuffer=function(a){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,a?a.underlyingResource:null)};nt.prototype.createExternalTexture=function(a){return null};nt.prototype.setExternalTexture=function(a,e){throw new Error("setExternalTexture: This engine does not support external textures!")};nt.prototype.updateVideoTexture=function(a,e,t){if(!a||a._isDisabled)return;const i=this._getInternalFormat(a.format),s=this._getRGBABufferInternalSizedFormat(0,a.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,a,!0);this._unpackFlipY(!t);try{if(this._videoTextureSupported===void 0&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,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,s,i,this._gl.UNSIGNED_BYTE,e);else{if(!a._workingCanvas){a._workingCanvas=this.createCanvas(a.width,a.height);const n=a._workingCanvas.getContext("2d");if(!n)throw new Error("Unable to get 2d context");a._workingContext=n,a._workingCanvas.width=a.width,a._workingCanvas.height=a.height}a._workingContext.clearRect(0,0,a.width,a.height),a._workingContext.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,a.width,a.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,i,this._gl.UNSIGNED_BYTE,a._workingCanvas)}a.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),a.isReady=!0}catch{a._isDisabled=!0}};nt.prototype.restoreSingleAttachment=function(){const a=this._gl;this.bindAttachments([a.BACK])};nt.prototype.restoreSingleAttachmentForRenderTarget=function(){const a=this._gl;this.bindAttachments([a.COLOR_ATTACHMENT0])};nt.prototype.buildTextureLayout=function(a){const e=this._gl,t=[];for(let i=0;i1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],i.readBuffer(s[n]),i.drawBuffers(s),i.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i.COLOR_BUFFER_BIT,i.NEAREST)}for(let n=0;n1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"];i.drawBuffers(s)}for(let n=0;n1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),I.label=(e==null?void 0:e.label)??"MultiRenderTargetWrapper";const R=this._gl,N=R.createFramebuffer();this._bindUnboundFramebuffer(N);const k=a.width||a,B=a.height||a,Q=[],ne=[],de=this.webGLVersion>1&&n&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===18),ge=this._setupFramebufferDepthAttachments(!de&&r,!n&&s,k,B);I._framebuffer=N,I._depthStencilBuffer=ge,I._generateDepthBuffer=!n&&s,I._generateStencilBuffer=!de&&r,I._attachments=ne;for(let fe=0;fe1||this.isWebGPU);const he=this.webGLVersion>1,ke=R[he?"COLOR_ATTACHMENT"+fe:"COLOR_ATTACHMENT"+fe+"_WEBGL"];if(ne.push(ke),oe===-1)continue;const Ye=new $t(this,xt.MultiRenderTarget);Q[fe]=Ye,R.activeTexture(R["TEXTURE"+fe]),R.bindTexture(oe,Ye._hardwareTexture.underlyingResource),R.texParameteri(oe,R.TEXTURE_MAG_FILTER,ie.mag),R.texParameteri(oe,R.TEXTURE_MIN_FILTER,ie.min),R.texParameteri(oe,R.TEXTURE_WRAP_S,R.CLAMP_TO_EDGE),R.texParameteri(oe,R.TEXTURE_WRAP_T,R.CLAMP_TO_EDGE);const et=this._getRGBABufferInternalSizedFormat(De,ue,Te),ye=this._getInternalFormat(ue),Ae=this._getWebGLTextureType(De);if(he&&(oe===35866||oe===32879))oe===35866?Ye.is2DArray=!0:Ye.is3D=!0,Ye.baseDepth=Ye.depth=F,R.texImage3D(oe,0,et,k,B,F,0,ye,Ae,null);else if(oe===34067){for(let rt=0;rt<6;rt++)R.texImage2D(R.TEXTURE_CUBE_MAP_POSITIVE_X+rt,0,et,k,B,0,ye,Ae,null);Ye.isCube=!0}else R.texImage2D(R.TEXTURE_2D,0,et,k,B,0,ye,Ae,null);i&&R.generateMipmap(oe),this._bindTextureDirectly(oe,null),Ye.baseWidth=k,Ye.baseHeight=B,Ye.width=k,Ye.height=B,Ye.isReady=!0,Ye.samples=1,Ye.generateMipMaps=i,Ye.samplingMode=Ee,Ye.type=De,Ye._useSRGBBuffer=Te,Ye.format=ue,this._internalTexturesCache.push(Ye)}if(n&&this._caps.depthTextureExtension){const fe=new $t(this,xt.Depth);let Ee=5,De=R.DEPTH_COMPONENT16,Te=R.DEPTH_COMPONENT,ue=R.UNSIGNED_SHORT,oe=R.DEPTH_ATTACHMENT;this.webGLVersion<2?De=R.DEPTH_COMPONENT:o===14?(Ee=1,ue=R.FLOAT,De=R.DEPTH_COMPONENT32F):o===18?(Ee=0,ue=R.FLOAT_32_UNSIGNED_INT_24_8_REV,De=R.DEPTH32F_STENCIL8,Te=R.DEPTH_STENCIL,oe=R.DEPTH_STENCIL_ATTACHMENT):o===16?(Ee=0,ue=R.UNSIGNED_INT,De=R.DEPTH_COMPONENT24,oe=R.DEPTH_ATTACHMENT):(o===13||o===17)&&(Ee=12,ue=R.UNSIGNED_INT_24_8,De=R.DEPTH24_STENCIL8,Te=R.DEPTH_STENCIL,oe=R.DEPTH_STENCIL_ATTACHMENT),R.activeTexture(R.TEXTURE0),R.bindTexture(R.TEXTURE_2D,fe._hardwareTexture.underlyingResource),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_MAG_FILTER,R.NEAREST),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_MIN_FILTER,R.NEAREST),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_WRAP_S,R.CLAMP_TO_EDGE),R.texParameteri(R.TEXTURE_2D,R.TEXTURE_WRAP_T,R.CLAMP_TO_EDGE),R.texImage2D(R.TEXTURE_2D,0,De,k,B,0,Te,ue,null),R.framebufferTexture2D(R.FRAMEBUFFER,oe,R.TEXTURE_2D,fe._hardwareTexture.underlyingResource,0),fe.baseWidth=k,fe.baseHeight=B,fe.width=k,fe.height=B,fe.isReady=!0,fe.samples=1,fe.generateMipMaps=i,fe.samplingMode=1,fe.format=o,fe.type=Ee,Q[l]=fe,this._internalTexturesCache.push(fe)}return I.setTextures(Q),t&&R.drawBuffers(ne),this._bindUnboundFramebuffer(null),I.setLayerAndFaceIndices(y,C),this.resetTextureCache(),I};nt.prototype.updateMultipleRenderTargetTextureSampleCount=function(a,e,t=!0){if(this.webGLVersion<2||!a||!a.texture)return 1;if(a.samples===e)return e;const i=a._attachments.length;if(i===0)return 1;const s=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples);const r=!!a._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(a._depthStencilBuffer),a._depthStencilBuffer=null),a._MSAAFramebuffer&&(s.deleteFramebuffer(a._MSAAFramebuffer),a._MSAAFramebuffer=null),e>1&&typeof s.renderbufferStorageMultisample=="function"){const n=s.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");a._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let l=0;l1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(h.width,h.height,e,-1,this._getRGBABufferInternalSizedFormat(h.type,h.format,h._useSRGBBuffer),u);if(!d)throw new Error("Unable to create multi sampled framebuffer");c.addMSAARenderBuffer(d),h.samples=e,o.push(u)}t&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(a._framebuffer);return r&&(a._depthStencilBuffer=this._setupFramebufferDepthAttachments(a._generateStencilBuffer,a._generateDepthBuffer,a.texture.width,a.texture.height,e)),this._bindUnboundFramebuffer(null),e};nt.prototype._createDepthStencilCubeTexture=function(a,e){const t=new $t(this,xt.DepthStencil);if(t.isCube=!0,this.webGLVersion===1)return U.Error("Depth cube texture is not supported by WebGL 1."),t;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let r=0;r<6;r++)i.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH24_STENCIL8,a,a,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,s.DEPTH_COMPONENT24,a,a,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};nt.prototype._setCubeMapTextureParams=function(a,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),a.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),a._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};nt.prototype.createCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d,f=!1){const m=this._gl;return this.createCubeTextureBase(a,e,t,!!i,s,r,n,o,l,h,c,u,_=>this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,_,!0),(_,x)=>{const E=this.needPOTTextures?on(x[0].width,this._caps.maxCubemapTextureSize):x[0].width,S=E,C=[m.TEXTURE_CUBE_MAP_POSITIVE_X,m.TEXTURE_CUBE_MAP_POSITIVE_Y,m.TEXTURE_CUBE_MAP_POSITIVE_Z,m.TEXTURE_CUBE_MAP_NEGATIVE_X,m.TEXTURE_CUBE_MAP_NEGATIVE_Y,m.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(m.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const y=n?this._getInternalFormat(n,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:m.RGBA;let A=n?this._getInternalFormat(n):m.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(A=y);for(let I=0;I{this.unRegisterView(a)}),s};ee.prototype.unRegisterView=function(a){if(!this.views||this.views.length===0)return this;for(const e of this.views)if(e.target===a){const t=this.views.indexOf(e);t!==-1&&this.views.splice(t,1);break}return this};ee.prototype._renderViewStep=function(a){const e=a.target,t=e.getContext("2d");if(!t)return!0;const i=this.getRenderingCanvas();XP.notifyObservers(a);const s=a.camera;let r=null,n=null,o=null;if(s&&(o=Array.isArray(s)?s[0].getScene():s.getScene(),r=o.activeCamera,n=o.activeCameras,this.activeView=a,Array.isArray(s)?o.activeCameras=s:(o.activeCamera=s,o.activeCameras=null)),a.customResize)a.customResize(e);else{const l=Math.floor(e.clientWidth/this._hardwareScalingLevel),h=Math.floor(e.clientHeight/this._hardwareScalingLevel),c=l!==e.width||i.width!==e.width||h!==e.height||i.height!==e.height;e.clientWidth&&e.clientHeight&&c&&(e.width=l,e.height=h,this.setSize(l,h))}return!i.width||!i.height?!1:(this._renderFrame(),this.flushFramebuffer(),a.clearBeforeCopy&&t.clearRect(0,0,i.width,i.height),t.drawImage(i,0,0),o&&(o.activeCameras=n,o.activeCamera=r),YP.notifyObservers(a),!0)};ee.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)};nt.prototype.createStorageBuffer=function(a,e){throw new Error("createStorageBuffer: Unsupported method in this engine!")};nt.prototype.updateStorageBuffer=function(a,e,t,i){};nt.prototype.readFromStorageBuffer=function(a,e,t,i){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")};nt.prototype.setStorageBuffer=function(a,e){throw new Error("setStorageBuffer: Unsupported method in this engine!")};function Hz(a){const e=r=>{const n="\\b"+r+"\\b";return a&&(a===r||a.match(new RegExp(n,"g")))};if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(e))return a;const t=a.lastIndexOf("."),i=a.lastIndexOf("?"),s=i>-1?a.substring(i,a.length):"";return(t>-1?a.substring(0,t):a)+this._textureFormatInUse+s}Object.defineProperty(ee.prototype,"texturesSupported",{get:function(){const a=[];return this._caps.astc&&a.push("-astc.ktx"),this._caps.s3tc&&a.push("-dxt.ktx"),this._caps.pvrtc&&a.push("-pvrtc.ktx"),this._caps.etc2&&a.push("-etc2.ktx"),this._caps.etc1&&a.push("-etc1.ktx"),a},enumerable:!0,configurable:!0});Object.defineProperty(ee.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0});ee.prototype.setCompressedTextureExclusions=function(a){this._excludedCompressedTextures=a};ee.prototype.setTextureFormatToUse=function(a){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}}cc.DEFAULT_BUFFER_SIZE=65536;const vo=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],Xz=[()=>1,a=>a.y,a=>a.z,a=>a.x,a=>a.x*a.y,a=>a.y*a.z,a=>3*a.z*a.z-1,a=>a.x*a.z,a=>a.x*a.x-a.y*a.y],sl=(a,e)=>vo[a]*Xz[a](e),rl=[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 uc{constructor(){this.preScaled=!1,this.l00=T.Zero(),this.l1_1=T.Zero(),this.l10=T.Zero(),this.l11=T.Zero(),this.l2_2=T.Zero(),this.l2_1=T.Zero(),this.l20=T.Zero(),this.l21=T.Zero(),this.l22=T.Zero()}addLight(e,t,i){W.Vector3[0].set(t.r,t.g,t.b);const s=W.Vector3[0],r=W.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(sl(0,e),W.Vector3[2]),this.l00.addInPlace(W.Vector3[2]),r.scaleToRef(sl(1,e),W.Vector3[2]),this.l1_1.addInPlace(W.Vector3[2]),r.scaleToRef(sl(2,e),W.Vector3[2]),this.l10.addInPlace(W.Vector3[2]),r.scaleToRef(sl(3,e),W.Vector3[2]),this.l11.addInPlace(W.Vector3[2]),r.scaleToRef(sl(4,e),W.Vector3[2]),this.l2_2.addInPlace(W.Vector3[2]),r.scaleToRef(sl(5,e),W.Vector3[2]),this.l2_1.addInPlace(W.Vector3[2]),r.scaleToRef(sl(6,e),W.Vector3[2]),this.l20.addInPlace(W.Vector3[2]),r.scaleToRef(sl(7,e),W.Vector3[2]),this.l21.addInPlace(W.Vector3[2]),r.scaleToRef(sl(8,e),W.Vector3[2]),this.l22.addInPlace(W.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(rl[0]),this.l1_1.scaleInPlace(rl[1]),this.l10.scaleInPlace(rl[2]),this.l11.scaleInPlace(rl[3]),this.l2_2.scaleInPlace(rl[4]),this.l2_1.scaleInPlace(rl[5]),this.l20.scaleInPlace(rl[6]),this.l21.scaleInPlace(rl[7]),this.l22.scaleInPlace(rl[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(vo[0]),this.l1_1.scaleInPlace(vo[1]),this.l10.scaleInPlace(vo[2]),this.l11.scaleInPlace(vo[3]),this.l2_2.scaleInPlace(vo[4]),this.l2_1.scaleInPlace(vo[5]),this.l20.scaleInPlace(vo[6]),this.l21.scaleInPlace(vo[7]),this.l22.scaleInPlace(vo[8])}updateFromArray(e){return T.FromArrayToRef(e[0],0,this.l00),T.FromArrayToRef(e[1],0,this.l1_1),T.FromArrayToRef(e[2],0,this.l10),T.FromArrayToRef(e[3],0,this.l11),T.FromArrayToRef(e[4],0,this.l2_2),T.FromArrayToRef(e[5],0,this.l2_1),T.FromArrayToRef(e[6],0,this.l20),T.FromArrayToRef(e[7],0,this.l21),T.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return T.FromFloatsToRef(e[0],e[1],e[2],this.l00),T.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),T.FromFloatsToRef(e[6],e[7],e[8],this.l10),T.FromFloatsToRef(e[9],e[10],e[11],this.l11),T.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),T.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),T.FromFloatsToRef(e[18],e[19],e[20],this.l20),T.FromFloatsToRef(e[21],e[22],e[23],this.l21),T.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new uc().updateFromArray(e)}static FromPolynomial(e){const t=new uc;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 zo{constructor(){this.x=T.Zero(),this.y=T.Zero(),this.z=T.Zero(),this.xx=T.Zero(),this.yy=T.Zero(),this.zz=T.Zero(),this.xy=T.Zero(),this.yz=T.Zero(),this.zx=T.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=uc.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){W.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=W.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),W.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),W.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(W.Vector3[0]).addInPlace(W.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(W.Vector3[0]).subtractInPlace(W.Vector3[1]),this.zz.copyFrom(e.l00),W.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(W.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 zo().updateFromHarmonics(e)}static FromArray(e){const t=new zo;return T.FromArrayToRef(e[0],0,t.x),T.FromArrayToRef(e[1],0,t.y),T.FromArrayToRef(e[2],0,t.z),T.FromArrayToRef(e[3],0,t.xx),T.FromArrayToRef(e[4],0,t.yy),T.FromArrayToRef(e[5],0,t.zz),T.FromArrayToRef(e[6],0,t.yz),T.FromArrayToRef(e[7],0,t.zx),T.FromArrayToRef(e[8],0,t.xy),t}}const Yz="rgbdDecodePixelShader",$z=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;j.ShadersStore[Yz]=$z;const Kz="lodPixelShader",jz=`#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));}} +`;j.ShadersStore[Kz]=jz;const qz="lodCubePixelShader",Qz=`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));}} +`;j.ShadersStore[qz]=Qz;function Zz(a,e,t,i=!0){const s=a.getScene(),r=s.getEngine(),n=new Yi("resized"+a.name,{width:e,height:t},s,!a.noMipmap,!0,a._texture.type,!1,a.samplingMode,!1);n.wrapU=a.wrapU,n.wrapV=a.wrapV,n.uOffset=a.uOffset,n.vOffset=a.vOffset,n.uScale=a.uScale,n.vScale=a.vScale,n.uAng=a.uAng,n.vAng=a.vAng,n.wAng=a.wAng,n.coordinatesIndex=a.coordinatesIndex,n.level=a.level,n.anisotropicFilteringLevel=a.anisotropicFilteringLevel,n._texture.isReady=!1,a.wrapU=X.CLAMP_ADDRESSMODE,a.wrapV=X.CLAMP_ADDRESSMODE;const o=new uo("pass",1,null,i?X.BILINEAR_SAMPLINGMODE:X.NEAREST_SAMPLINGMODE,r,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(h){h.setTexture("textureSampler",a)};const l=n.renderTarget;l&&(s.postProcessManager.directRender([o],l),r.unBindFramebuffer(l),n.disposeFramebufferObjects(),o.dispose(),n.getInternalTexture().isReady=!0)}),n}function Kv(a,e,t,i,s,r,n,o){const l=e.getEngine();return e.isReady=!1,s=s??e.samplingMode,i=i??e.type,r=r??e.format,n=n??e.width,o=o??e.height,i===-1&&(i=0),new Promise(h=>{const c=new je("postprocess",a,null,null,1,null,s,l,!1,void 0,i,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:n,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:i,format:r});c.getEffect().executeWhenCompiled(()=>{c.onApply=d=>{d._bindTexture("textureSampler",e),d.setFloat2("scale",1,1)},t.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),c&&c.dispose(),u._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,h(e)})})}let Dm,n0;function Po(a){Dm||(Dm=new Float32Array(1),n0=new Int32Array(Dm.buffer)),Dm[0]=a;const e=n0[0];let t=e>>16&32768,i=e>>12&2047;const s=e>>23&255;return s<103?t:s>142?(t|=31744,t|=(s==255?0:1)&&e&8388607,t):s<113?(i|=2048,t|=(i>>114-s)+(i>>113-s&1),t):(t|=s-112<<10|i>>1,t+=i&1,t)}function Co(a){const e=(a&32768)>>15,t=(a&31744)>>10,i=a&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 Jz=async(a,e,t,i,s)=>{const r=a.getScene(),n=r.getEngine();let o;if(!a.isCube)o=new je("lod","lod",["lod","gamma"],null,1,null,X.NEAREST_NEAREST_MIPNEAREST,n);else{const c=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];o=new je("lodCube","lodCube",["lod","gamma"],null,1,null,X.NEAREST_NEAREST_MIPNEAREST,n,!1,c[i])}await new Promise(c=>{o.getEffect().executeWhenCompiled(()=>{c(0)})});const l=new Yi("temp",{width:e,height:t},r,!1);o.onApply=function(c){c.setTexture("textureSampler",a),c.setFloat("lod",s),c.setBool("gamma",a.gammaSpace)};const h=a.getInternalTexture();try{if(l.renderTarget&&h){const c=h.samplingMode;s!==0?a.updateSamplingMode(X.NEAREST_NEAREST_MIPNEAREST):a.updateSamplingMode(X.NEAREST_NEAREST),r.postProcessManager.directRender([o],l.renderTarget,!0),a.updateSamplingMode(c);const u=await n.readPixels(0,0,e,t),d=new Uint8Array(u.buffer,0,u.byteLength);return n.unBindFramebuffer(l.renderTarget),d}else throw Error("Render to texture failed.")}finally{l.dispose(),o.dispose()}};async function e4(a,e,t,i=0,s=0){return!a.isReady()&&a._texture&&await new Promise((r,n)=>{if(a._texture===null){n(0);return}a._texture.onLoadedObservable.addOnce(()=>{r(0)})}),await Jz(a,e,t,i,s)}const t4={CreateResizedCopy:Zz,ApplyPostProcess:Kv,ToHalfFloat:Po,FromHalfFloat:Co,GetTextureDataAsync:e4};class a0{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const l=new je("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);l.externalTextureSamplerBinding=!0;const h=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});l.getEffect().executeWhenCompiled(()=>{l.onApply=c=>{c._bindTexture("textureSampler",t),c.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([l],h,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),l&&l.dispose(),h._swapAndDie(t),t.isReady=!0})};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return Kv("rgbdEncode",e,t,i,1,5)}}class Xc{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class ff{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),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=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),h=e.gammaSpace,c=5;let u=0;return(e.textureType==1||e.textureType==2)&&(u=1),new Promise(f=>{Promise.all([s,i,r,n,o,l]).then(([m,_,x,E,S,C])=>{const y={size:t,right:_,left:m,up:x,down:E,front:S,back:C,format:c,type:u,gammaSpace:h};f(this.ConvertCubeMapToSphericalPolynomial(y))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new uc;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let d=0;d<6;d++){const f=this._FileFaces[d],m=e[f.name];let _=o;const x=e.format===5?4:3;for(let E=0;Ek){const ne=k/Q;I*=ne,R*=ne,N*=ne}}else I=Ne.Clamp(I,0,k),R=Ne.Clamp(R,0,k),N=Ne.Clamp(N,0,k);const B=new re(I,R,N);t.addLight(y,B,A),i+=A,S+=s}_+=r}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),zo.FromHarmonics(t)}}ff._FileFaces=[new Xc("right",new T(1,0,0),new T(0,0,-1),new T(0,-1,0)),new Xc("left",new T(-1,0,0),new T(0,0,1),new T(0,-1,0)),new Xc("up",new T(0,1,0),new T(1,0,0),new T(0,0,1)),new Xc("down",new T(0,-1,0),new T(1,0,0),new T(0,0,-1)),new Xc("front",new T(0,0,1),new T(1,0,0),new T(0,-1,0)),new Xc("back",new T(0,0,-1),new T(-1,0,0),new T(0,-1,0))];ff.MAX_HDRI_VALUE=4096;ff.PRESERVE_CLAMPED_COLORS=!1;Kt.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(Kt.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=ff.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(a=>{this._texture._sphericalPolynomial=a,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(a){this._texture&&(this._texture._sphericalPolynomial=a)},enumerable:!0,configurable:!0});const i4="rgbdEncodePixelShader",s4=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;j.ShadersStore[i4]=s4;const $P="image/png",o0=2,l0=[134,22,135,150,246,214,150,54];function KP(a){const e=new DataView(a.buffer,a.byteOffset,a.byteLength);let t=0;for(let n=0;no0)throw new Error(`Unsupported babylon environment map version "${a.version}". Latest supported version is "${o0}".`);return a.version===2||(a={...a,version:2,imageType:$P}),a}function jP(a,e){e=fx(e);const t=e.specular;let i=Ne.Log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);const s=new Array(i);for(let r=0;r{if(t){const f=e.createTexture(null,!0,!0,null,1,null,m=>{d(m)},a);i.getEffect().executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=m=>{m._bindTexture("textureSampler",f),m.setFloat2("scale",1,e._features.needsInvertingBitmap&&a instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],h,!0,r,n),e.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(s),u())})}else{if(e._uploadImageToTexture(c,a,r,n),o){const f=l[n];f&&e._uploadImageToTexture(f._texture,a,r,0)}u()}})}function KE(a,e,t=$P){if(!Z.IsExponentOfTwo(a.width))throw new Error("Texture size must be a power of two");const i=Ne.ILog2(a.width)+1,s=a.getEngine();let r=!1,n=!1,o=null,l=null,h=null;const c=s.getCaps();if(a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,a),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,a.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,a.type=1):r=!1:(r=!1,n=!0,h={}),r)o=new je("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,a.type,void 0,null,!1),a._isRGBD=!1,a.invertY=!1,l=s.createRenderTargetCubeTexture(a.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:a.type,format:5});else if(a._isRGBD=!0,a.invertY=!0,n){const f=a._lodGenerationScale,m=a._lodGenerationOffset;for(let _=0;_<3;_++){const E=1-_/2,S=m,C=(i-1)*f+m,y=S+(C-S)*E,A=Math.round(Math.min(Math.max(y,0),C)),I=new $t(s,xt.Temp);I.isCube=!0,I.invertY=!0,I.generateMipMaps=!1,s.updateTextureSamplingMode(2,I);const R=new Kt(null);switch(R._isCube=!0,R._texture=I,h[A]=R,_){case 0:a._lodTextureLow=R;break;case 1:a._lodTextureMid=R;break;case 2:a._lodTextureHigh=R;break}}}const u=[];for(let d=0;dh0(S,s,r,o,x,f,d,n,h,l,a));else{const S=new Image;S.src=x,E=new Promise((C,y)=>{S.onload=()=>{h0(S,s,r,o,x,f,d,n,h,l,a).then(()=>C()).catch(A=>{y(A)})},S.onerror=A=>{y(A)}})}u.push(E)}if(e.length{l&&(s._releaseTexture(a),l._swapAndDie(a)),o&&o.dispose(),n&&(a._lodTextureHigh&&a._lodTextureHigh._texture&&(a._lodTextureHigh._texture.isReady=!0),a._lodTextureMid&&a._lodTextureMid._texture&&(a._lodTextureMid._texture.isReady=!0),a._lodTextureLow&&a._lodTextureLow._texture&&(a._lodTextureLow._texture.isReady=!0))})}function qP(a,e){e=fx(e);const t=e.irradiance;if(!t)return;const i=new zo;T.FromArrayToRef(t.x,0,i.x),T.FromArrayToRef(t.y,0,i.y),T.FromArrayToRef(t.z,0,i.z),T.FromArrayToRef(t.xx,0,i.xx),T.FromArrayToRef(t.yy,0,i.yy),T.FromArrayToRef(t.zz,0,i.zz),T.FromArrayToRef(t.yz,0,i.yz),T.FromArrayToRef(t.zx,0,i.zx),T.FromArrayToRef(t.xy,0,i.xy),a._sphericalPolynomial=i}function n4(a,e,t,i,s){const r=a.getEngine().createRawCubeTexture(null,a.width,a.format,a.type,a.generateMipMaps,a.invertY,a.samplingMode,a._compression),n=KE(r,e).then(()=>a);return a.onRebuildCallback=o=>({proxy:n,isReady:!0,isAsync:!0}),a._source=xt.CubeRawRGBD,a._bufferViewArrayArray=e,a._lodGenerationScale=i,a._lodGenerationOffset=s,a._sphericalPolynomial=t,KE(a,e).then(()=>(a.isReady=!0,a))}function Nm(a,e,t,i){let s=i,r=0,n="";for(;s=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e==95}function jE(a){let e=0,t="",i=!1;const s=[];for(;e=0&&a.charAt(e)!==t&&(!i||a.charAt(e)!==i);)e--;return e}function o4(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class nc{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&U.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&U.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&f.push(E.substring(S+1))}r!=="void"&&f.push("return"),this._functionDescr.push({name:n,type:r,parameters:f,body:u,callIndex:0}),e=c+1;const m=t>0?this._sourceCode.substring(0,t):"",_=c+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&U.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const y=[];let A=0,I=0;for(;A0?this._sourceCode.substring(0,l):"";const S=c+1{const c=h[0];return _E(e.charAt(c-1))||_E(e.charAt(c+n))?t[s]:o})}return e}}nc._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class l4{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){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}_fillEffectInformation(e,t,i,s,r,n,o,l){const h=this._engine;if(h.supportsUniformBuffers)for(const d in t)e.bindUniformBlock(d,t[d]);this._engine.getUniforms(this,i).forEach((d,f)=>{s[i[f]]=d}),this._uniforms=s;let u;for(u=0;u{n[d]=f}),l.push(...h.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return i!==void 0&&i===s?!1:(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(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,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(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,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(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 h4 extends yv{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,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class u0{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 mE(a,e){switch(a){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 oo(`Unsupported texture format or type: format ${a}, type ${e}.`,ml.UnsupportedTextureError)}function jf(a){switch(a){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: ${a}.`)}}function gE(a){switch(a){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: "+a+".")}}function c4(a){switch(a){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: ${a}.`)}}function u4(a){switch(a){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: ${a}.`)}}function d4(a){switch(a){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: ${a}.`)}}function f4(a){switch(a){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: ${a}.`)}}function p4(a){switch(a){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: ${a}.`)}}function _4(a){switch(a){case P.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case P.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case P.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case P.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case P.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${a}.`)}}const QP=new K;if(typeof self<"u"&&!Object.prototype.hasOwnProperty.call(self,"_native")){let a;Object.defineProperty(self,"_native",{get:()=>a,set:e=>{a=e,a&&QP.notifyObservers(a)}})}function m4(){return new Promise(a=>{typeof _native>"u"?QP.addOnce(e=>a(e)):a(_native)})}async function g4(a,e){(await m4())[a]=e}class d0 extends _c{}class x4{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=Iu._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}}class Iu extends ee{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new x4(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,_native.Engine.PROTOCOL_VERSION!==Iu.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${Iu.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:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},Z.Log("Babylon Native (v"+ee.Version+") launched"),Z.LoadScript=function(s,r,n,o){Z.LoadFile(s,l=>{Function(l).apply(null),r&&r()},void 0,void 0,!1,(l,h)=>{n&&n("LoadScript Error",h)})},typeof URL>"u"&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),typeof Blob>"u"&&(window.Blob=function(s){return s}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function s(){const r=isNaN(arguments[0])?1:Number(arguments[0]);return r?Array.prototype.reduce.call(this,function(n,o){return Array.isArray(o)?n.push.apply(n,s.call(o,r-1)):n.push(o),n},[]):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 XI,this.onNewSceneAddedObservable.add(s=>{const r=s.render;s.render=(...n)=>{this._commandBufferEncoder.beginCommandScope(),r.apply(s,n),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new cc}_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,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,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,s=!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(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new d0;return r.references=1,r.is32Bits=s.BYTES_PER_ELEMENT===4,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new d0;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let o=0;o=0){const h=n[o];let c=null;if(r&&(c=r[h]),c||(c=t[h]),c){const u=c.getBuffer();u&&u.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,u.nativeVertexBuffer,l,c.byteOffset,c.byteStride,c.getSize(),_4(c.type),c.normalized,c.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,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_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;return this._engine.getAttributes(i.program,t)}drawElementsType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,s){this._drawCalls.addCount(1,!1),s&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){const e=!!(this._caps.parallelShaderCompile&&this._engine.createProgramAsync);return new l4(this,e)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,s,r,n,o,l){s?this.createRawShaderProgram():this.createShaderProgram(e,t,i,l)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(i.isAsync)if(i.onCompiled){const s=i.onCompiled;i.onCompiled=()=>{s(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new nc(t);n.processCode(),t=n.code;const o=new nc(i);o.processCode(),i=o.code,t=nt._ConcatenateShader(t,s),i=nt._ConcatenateShader(i,s);const l=()=>{var h;r.isCompiled=!0,(h=r.onCompiled)==null||h.call(r),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,l,h=>{r.compilationError=h});else try{r.program=this._engine.createProgram(t,i),l()}catch(h){const c=h==null?void 0:h.message;throw new Error("SHADER ERROR"+(typeof c=="string"?` +`+c:""))}return r.program}inlineShaderCode(e){const t=new nc(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 s=0;s{}}}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,u4(this._stencilOpStencilFail),d4(this._stencilOpDepthFail),f4(this._stencilOpStencilDepthPass),c4(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),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,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=p4(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(e===0),this._alphaMode=e}getAlphaMode(){return this._alphaMode}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,s){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0):!1}setFloat4(e,t,i,s,r){return e?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),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)}updateDynamicTexture(e,t,i,s=!1,r){if(s===void 0&&(s=!1),e&&e._hardwareTexture){const n=t.getCanvasTexture(),o=e._hardwareTexture.underlyingResource;this._engine.copyTexture(o,n),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,l=null,h=0,c=0,u=!1){const d=new $t(this,xt.Raw);if(d.format=s,d.generateMipMaps=r,d.samplingMode=o,d.invertY=n,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=l,d.type=h,d._useSRGBBuffer=this._getUseSRGBBuffer(u,!r),this.updateRawTexture(d,e,s,n,l,h,d._useSRGBBuffer),d._hardwareTexture){const f=d._hardwareTexture.underlyingResource,m=jf(o);this._setTextureSampling(f,m)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,s,r,n,o,l,h=null,c=0){const u=new $t(this,xt.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=s,u.width=t,u.height=i,u.depth=s,u.format=r,u.type=c,u.generateMipMaps=n,u.samplingMode=l,u.is2DArray=!0,u._hardwareTexture){const d=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(d,e,t,i,s,mE(r,c),n,o);const f=jf(l);this._setTextureSampling(d,f)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const l=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(l,t,e.width,e.height,mE(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,m,_=!1){e=e||"";const x=e.substr(0,5)==="data:",E=x&&e.indexOf(";base64,")!==-1,S=h||new $t(this,xt.Url),C=e;this._transformTextureUrl&&!E&&!h&&!l&&(e=this._transformTextureUrl(e));const y=e.lastIndexOf("."),A=u||(y>-1?e.substring(y).toLowerCase():"");let I=null;for(const k of He._TextureLoaders)if(k.canLoad(A)){I=k;break}s&&s.addPendingData(S),S.url=e,S.generateMipMaps=!t,S.samplingMode=r,S.invertY=i,S._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(S._buffer=l);let R=null;n&&!h&&(R=S.onLoadedObservable.add(n)),h||this._internalTexturesCache.push(S);const N=(k,B)=>{s&&s.removePendingData(S),e===C?(R&&S.onLoadedObservable.remove(R),We.UseFallbackTexture&&this.createTexture(We.FallbackTexture,t,S.invertY,s,r,null,o,l,S),o&&o((k||"Unknown error")+(We.UseFallbackTexture?" - Fallback texture was used":""),B)):(U.Warn(`Failed to load ${e}, falling back to ${C}`),this.createTexture(C,t,S.invertY,s,r,n,o,l,S,c,u,d,f))};if(I)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const k=B=>{if(!S._hardwareTexture){s&&s.removePendingData(S);return}const Q=S._hardwareTexture.underlyingResource;this._engine.loadTexture(Q,B,!t,i,S._useSRGBBuffer,()=>{S.baseWidth=this._engine.getTextureWidth(Q),S.baseHeight=this._engine.getTextureHeight(Q),S.width=S.baseWidth,S.height=S.baseHeight,S.isReady=!0;const ne=jf(r);this._setTextureSampling(Q,ne),s&&s.removePendingData(S),S.onLoadedObservable.notifyObservers(S),S.onLoadedObservable.clear()},()=>{throw new Error("Could not load a native texture.")})};if(x&&l)if(l instanceof ArrayBuffer)k(new Uint8Array(l));else if(ArrayBuffer.isView(l))k(l);else if(typeof l=="string")k(new Uint8Array(Z.DecodeBase64(l)));else throw new Error("Unsupported buffer type");else E?k(new Uint8Array(Z.DecodeBase64(e))):this._loadFile(e,B=>k(new Uint8Array(B)),void 0,void 0,!0,(B,Q)=>{N("Unable to load "+(B&&B.responseURL,Q))})}return S}wrapNativeTexture(e,t=!1,i=3){const s=new u0(e,this._engine),r=new $t(this,xt.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new $t(this,xt.DepthStencil),l=e.width??e,h=e.height??e,c=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,s,!0,r);return n._framebufferDepthStencil=c,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((s,r)=>{const n=this.createCanvasImage();n.onload=()=>{try{const o=this._engine.createImageBitmap(n);s(o)}catch(o){r(`Error loading image ${n.src} with exception: ${o}`)}},n.onerror=o=>{r(`Error loading image ${n.src} with exception: ${o}`)},n.src=e})}createImageBitmap(e,t){return new Promise((i,s)=>{if(Array.isArray(e)){const r=e;if(r.length){const n=this._engine.createImageBitmap(r[0]);if(n){i(n);return}}}s("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,l=null,h=!1,c=0,u=0,d=null,f,m=!1){const _=d||new $t(this,xt.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!s,_._lodGenerationScale=c,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(m,!!s),this._doNotHandleContextLost||(_._extension=l,_._files=i);const x=e.lastIndexOf(".");if((l||(x>-1?e.substring(x).toLowerCase():""))===".env"){const S=C=>{const y=KP(C);_.width=y.width,_.height=y.width,qP(_,y);const A=y.specular;if(!A)throw new Error("Nothing else parsed so far");_._lodGenerationScale=A.lodGenerationScale;const I=jP(C,y);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(X.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,I,!1,_._useSRGBBuffer,()=>{_.isReady=!0,r&&r()},()=>{throw new Error("Could not load a native cube texture.")})};if(i&&i.length===6)throw new Error("Multi-file loading not allowed on env files.");{const C=(y,A)=>{n&&y&&n(y.status+" "+y.statusText,A)};this._loadFile(e,y=>{S(new Uint8Array(y,0,y.byteLength))},void 0,void 0,!0,C)}}else{if(!i||i.length!==6)throw new Error("Cannot load cubemap because 6 files were not defined");const S=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(S.map(C=>this._loadFileAsync(C,void 0,!0).then(y=>new Uint8Array(y,0,y.byteLength)))).then(C=>new Promise((y,A)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,C,!s,!0,_._useSRGBBuffer,y,A)})).then(()=>{_.isReady=!0,r&&r()},C=>{n&&n(`Failed to load cubemap: ${C.message}`,C)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new u0(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new h4(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=xt.Unknown){let r=!1,n=0,o=3,l=5,h=!1,c=1,u;t!==void 0&&typeof t=="object"?(r=!!t.generateMipMaps,n=t.type===void 0?0:t.type,o=t.samplingMode===void 0?3:t.samplingMode,l=t.format===void 0?5:t.format,h=t.useSRGBBuffer===void 0?!1:t.useSRGBBuffer,c=t.samples??1,u=t.label):r=!!t,h=this._getUseSRGBBuffer(h,!r),(n===1&&!this._caps.textureFloatLinearFiltering||n===2&&!this._caps.textureHalfFloatLinearFiltering)&&(o=1),n===1&&!this._caps.textureFloat&&(n=0,U.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=new $t(this,s),f=e.width??e,m=e.height??e,_=e.layers||0;if(_!==0)throw new Error("Texture layers are not supported in Babylon Native");const x=d._hardwareTexture.underlyingResource,E=mE(l,n);return this._engine.initializeTexture(x,f,m,r,E,!0,h,c),this._setTextureSampling(x,jf(o)),d._useSRGBBuffer=h,d.baseWidth=f,d.baseHeight=m,d.width=f,d.height=m,d.depth=_,d.isReady=!0,d.samples=c,d.generateMipMaps=r,d.samplingMode=o,d.type=n,d.format=l,d.label=u,this._internalTexturesCache.push(d),d}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s=!0,r=!1,n=!1,o,l=1;t!==void 0&&typeof t=="object"&&(s=t.generateDepthBuffer??!0,r=!!t.generateStencilBuffer,n=!!t.noColorAttachment,o=t.colorAttachment,l=t.samples??1);const h=o||(n?null:this._createInternalTexture(e,t,!0,xt.RenderTarget)),c=e.width??e,u=e.height??e,d=this._engine.createFrameBuffer(h?h._hardwareTexture.underlyingResource:null,c,u,r,s,l);return i._framebuffer=d,i._generateDepthBuffer=s,i._generateStencilBuffer=r,i._samples=l,i.setTextures(h),i}updateRenderTargetTextureSampleCount(e,t){return U.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=jf(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=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||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._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 s=e,r=this._normalizeIndexData(t);s.is32Bits=r.BYTES_PER_ELEMENT===4,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===4)return t.delayLoad(),!1;let n;return s?n=t.depthStencilTexture:t.isReady()?n=t.getInternalTexture():t.isCube?n=this.emptyCubeTexture:t.is3D?n=this.emptyTexture3D:t.is2DArray?n=this.emptyTexture2DArray:n=this.emptyTexture,this._activeChannel=e,!n||!n._hardwareTexture?!1:(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,gE(t.wrapU),gE(t.wrapV),gE(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(r,n._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,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),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&&t&&t._hardwareTexture){const s=t._hardwareTexture.underlyingResource;this._setTextureCore(i,s)}}_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,s,r,n,o=0,l=0,h=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,l,h,c){var u;if(s!==void 0&&s!==-1)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture((u=e._hardwareTexture)==null?void 0:u.underlyingResource,r??0,h??0,c??0,t,i,(n==null?void 0:n.buffer)??null,(n==null?void 0:n.byteOffset)??0,(n==null?void 0:n.byteLength)??0).then(d=>(n||(n=new Uint8Array(d)),n))}}Iu.PROTOCOL_VERSION=8;Iu._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new T4:new cc};class T4 extends cc{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 f0;(function(a){a.LowPower="low-power",a.HighPerformance="high-performance"})(f0||(f0={}));var Ro;(function(a){a.DepthClipControl="depth-clip-control",a.Depth32FloatStencil8="depth32float-stencil8",a.TextureCompressionBC="texture-compression-bc",a.TextureCompressionETC2="texture-compression-etc2",a.TextureCompressionASTC="texture-compression-astc",a.TimestampQuery="timestamp-query",a.IndirectFirstInstance="indirect-first-instance",a.ShaderF16="shader-f16",a.RG11B10UFloatRenderable="rg11b10ufloat-renderable",a.BGRA8UnormStorage="bgra8unorm-storage",a.Float32Filterable="float32-filterable"})(Ro||(Ro={}));var p0;(function(a){a.Unmapped="unmapped",a.Pending="pending",a.Mapped="mapped"})(p0||(p0={}));var gi;(function(a){a[a.MapRead=1]="MapRead",a[a.MapWrite=2]="MapWrite",a[a.CopySrc=4]="CopySrc",a[a.CopyDst=8]="CopyDst",a[a.Index=16]="Index",a[a.Vertex=32]="Vertex",a[a.Uniform=64]="Uniform",a[a.Storage=128]="Storage",a[a.Indirect=256]="Indirect",a[a.QueryResolve=512]="QueryResolve"})(gi||(gi={}));var ac;(function(a){a[a.Read=1]="Read",a[a.Write=2]="Write"})(ac||(ac={}));var Ba;(function(a){a.E1d="1d",a.E2d="2d",a.E3d="3d"})(Ba||(Ba={}));var zi;(function(a){a[a.CopySrc=1]="CopySrc",a[a.CopyDst=2]="CopyDst",a[a.TextureBinding=4]="TextureBinding",a[a.StorageBinding=8]="StorageBinding",a[a.RenderAttachment=16]="RenderAttachment"})(zi||(zi={}));var kt;(function(a){a.E1d="1d",a.E2d="2d",a.E2dArray="2d-array",a.Cube="cube",a.CubeArray="cube-array",a.E3d="3d"})(kt||(kt={}));var io;(function(a){a.All="all",a.StencilOnly="stencil-only",a.DepthOnly="depth-only"})(io||(io={}));var V;(function(a){a.R8Unorm="r8unorm",a.R8Snorm="r8snorm",a.R8Uint="r8uint",a.R8Sint="r8sint",a.R16Uint="r16uint",a.R16Sint="r16sint",a.R16Float="r16float",a.RG8Unorm="rg8unorm",a.RG8Snorm="rg8snorm",a.RG8Uint="rg8uint",a.RG8Sint="rg8sint",a.R32Uint="r32uint",a.R32Sint="r32sint",a.R32Float="r32float",a.RG16Uint="rg16uint",a.RG16Sint="rg16sint",a.RG16Float="rg16float",a.RGBA8Unorm="rgba8unorm",a.RGBA8UnormSRGB="rgba8unorm-srgb",a.RGBA8Snorm="rgba8snorm",a.RGBA8Uint="rgba8uint",a.RGBA8Sint="rgba8sint",a.BGRA8Unorm="bgra8unorm",a.BGRA8UnormSRGB="bgra8unorm-srgb",a.RGB9E5UFloat="rgb9e5ufloat",a.RGB10A2UINT="rgb10a2uint",a.RGB10A2Unorm="rgb10a2unorm",a.RG11B10UFloat="rg11b10ufloat",a.RG32Uint="rg32uint",a.RG32Sint="rg32sint",a.RG32Float="rg32float",a.RGBA16Uint="rgba16uint",a.RGBA16Sint="rgba16sint",a.RGBA16Float="rgba16float",a.RGBA32Uint="rgba32uint",a.RGBA32Sint="rgba32sint",a.RGBA32Float="rgba32float",a.Stencil8="stencil8",a.Depth16Unorm="depth16unorm",a.Depth24Plus="depth24plus",a.Depth24PlusStencil8="depth24plus-stencil8",a.Depth32Float="depth32float",a.BC1RGBAUnorm="bc1-rgba-unorm",a.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",a.BC2RGBAUnorm="bc2-rgba-unorm",a.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",a.BC3RGBAUnorm="bc3-rgba-unorm",a.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",a.BC4RUnorm="bc4-r-unorm",a.BC4RSnorm="bc4-r-snorm",a.BC5RGUnorm="bc5-rg-unorm",a.BC5RGSnorm="bc5-rg-snorm",a.BC6HRGBUFloat="bc6h-rgb-ufloat",a.BC6HRGBFloat="bc6h-rgb-float",a.BC7RGBAUnorm="bc7-rgba-unorm",a.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",a.ETC2RGB8Unorm="etc2-rgb8unorm",a.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",a.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",a.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",a.ETC2RGBA8Unorm="etc2-rgba8unorm",a.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",a.EACR11Unorm="eac-r11unorm",a.EACR11Snorm="eac-r11snorm",a.EACRG11Unorm="eac-rg11unorm",a.EACRG11Snorm="eac-rg11snorm",a.ASTC4x4Unorm="astc-4x4-unorm",a.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",a.ASTC5x4Unorm="astc-5x4-unorm",a.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",a.ASTC5x5Unorm="astc-5x5-unorm",a.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",a.ASTC6x5Unorm="astc-6x5-unorm",a.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",a.ASTC6x6Unorm="astc-6x6-unorm",a.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",a.ASTC8x5Unorm="astc-8x5-unorm",a.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",a.ASTC8x6Unorm="astc-8x6-unorm",a.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",a.ASTC8x8Unorm="astc-8x8-unorm",a.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",a.ASTC10x5Unorm="astc-10x5-unorm",a.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",a.ASTC10x6Unorm="astc-10x6-unorm",a.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",a.ASTC10x8Unorm="astc-10x8-unorm",a.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",a.ASTC10x10Unorm="astc-10x10-unorm",a.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",a.ASTC12x10Unorm="astc-12x10-unorm",a.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",a.ASTC12x12Unorm="astc-12x12-unorm",a.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",a.Depth32FloatStencil8="depth32float-stencil8"})(V||(V={}));var tu;(function(a){a.ClampToEdge="clamp-to-edge",a.Repeat="repeat",a.MirrorRepeat="mirror-repeat"})(tu||(tu={}));var wt;(function(a){a.Nearest="nearest",a.Linear="linear"})(wt||(wt={}));var _0;(function(a){a.Nearest="nearest",a.Linear="linear"})(_0||(_0={}));var cr;(function(a){a.Never="never",a.Less="less",a.Equal="equal",a.LessEqual="less-equal",a.Greater="greater",a.NotEqual="not-equal",a.GreaterEqual="greater-equal",a.Always="always"})(cr||(cr={}));var jl;(function(a){a[a.Vertex=1]="Vertex",a[a.Fragment=2]="Fragment",a[a.Compute=4]="Compute"})(jl||(jl={}));var ah;(function(a){a.Uniform="uniform",a.Storage="storage",a.ReadOnlyStorage="read-only-storage"})(ah||(ah={}));var Th;(function(a){a.Filtering="filtering",a.NonFiltering="non-filtering",a.Comparison="comparison"})(Th||(Th={}));var Hn;(function(a){a.Float="float",a.UnfilterableFloat="unfilterable-float",a.Depth="depth",a.Sint="sint",a.Uint="uint"})(Hn||(Hn={}));var qE;(function(a){a.WriteOnly="write-only",a.ReadOnly="read-only",a.ReadWrite="read-write"})(qE||(qE={}));var m0;(function(a){a.Error="error",a.Warning="warning",a.Info="info"})(m0||(m0={}));var g0;(function(a){a.Validation="validation",a.Internal="internal"})(g0||(g0={}));var Up;(function(a){a.Auto="auto"})(Up||(Up={}));var Vn;(function(a){a.PointList="point-list",a.LineList="line-list",a.LineStrip="line-strip",a.TriangleList="triangle-list",a.TriangleStrip="triangle-strip"})(Vn||(Vn={}));var gg;(function(a){a.CCW="ccw",a.CW="cw"})(gg||(gg={}));var ap;(function(a){a.None="none",a.Front="front",a.Back="back"})(ap||(ap={}));var x0;(function(a){a[a.Red=1]="Red",a[a.Green=2]="Green",a[a.Blue=4]="Blue",a[a.Alpha=8]="Alpha",a[a.All=15]="All"})(x0||(x0={}));var Fr;(function(a){a.Zero="zero",a.One="one",a.Src="src",a.OneMinusSrc="one-minus-src",a.SrcAlpha="src-alpha",a.OneMinusSrcAlpha="one-minus-src-alpha",a.Dst="dst",a.OneMinusDst="one-minus-dst",a.DstAlpha="dst-alpha",a.OneMinusDstAlpha="one-minus-dst-alpha",a.SrcAlphaSaturated="src-alpha-saturated",a.Constant="constant",a.OneMinusConstant="one-minus-constant"})(Fr||(Fr={}));var ql;(function(a){a.Add="add",a.Subtract="subtract",a.ReverseSubtract="reverse-subtract",a.Min="min",a.Max="max"})(ql||(ql={}));var Ka;(function(a){a.Keep="keep",a.Zero="zero",a.Replace="replace",a.Invert="invert",a.IncrementClamp="increment-clamp",a.DecrementClamp="decrement-clamp",a.IncrementWrap="increment-wrap",a.DecrementWrap="decrement-wrap"})(Ka||(Ka={}));var Eh;(function(a){a.Uint16="uint16",a.Uint32="uint32"})(Eh||(Eh={}));var Ki;(function(a){a.Uint8x2="uint8x2",a.Uint8x4="uint8x4",a.Sint8x2="sint8x2",a.Sint8x4="sint8x4",a.Unorm8x2="unorm8x2",a.Unorm8x4="unorm8x4",a.Snorm8x2="snorm8x2",a.Snorm8x4="snorm8x4",a.Uint16x2="uint16x2",a.Uint16x4="uint16x4",a.Sint16x2="sint16x2",a.Sint16x4="sint16x4",a.Unorm16x2="unorm16x2",a.Unorm16x4="unorm16x4",a.Snorm16x2="snorm16x2",a.Snorm16x4="snorm16x4",a.Float16x2="float16x2",a.Float16x4="float16x4",a.Float32="float32",a.Float32x2="float32x2",a.Float32x3="float32x3",a.Float32x4="float32x4",a.Uint32="uint32",a.Uint32x2="uint32x2",a.Uint32x3="uint32x3",a.Uint32x4="uint32x4",a.Sint32="sint32",a.Sint32x2="sint32x2",a.Sint32x3="sint32x3",a.Sint32x4="sint32x4",a.UNORM10x10x10x2="unorm10-10-10-2"})(Ki||(Ki={}));var xg;(function(a){a.Vertex="vertex",a.Instance="instance"})(xg||(xg={}));var T0;(function(a){a.Beginning="beginning",a.End="end"})(T0||(T0={}));var E0;(function(a){a.Beginning="beginning",a.End="end"})(E0||(E0={}));var Fs;(function(a){a.Load="load",a.Clear="clear"})(Fs||(Fs={}));var na;(function(a){a.Store="store",a.Discard="discard"})(na||(na={}));var Tg;(function(a){a.Occlusion="occlusion",a.Timestamp="timestamp"})(Tg||(Tg={}));var Eg;(function(a){a.Opaque="opaque",a.Premultiplied="premultiplied"})(Eg||(Eg={}));var S0;(function(a){a.Unknown="unknown",a.Destroyed="destroyed"})(S0||(S0={}));var v0;(function(a){a.Validation="validation",a.OutOfMemory="out-of-memory",a.Internal="internal"})(v0||(v0={}));class Xi{constructor(){this.shaderLanguage=vt.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let r=0;r=0&&(d.push(o[u]),f.push(m))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=f}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new ze(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Xi.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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateInt4(e,t,i,s,r)}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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateUInt4(e,t,i,s,r)}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,s){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat3(e,t,i,s)}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,s,r){!this.uniformBuffer||!this._leftOverUniformsByName[e]||this.uniformBuffer.updateFloat4(e,t,i,s,r)}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 S4=4,v4=65536,C0={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Yn{static get KnownUBOs(){return Yn._SimplifiedKnownBindings?Yn._SimplifiedKnownUBOs:Yn._KnownUBOs}constructor(e){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=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Yn.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;s.groupIndex!==-1&&(t[s.groupIndex]===void 0?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.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+=(C0[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(C0[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>v4-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),this.freeGroupIndex===S4)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}}Yn._SimplifiedKnownBindings=!0;Yn._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}}};Yn._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 C4 extends Xi{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=vt.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const o=e.substring(r+1,n);s=+o,isNaN(s)&&(s=+i[o.trim()]),e=e.substr(0,r)}return[e,t,s]}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 ${Xi.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,s=e.indexOf("// Internals UBO")!==-1;return t?(this._fragmentIsGLES3=e.indexOf("#version 3")!==-1,this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+`##INJECTCODE## +`+e):(this._vertexIsGLES3=e.indexOf("#version 3")!==-1,this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){const i=/(flat\s)?\s*\bout\b/,s=/(flat\s)?\s*\bin\b/,r=/(flat\s)?\s*\bvarying\b/;return(t&&this._fragmentIsGLES3?s:!t&&this._vertexIsGLES3?i:r).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,r=/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,l=(t&&this._fragmentIsGLES3?r:!t&&this._vertexIsGLES3?s:n).exec(e);if(l!==null){const h=l[1]??"",c=l[2],u=l[3];let d;t?(d=this._webgpuProcessingContext.availableVaryings[u],this._missingVaryings[d]="",d===void 0&&U.Warn(`Invalid fragment shader: The varying named "${u}" is not declared in the vertex shader! This declaration will be ignored.`)):(d=this._webgpuProcessingContext.getVaryingNextLocation(c,this._getArraySize(u,c,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=d,this._missingVaryings[d]=`layout(location = ${d}) ${h} in ${c} ${u};`),e=e.replace(l[0],d===void 0?"":`layout(location = ${d}) ${h} ${t?"in":"out"} ${c} ${u};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=/\s*in\s+(\S+)\s+(\S+)\s*;/gm,s=/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,n=(this._vertexIsGLES3?i:s).exec(e);if(n!==null){const o=n[1],l=n[2],h=this._webgpuProcessingContext.getAttributeNextLocation(o,this._getArraySize(l,o,t)[2]);this._webgpuProcessingContext.availableAttributes[l]=h,this._webgpuProcessingContext.orderedAttributes[h]=l;const c=this.vertexBufferKindToNumberOfComponents[l];if(c!==void 0){const u=c<0?c===-1?"int":"ivec"+-c:c===1?"uint":"uvec"+c,d=`_int_${l}_`;e=e.replace(n[0],`layout(location = ${h}) in ${u} ${d}; ${o} ${l} = ${o}(${d});`)}else e=e.replace(n[0],`layout(location = ${h}) in ${o} ${l};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const r=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(r!==null){let n=r[1],o=r[2];if(n.indexOf("sampler")===0||n.indexOf("sampler")===1){let l=0;[o,n,l]=this._getArraySize(o,n,i);let h=this._webgpuProcessingContext.availableTextures[o];if(!h){h={autoBindSampler:!0,isTextureArray:l>0,isStorageTexture:!1,textures:[],sampleType:Hn.Float};for(let R=0;R<(l||1);++R)h.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const c=Xi._SamplerTypeByWebGLSamplerType[n]??"sampler",u=!!Xi._IsComparisonSamplerByWebGPUSamplerType[c],d=u?Th.Comparison:Th.Filtering,f=o+Xi.AutoSamplerSuffix;let m=this._webgpuProcessingContext.availableSamplers[f];m||(m={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:d});const _=n.charAt(0)==="u"?"u":n.charAt(0)==="i"?"i":"";_&&(n=n.substr(1));const x=u?Hn.Depth:_==="u"?Hn.Uint:_==="i"?Hn.Sint:Hn.Float;h.sampleType=x;const E=l>0,S=m.binding.groupIndex,C=m.binding.bindingIndex,y=Xi._SamplerFunctionByWebGLSamplerType[n],A=Xi._TextureTypeByWebGLSamplerType[n],I=Xi._GpuTextureViewDimensionByWebGPUTextureType[A];if(!E)l=1,e=`layout(set = ${S}, binding = ${C}) uniform ${c} ${f}; + layout(set = ${h.textures[0].groupIndex}, binding = ${h.textures[0].bindingIndex}) uniform ${_}${A} ${o}Texture; + #define ${o} ${_}${y}(${o}Texture, ${f})`;else{const R=[];R.push(`layout(set = ${S}, binding = ${C}) uniform ${_}${c} ${f};`),e=` +`;for(let N=0;N0?` +`:""}#define ${o}${N} ${_}${y}(${o}Texture${N}, ${f})`}e=R.join(` +`)+e,this._textureArrayProcessing.push(o)}this._webgpuProcessingContext.availableTextures[o]=h,this._webgpuProcessingContext.availableSamplers[f]=m,this._addSamplerBindingDescription(f,m,!t);for(let R=0;R=0,h=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,c=l?`vec4 glFragCoord_; +`:"",u=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,(n||u?"":`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##",c),l&&(e=this._injectStartingAndEndingCode(e,"void main",h))}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 s=i.exec(e);for(;s!==null;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(const s of this._webgpuProcessingContext.leftOverUniforms)s.length>0?i+=` ${s.type} ${s.name}[${s.length}]; +`:i+=` ${s.type} ${s.name}; +`;return i+=`}; + +`,i}finalizeShaders(e,t){for(let s=0;s0&&(t=r+` +`+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const b4="bonesDeclaration",y4=`#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 +`;j.IncludesShadersStoreWGSL[b4]=y4;const A4="bonesVertex",R4=`#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 +`;j.IncludesShadersStoreWGSL[A4]=R4;const I4="bakedVertexAnimationDeclaration",P4=`#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 +`;j.IncludesShadersStoreWGSL[I4]=P4;const M4="bakedVertexAnimation",O4=`#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 +`;j.IncludesShadersStoreWGSL[M4]=O4;const D4="clipPlaneFragment",N4=`#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 +`;j.IncludesShadersStoreWGSL[D4]=N4;const w4="clipPlaneFragmentDeclaration",F4=`#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 +`;j.IncludesShadersStoreWGSL[w4]=F4;const L4="clipPlaneVertex",B4=`#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 +`;j.IncludesShadersStoreWGSL[L4]=B4;const U4="clipPlaneVertexDeclaration",V4=`#ifdef CLIPPLANE +uniform vClipPlane: vec4;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 +`;j.IncludesShadersStoreWGSL[U4]=V4;const k4="instancesDeclaration",G4=`#ifdef INSTANCES +attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform previousWorld : mat4x4; +#endif +#endif +`;j.IncludesShadersStoreWGSL[k4]=G4;const z4="instancesVertex",W4=`#ifdef INSTANCES +var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=previousWorld; +#endif +#endif +`;j.IncludesShadersStoreWGSL[z4]=W4;const H4="helperFunctions",X4=`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; +#define saturate(x) clamp(x,0.0,1.0) +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: vec4)->vec4 +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +fn toLinearSpaceVec3(color: vec3)->vec3 +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#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 square(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;} +`;j.IncludesShadersStoreWGSL[H4]=X4;const Y4="fresnelFunction",$4=`#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 +`;j.IncludesShadersStoreWGSL[Y4]=$4;const K4="meshUboDeclaration",j4=`struct Mesh {world : mat4x4, +visibility : f32,};var mesh : Mesh; +#define WORLD_UBO +`;j.IncludesShadersStoreWGSL[K4]=j4;const q4="morphTargetsVertex",Q4=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +#if {X}==0 +for (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;} +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +} +#endif +#else +positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;j.IncludesShadersStoreWGSL[q4]=Q4;const Z4="morphTargetsVertexDeclaration",J4=`#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 +`;j.IncludesShadersStoreWGSL[Z4]=J4;const eW="morphTargetsVertexGlobal",tW=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;j.IncludesShadersStoreWGSL[eW]=tW;const iW="morphTargetsVertexGlobalDeclaration",sW=`#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 +`;j.IncludesShadersStoreWGSL[iW]=sW;const rW="sceneUboDeclaration",nW=`struct Scene {viewProjection : mat4x4, +#ifdef MULTIVIEW +viewProjectionR : mat4x4, +#endif +view : mat4x4, +projection : mat4x4, +vEyePosition : vec4,};var scene : Scene; +`;j.IncludesShadersStoreWGSL[rW]=nW;const b0="fragmentOutputs.fragDepth",aW="uniforms",oW="internals",lW={texture_1d:kt.E1d,texture_2d:kt.E2d,texture_2d_array:kt.E2dArray,texture_3d:kt.E3d,texture_cube:kt.Cube,texture_cube_array:kt.CubeArray,texture_multisampled_2d:kt.E2d,texture_depth_2d:kt.E2d,texture_depth_2d_array:kt.E2dArray,texture_depth_cube:kt.Cube,texture_depth_cube_array:kt.CubeArray,texture_depth_multisampled_2d:kt.E2d,texture_storage_1d:kt.E1d,texture_storage_2d:kt.E2d,texture_storage_2d_array:kt.E2dArray,texture_storage_3d:kt.E3d,texture_external:null};class hW extends Xi{constructor(){super(...arguments),this.shaderLanguage=vt.WGSL,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}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let n=r;for(;n>0&&t.charAt(n)!==" "&&t.charAt(n)!==",";)n--;const o=t.substring(n+1,r);for(s=+o,isNaN(s)&&(s=+i[o.trim()]);n>0&&(t.charAt(n)===" "||t.charAt(n)===",");)n--;t=t.substring(t.indexOf("<")+1,n+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Xi.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var ${oW} : ${Xi.InternalsUBOName}; +`;return e.indexOf(t)!==-1?e:t+jE(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const r=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(r!==null){const n=r[1]??"perspective",o=r[2]??"center",l=r[4],h=r[3],c=n==="flat"?`@interpolate(${n})`:`@interpolate(${n}, ${o})`;let u;t?(u=this._webgpuProcessingContext.availableVaryings[h],u===void 0&&U.Warn(`Invalid fragment shader: The varying named "${h}" is not declared in the vertex shader! This declaration will be ignored.`)):(u=this._webgpuProcessingContext.getVaryingNextLocation(l,this._getArraySize(h,l,i)[2]),this._webgpuProcessingContext.availableVaryings[h]=u,this._varyingsWGSL.push(` @location(${u}) ${c} ${h} : ${l},`),this._varyingNamesWGSL.push(h)),e=""}return e}attributeProcessor(e,t){const s=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(s!==null){const r=s[2],n=s[1],o=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=o,this._webgpuProcessingContext.orderedAttributes[o]=n;const l=this.vertexBufferKindToNumberOfComponents[n];if(l!==void 0){const h=l<0?l===-1?"i32":"vec"+-l+"":l===1?"u32":"vec"+l+"",c=`_int_${n}_`;this._attributesInputWGSL.push(`@location(${o}) ${c} : ${h},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = ${r}(vertexInputs_.${c});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${o}) ${n} : ${r},`),this._attributesWGSL.push(`${n} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = vertexInputs_.${n};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(s!==null){const r=s[2],n=s[1];this._addUniformToLeftOverUBO(n,r,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(s!==null){const r=s[1],n=s[2],o=!!s[3],l=s[4],h=l.indexOf("storage")>0,c=s[6],u=h?c.substring(0,c.indexOf(",")).trim():null;let d=o?this._getArraySize(r,n,i)[2]:0,f=this._webgpuProcessingContext.availableTextures[r];if(f)d=f.textures.length;else{f={isTextureArray:d>0,isStorageTexture:h,textures:[],sampleType:Hn.Float},d=d||1;for(let E=0;E0,_=lW[l],x=m?Hn.Depth:c==="u32"?Hn.Uint:c==="i32"?Hn.Sint:Hn.Float;if(f.sampleType=x,_===void 0)throw`Can't get the texture dimension corresponding to the texture function "${l}"!`;for(let E=0;E2?r[2]:""}return e.replace(/\$(\w+)\$/g,(s,r)=>i[r]??r)}finalizeShaders(e,t){const i=t.indexOf("fragmentInputs.position")>=0?` + 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 s=this._buildLeftOverUBO();e=s+e,t=s+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r=`struct VertexInputs { + @builtin(vertex_index) vertexIndex : u32, + @builtin(instance_index) instanceIndex : u32, +`;this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join(` +`)),r+=` +}; +var vertexInputs`+(this._hasNonFloatAttribute?"_":"")+` : VertexInputs; +`,this._hasNonFloatAttribute&&(r+=`struct VertexInputs_ { + vertexIndex : u32, instanceIndex : u32, +`,r+=this._attributesWGSL.join(` +`),r+=` +}; +var vertexInputs : VertexInputs_; +`);let n=`struct FragmentInputs { + @builtin(position) position : vec4, +`;this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join(` +`)),n+=` +}; +var vertexOutputs : FragmentInputs; +`,e=r+n+e;let o=` + vertexInputs${this._hasNonFloatAttribute?"_":""} = input; +`;this._hasNonFloatAttribute&&(o+=`vertexInputs.vertexIndex = vertexInputs_.vertexIndex; +vertexInputs.instanceIndex = vertexInputs_.instanceIndex; +`,o+=this._attributesConversionCodeWGSL.join(` +`),o+=` +`),e=this._injectStartingAndEndingCode(e,"fn main",o,` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`),t=t.replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let h=`struct FragmentInputs { + @builtin(position) position : vec4, + @builtin(front_facing) frontFacing : bool, +`;this._varyingsWGSL.length>0&&(h+=this._varyingsWGSL.join(` +`)),h+=` +}; +var fragmentInputs : FragmentInputs; +`;let c=`struct FragmentOutputs { + @location(0) color : vec4, +`,u=!1,d=0;for(;!u&&(d=t.indexOf(b0,d),!(d<0));){const _=d;for(u=!0;d>1&&t.charAt(d)!==` +`;){if(t.charAt(d)==="/"&&t.charAt(d-1)==="/"){u=!1;break}d--}d=_+b0.length}u&&(c+=` @builtin(frag_depth) fragDepth: f32, +`),c+=`}; +var fragmentOutputs : FragmentOutputs; +`,t=h+c+t;const f=` fragmentInputs = input; + `+i;return t=this._injectStartingAndEndingCode(t,"fn main",f," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} { +`;for(const r of this._webgpuProcessingContext.leftOverUniforms){const n=r.type.replace(/^(.*?)(<.*>)?$/,"$1"),o=Xi.UniformSizes[n];if(r.length>0)if(o<=2){const l=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${l} { + @size(16) + el: ${n}, + }`,this._stridedUniformArrays.push(r.name),s+=` @align(16) ${r.name} : array<${l}, ${r.length}>, +`}else s+=` ${r.name} : array<${r.type}, ${r.length}>, +`;else s+=` ${r.name} : ${r.type}, +`}return s+=`}; +`,s=`${i} +${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var ${aW} : ${e}; +`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(s===null)break;const r=s[1],n=s[2],o=r.indexOf(Xi.AutoSamplerSuffix)===r.length-Xi.AutoSamplerSuffix.length?r.substring(0,r.indexOf(Xi.AutoSamplerSuffix)):null,l=n==="sampler_comparison"?Th.Comparison:Th.Filtering;if(o){const f=this._webgpuProcessingContext.availableTextures[o];f&&(f.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[r];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[r]=h),this._addSamplerBindingDescription(r,h,t);const c=e.substring(0,s.index),u=`@group(${h.binding.groupIndex}) @binding(${h.binding.bindingIndex}) `,d=e.substring(s.index);e=c+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){var s;const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const r=i.exec(e);if(r===null)break;const n=r[1],o=r[3];let l=r[4];const h=r[5];let c=this._webgpuProcessingContext.availableBuffers[l];if(!c){const x=n==="uniform"?Yn.KnownUBOs[h]:null;let E;x?(l=h,E=x.binding,E.groupIndex===-1&&(E=(s=this._webgpuProcessingContext.availableBuffers[l])==null?void 0:s.binding,E||(E=this._webgpuProcessingContext.getNextFreeUBOBinding()))):E=this._webgpuProcessingContext.getNextFreeUBOBinding(),c={binding:E},this._webgpuProcessingContext.availableBuffers[l]=c}this._addBufferBindingDescription(l,this._webgpuProcessingContext.availableBuffers[l],o==="read_write"?ah.Storage:n==="storage"?ah.ReadOnlyStorage:ah.Uniform,t);const u=c.binding.groupIndex,d=c.binding.bindingIndex,f=e.substring(0,r.index),m=`@group(${u}) @binding(${d}) `,_=e.substring(r.index);e=f+m+_,i.lastIndex+=m.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 Zt{static ComputeNumMipmapLevels(e,t){return Ne.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case V.R8Unorm:case V.R8Snorm:case V.R8Uint:case V.R8Sint:case V.RG8Unorm:case V.RG8Snorm:case V.RG8Uint:case V.RG8Sint:case V.RGBA8Unorm:case V.RGBA8UnormSRGB:case V.RGBA8Snorm:case V.RGBA8Uint:case V.RGBA8Sint:case V.BGRA8Unorm:case V.BGRA8UnormSRGB:case V.RGB10A2UINT:case V.RGB10A2Unorm:case V.RGB9E5UFloat:case V.RG11B10UFloat:case V.BC7RGBAUnorm:case V.BC7RGBAUnormSRGB:case V.BC6HRGBUFloat:case V.BC6HRGBFloat:case V.BC5RGUnorm:case V.BC5RGSnorm:case V.BC3RGBAUnorm:case V.BC3RGBAUnormSRGB:case V.BC2RGBAUnorm:case V.BC2RGBAUnormSRGB:case V.BC4RUnorm:case V.BC4RSnorm:case V.BC1RGBAUnorm:case V.BC1RGBAUnormSRGB:case V.ETC2RGB8Unorm:case V.ETC2RGB8UnormSRGB:case V.ETC2RGB8A1Unorm:case V.ETC2RGB8A1UnormSRGB:case V.ETC2RGBA8Unorm:case V.ETC2RGBA8UnormSRGB:case V.EACR11Unorm:case V.EACR11Snorm:case V.EACRG11Unorm:case V.EACRG11Snorm:case V.ASTC4x4Unorm:case V.ASTC4x4UnormSRGB:case V.ASTC5x4Unorm:case V.ASTC5x4UnormSRGB:case V.ASTC5x5Unorm:case V.ASTC5x5UnormSRGB:case V.ASTC6x5Unorm:case V.ASTC6x5UnormSRGB:case V.ASTC6x6Unorm:case V.ASTC6x6UnormSRGB:case V.ASTC8x5Unorm:case V.ASTC8x5UnormSRGB:case V.ASTC8x6Unorm:case V.ASTC8x6UnormSRGB:case V.ASTC8x8Unorm:case V.ASTC8x8UnormSRGB:case V.ASTC10x5Unorm:case V.ASTC10x5UnormSRGB:case V.ASTC10x6Unorm:case V.ASTC10x6UnormSRGB:case V.ASTC10x8Unorm:case V.ASTC10x8UnormSRGB:case V.ASTC10x10Unorm:case V.ASTC10x10UnormSRGB:case V.ASTC12x10Unorm:case V.ASTC12x10UnormSRGB:case V.ASTC12x12Unorm:case V.ASTC12x12UnormSRGB:case V.Stencil8:return 0;case V.R16Uint:case V.R16Sint:case V.RG16Uint:case V.RG16Sint:case V.RGBA16Uint:case V.RGBA16Sint:case V.Depth16Unorm:return 5;case V.R16Float:case V.RG16Float:case V.RGBA16Float:return 2;case V.R32Uint:case V.R32Sint:case V.RG32Uint:case V.RG32Sint:case V.RGBA32Uint:case V.RGBA32Sint:return 7;case V.R32Float:case V.RG32Float:case V.RGBA32Float:case V.Depth32Float:case V.Depth32FloatStencil8:case V.Depth24Plus:case V.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case V.R8Unorm:case V.R8Snorm:case V.R8Uint:case V.R8Sint:return{width:1,height:1,length:1};case V.R16Uint:case V.R16Sint:case V.R16Float:case V.RG8Unorm:case V.RG8Snorm:case V.RG8Uint:case V.RG8Sint:return{width:1,height:1,length:2};case V.R32Uint:case V.R32Sint:case V.R32Float:case V.RG16Uint:case V.RG16Sint:case V.RG16Float:case V.RGBA8Unorm:case V.RGBA8UnormSRGB:case V.RGBA8Snorm:case V.RGBA8Uint:case V.RGBA8Sint:case V.BGRA8Unorm:case V.BGRA8UnormSRGB:case V.RGB9E5UFloat:case V.RGB10A2UINT:case V.RGB10A2Unorm:case V.RG11B10UFloat:return{width:1,height:1,length:4};case V.RG32Uint:case V.RG32Sint:case V.RG32Float:case V.RGBA16Uint:case V.RGBA16Sint:case V.RGBA16Float:return{width:1,height:1,length:8};case V.RGBA32Uint:case V.RGBA32Sint:case V.RGBA32Float:return{width:1,height:1,length:16};case V.Stencil8:throw"No fixed size for Stencil8 format!";case V.Depth16Unorm:return{width:1,height:1,length:2};case V.Depth24Plus:throw"No fixed size for Depth24Plus format!";case V.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case V.Depth32Float:return{width:1,height:1,length:4};case V.Depth32FloatStencil8:return{width:1,height:1,length:5};case V.BC7RGBAUnorm:case V.BC7RGBAUnormSRGB:case V.BC6HRGBUFloat:case V.BC6HRGBFloat:case V.BC5RGUnorm:case V.BC5RGSnorm:case V.BC3RGBAUnorm:case V.BC3RGBAUnormSRGB:case V.BC2RGBAUnorm:case V.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case V.BC4RUnorm:case V.BC4RSnorm:case V.BC1RGBAUnorm:case V.BC1RGBAUnormSRGB:return{width:4,height:4,length:8};case V.ETC2RGB8Unorm:case V.ETC2RGB8UnormSRGB:case V.ETC2RGB8A1Unorm:case V.ETC2RGB8A1UnormSRGB:case V.EACR11Unorm:case V.EACR11Snorm:return{width:4,height:4,length:8};case V.ETC2RGBA8Unorm:case V.ETC2RGBA8UnormSRGB:case V.EACRG11Unorm:case V.EACRG11Snorm:return{width:4,height:4,length:16};case V.ASTC4x4Unorm:case V.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case V.ASTC5x4Unorm:case V.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case V.ASTC5x5Unorm:case V.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case V.ASTC6x5Unorm:case V.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case V.ASTC6x6Unorm:case V.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case V.ASTC8x5Unorm:case V.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case V.ASTC8x6Unorm:case V.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case V.ASTC8x8Unorm:case V.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case V.ASTC10x5Unorm:case V.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case V.ASTC10x6Unorm:case V.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case V.ASTC10x8Unorm:case V.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case V.ASTC10x10Unorm:case V.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case V.ASTC12x10Unorm:case V.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case V.ASTC12x12Unorm:case V.ASTC12x12UnormSRGB: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 V.BC7RGBAUnormSRGB:case V.BC7RGBAUnorm:case V.BC6HRGBFloat:case V.BC6HRGBUFloat:case V.BC5RGSnorm:case V.BC5RGUnorm:case V.BC4RSnorm:case V.BC4RUnorm:case V.BC3RGBAUnormSRGB:case V.BC3RGBAUnorm:case V.BC2RGBAUnormSRGB:case V.BC2RGBAUnorm:case V.BC1RGBAUnormSRGB:case V.BC1RGBAUnorm:case V.ETC2RGB8Unorm:case V.ETC2RGB8UnormSRGB:case V.ETC2RGB8A1Unorm:case V.ETC2RGB8A1UnormSRGB:case V.ETC2RGBA8Unorm:case V.ETC2RGBA8UnormSRGB:case V.EACR11Unorm:case V.EACR11Snorm:case V.EACRG11Unorm:case V.EACRG11Snorm:case V.ASTC4x4Unorm:case V.ASTC4x4UnormSRGB:case V.ASTC5x4Unorm:case V.ASTC5x4UnormSRGB:case V.ASTC5x5Unorm:case V.ASTC5x5UnormSRGB:case V.ASTC6x5Unorm:case V.ASTC6x5UnormSRGB:case V.ASTC6x6Unorm:case V.ASTC6x6UnormSRGB:case V.ASTC8x5Unorm:case V.ASTC8x5UnormSRGB:case V.ASTC8x6Unorm:case V.ASTC8x6UnormSRGB:case V.ASTC8x8Unorm:case V.ASTC8x8UnormSRGB:case V.ASTC10x5Unorm:case V.ASTC10x5UnormSRGB:case V.ASTC10x6Unorm:case V.ASTC10x6UnormSRGB:case V.ASTC10x8Unorm:case V.ASTC10x8UnormSRGB:case V.ASTC10x10Unorm:case V.ASTC10x10UnormSRGB:case V.ASTC12x10Unorm:case V.ASTC12x10UnormSRGB:case V.ASTC12x12Unorm:case V.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return V.Depth16Unorm;case 16:return V.Depth24Plus;case 13:return V.Depth24PlusStencil8;case 14:return V.Depth32Float;case 18:return V.Depth32FloatStencil8;case 19:return V.Stencil8;case 36492:return i?V.BC7RGBAUnormSRGB:V.BC7RGBAUnorm;case 36495:return V.BC6HRGBUFloat;case 36494:return V.BC6HRGBFloat;case 33779:return i?V.BC3RGBAUnormSRGB:V.BC3RGBAUnorm;case 33778:return i?V.BC2RGBAUnormSRGB:V.BC2RGBAUnorm;case 33777:case 33776:return i?V.BC1RGBAUnormSRGB:V.BC1RGBAUnorm;case 37808:return i?V.ASTC4x4UnormSRGB:V.ASTC4x4Unorm;case 36196:case 37492:return i?V.ETC2RGB8UnormSRGB:V.ETC2RGB8Unorm;case 37496:return i?V.ETC2RGBA8UnormSRGB:V.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return V.R8Snorm;case 7:return V.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return V.R8Sint;case 9:return V.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return V.RGBA8Sint;default:return V.RGBA8Snorm}case 0:switch(t){case 6:return V.R8Unorm;case 7:return V.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?V.RGBA8UnormSRGB:V.RGBA8Unorm;case 12:return i?V.BGRA8UnormSRGB:V.BGRA8Unorm;case 8:return V.R8Uint;case 9:return V.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return V.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 V.RGBA8Unorm}case 4:switch(t){case 8:return V.R16Sint;case 9:return V.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return V.RGBA16Sint;default:return V.RGBA16Sint}case 5:switch(t){case 8:return V.R16Uint;case 9:return V.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return V.RGBA16Uint;default:return V.RGBA16Uint}case 6:switch(t){case 8:return V.R32Sint;case 9:return V.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return V.RGBA32Sint;default:return V.RGBA32Sint}case 7:switch(t){case 8:return V.R32Uint;case 9:return V.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case 11:return V.RGBA32Uint;default:return V.RGBA32Uint}case 1:switch(t){case 6:return V.R32Float;case 7:return V.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return V.RGBA32Float;default:return V.RGBA32Float}case 2:switch(t){case 6:return V.R16Float;case 7:return V.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return V.RGBA16Float;default:return V.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:return V.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return V.RG11B10UFloat}case 14:switch(t){case 5:return V.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 V.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 V.RGB10A2Unorm;case 11:return V.RGB10A2UINT;default:return V.RGB10A2Unorm}}return i?V.RGBA8UnormSRGB:V.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case V.R8Unorm:case V.R8Snorm:case V.R8Uint:case V.R8Sint:case V.BC4RUnorm:case V.BC4RSnorm:case V.R16Uint:case V.R16Sint:case V.Depth16Unorm:case V.R16Float:case V.R32Uint:case V.R32Sint:case V.R32Float:case V.Depth32Float:case V.Stencil8:case V.Depth24Plus:case V.EACR11Unorm:case V.EACR11Snorm:return 1;case V.RG8Unorm:case V.RG8Snorm:case V.RG8Uint:case V.RG8Sint:case V.Depth32FloatStencil8:case V.BC5RGUnorm:case V.BC5RGSnorm:case V.RG16Uint:case V.RG16Sint:case V.RG16Float:case V.RG32Uint:case V.RG32Sint:case V.RG32Float:case V.Depth24PlusStencil8:case V.EACRG11Unorm:case V.EACRG11Snorm:return 2;case V.RGB9E5UFloat:case V.RG11B10UFloat:case V.BC6HRGBUFloat:case V.BC6HRGBFloat:case V.ETC2RGB8Unorm:case V.ETC2RGB8UnormSRGB:return 3;case V.RGBA8Unorm:case V.RGBA8UnormSRGB:case V.RGBA8Snorm:case V.RGBA8Uint:case V.RGBA8Sint:case V.BGRA8Unorm:case V.BGRA8UnormSRGB:case V.RGB10A2UINT:case V.RGB10A2Unorm:case V.BC7RGBAUnorm:case V.BC7RGBAUnormSRGB:case V.BC3RGBAUnorm:case V.BC3RGBAUnormSRGB:case V.BC2RGBAUnorm:case V.BC2RGBAUnormSRGB:case V.BC1RGBAUnorm:case V.BC1RGBAUnormSRGB:case V.RGBA16Uint:case V.RGBA16Sint:case V.RGBA16Float:case V.RGBA32Uint:case V.RGBA32Sint:case V.RGBA32Float:case V.ETC2RGB8A1Unorm:case V.ETC2RGB8A1UnormSRGB:case V.ETC2RGBA8Unorm:case V.ETC2RGBA8UnormSRGB:case V.ASTC4x4Unorm:case V.ASTC4x4UnormSRGB:case V.ASTC5x4Unorm:case V.ASTC5x4UnormSRGB:case V.ASTC5x5Unorm:case V.ASTC5x5UnormSRGB:case V.ASTC6x5Unorm:case V.ASTC6x5UnormSRGB:case V.ASTC6x6Unorm:case V.ASTC6x6UnormSRGB:case V.ASTC8x5Unorm:case V.ASTC8x5UnormSRGB:case V.ASTC8x6Unorm:case V.ASTC8x6UnormSRGB:case V.ASTC8x8Unorm:case V.ASTC8x8UnormSRGB:case V.ASTC10x5Unorm:case V.ASTC10x5UnormSRGB:case V.ASTC10x6Unorm:case V.ASTC10x6UnormSRGB:case V.ASTC10x8Unorm:case V.ASTC10x8UnormSRGB:case V.ASTC10x10Unorm:case V.ASTC10x10UnormSRGB:case V.ASTC12x10Unorm:case V.ASTC12x10UnormSRGB:case V.ASTC12x12Unorm:case V.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case V.Stencil8:case V.Depth32FloatStencil8:case V.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case V.Depth32FloatStencil8:case V.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case V.Depth16Unorm:return V.Depth16Unorm;case V.Depth24Plus:return V.Depth24Plus;case V.Depth24PlusStencil8:return V.Depth24Plus;case V.Depth32Float:return V.Depth32Float;case V.Depth32FloatStencil8:return V.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Jm{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=V.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,s,r,n,o,l){let h=kt.E2d,c=1;s?(h=i?kt.CubeArray:kt.Cube,c=6*(l||1)):r?(h=kt.E3d,c=1):i&&(h=kt.E2dArray,c=l);const u=Zt.GetDepthFormatOnly(this.format),d=Zt.HasDepthAndStencilAspects(this.format)?io.DepthOnly:io.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+c:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${h}`,format:u,dimension:h,mipLevelCount:t?Ne.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:c,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 cW=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(location = 0) out vec2 vTex; + + void main() { + vTex = tex[gl_VertexIndex]; + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,uW=` + layout(set = 0, binding = 0) uniform sampler imgSampler; + layout(set = 0, binding = 1) uniform texture2D img; + + layout(location = 0) in vec2 vTex; + layout(location = 0) out vec4 outColor; + + void main() { + outColor = texture(sampler2D(img, imgSampler), vTex); + } + `,ZP=` + #extension GL_EXT_samplerless_texture_functions : enable + + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) out flat ivec2 vTextureSize; + #endif + + void main() { + #ifdef INVERTY + vTextureSize = textureSize(img, 0); + #endif + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,dW=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,fW=ZP,pW=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + layout(set = 0, binding = 1) uniform Params { + float ofstX; + float ofstY; + float width; + float height; + }; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { + discard; + } + if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { + discard; + } + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,_W=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,mW=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,gW=` + 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; + } + `,xW=` + @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); + } + `,TW=` + @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 Na;(function(a){a[a.MipMap=0]="MipMap",a[a.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",a[a.Clear=2]="Clear",a[a.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(Na||(Na={}));var iu;(function(a){a[a.DontInvertY=0]="DontInvertY",a[a.InvertY=1]="InvertY"})(iu||(iu={}));const y0=[{vertex:cW,fragment:uW},{vertex:ZP,fragment:dW},{vertex:_W,fragment:mW},{vertex:fW,fragment:pW}],Oo={"":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 EW{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,n.indexOf(Ro.RG11B10UFloatRenderable)!==-1){const o=Object.keys(Oo);Oo[V.RG11B10UFloat]=Oo[o[o.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:wt.Linear}),this._videoSampler=t.createSampler({minFilter:wt.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(4*4,gi.Uniform|gi.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(V.RGBA8Unorm),this._getVideoPipeline(V.RGBA8Unorm)}_getPipeline(e,t=Na.MipMap,i){const s=t===Na.MipMap?1:t===Na.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Na.Clear?8:t===Na.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n=`#version 450 +`;(t===Na.InvertYPremultiplyAlpha||t===Na.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+=`#define INVERTY +`),i.premultiplyAlpha&&(n+=`#define PREMULTIPLYALPHA +`));let o=this._compiledShaders[s];if(!o){let h=this._glslang.compileGLSL(n+y0[t].vertex,"vertex"),c=this._glslang.compileGLSL(n+y0[t].fragment,"fragment");this._tintWASM&&(h=this._tintWASM.convertSpirV2WGSL(h),c=this._tintWASM.convertSpirV2WGSL(c));const u=this._device.createShaderModule({code:h}),d=this._device.createShaderModule({code:c});o=this._compiledShaders[s]=[u,d]}const l=this._device.createRenderPipeline({layout:Up.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Vn.TriangleStrip,stripIndexFormat:Eh.Uint16}});r=this._pipelines[e][s]=[l,l.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=iu.DontInvertY){const i=t===iu.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let r=this._videoCompiledShaders[i];if(!r){const o=this._device.createShaderModule({code:gW}),l=this._device.createShaderModule({code:i===0?xW:TW});r=this._videoCompiledShaders[i]=[o,l]}const n=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${i===0?"DontInvertY":"InvertY"}`,layout:Up.Auto,vertex:{module:r[0],entryPoint:"main"},fragment:{module:r[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Vn.TriangleStrip,stripIndexFormat:Eh.Uint16}});s=this._videoPipelines[e][i]=[n,n.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){var m,_;const n=r===void 0,[o,l]=this._getVideoPipeline(i,s?iu.InvertY:iu.DontInvertY);n&&(r=this._device.createCommandEncoder({})),(m=r.pushDebugGroup)==null||m.call(r,`copy video to texture - invertY=${s}`);const h=t._hardwareTexture,c={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:h.underlyingResource.createView({format:i,dimension:kt.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:io.All}),loadOp:Fs.Load,storeOp:na.Store}]},u=r.beginRenderPass(c),d={layout:l,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(d);u.setPipeline(o),u.setBindGroup(0,f),u.draw(4,1,0,0),u.end(),(_=r.popDebugGroup)==null||_.call(r),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,l=0,h=1,c=0,u=0,d=0,f=0,m,_){var B,Q;const x=d!==0,E=m===void 0,[S,C]=this._getPipeline(s,x?Na.InvertYPremultiplyAlphaWithOfst:Na.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});o=Math.max(o,0),E&&(m=this._device.createCommandEncoder({})),(B=m.pushDebugGroup)==null||B.call(m,`internal process texture - invertY=${r} premultiplyAlpha=${n}`);let y;if(Zt.IsHardwareTexture(e)?(y=e.underlyingResource,r&&!n&&h===1&&o===0||(e=void 0)):(y=e,e=void 0),!y)return;x&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,d,f]),0,4*4);const A=e,I=(A==null?void 0:A._copyInvertYTempTexture)??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,m,zi.CopySrc|zi.RenderAttachment|zi.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),R=(A==null?void 0:A._copyInvertYRenderPassDescr)??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:I.createView({format:s,dimension:kt.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Fs.Load,storeOp:na.Store}]},N=m.beginRenderPass(R);let k=x?A==null?void 0:A._copyInvertYBindGroupWithOfst:A==null?void 0:A._copyInvertYBindGroup;if(!k){const ne={layout:C,entries:[{binding:0,resource:y.createView({format:s,dimension:kt.E2d,baseMipLevel:l,mipLevelCount:1,arrayLayerCount:h,baseArrayLayer:o})}]};x&&ne.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),k=this._device.createBindGroup(ne)}N.setPipeline(S),N.setBindGroup(0,k),N.draw(4,1,0,0),N.end(),m.copyTextureToTexture({texture:I},{texture:y,mipLevel:l,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=I,A._copyInvertYRenderPassDescr=R,x?A._copyInvertYBindGroupWithOfst=k:A._copyInvertYBindGroup=k):this._deferredReleaseTextures.push([I,null]),(Q=m.popDebugGroup)==null||Q.call(m),E&&(this._device.queue.submit([m.finish()]),m=null)}copyWithInvertY(e,t,i,s){var c,u;const r=s===void 0,[n,o]=this._getPipeline(t,Na.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),(c=s.pushDebugGroup)==null||c.call(s,"internal copy texture with invertY");const l=s.beginRenderPass(i),h=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});l.setPipeline(n),l.setBindGroup(0,h),l.draw(4,1,0,0),l.end(),(u=s.popDebugGroup)==null||u.call(s),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=V.RGBA8Unorm,l=1,h,c=-1,u=0,d){l=Zt.GetSample(l);const f=e.layers||1,m={width:e.width,height:e.height,depthOrArrayLayers:f},_=Oo[o]?zi.RenderAttachment:0,x=Zt.IsCompressedFormat(o),E=t?Zt.ComputeNumMipmapLevels(e.width,e.height):1,S=c>=0?c:zi.CopySrc|zi.CopyDst|zi.TextureBinding;u|=t&&!x?zi.CopySrc|_:0,!x&&!n&&(u|=_|zi.CopyDst);const C=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${d?d+"_":""}${m.width}x${m.height}x${m.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${l}`,size:m,dimension:n?Ba.E3d:Ba.E2d,format:o,usage:S|u,sampleCount:l,mipLevelCount:E});return Zt.IsImageBitmap(e)&&(this.updateTexture(e,C,e.width,e.height,f,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(C,o,E,0,n,h)),C}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=V.RGBA8Unorm,o=1,l,h=-1,c=0,u){o=Zt.GetSample(o);const d=Zt.IsImageBitmapArray(e)?e[0].width:e.width,f=Zt.IsImageBitmapArray(e)?e[0].height:e.height,m=Oo[n]?zi.RenderAttachment:0,_=Zt.IsCompressedFormat(n),x=t?Zt.ComputeNumMipmapLevels(d,f):1,E=h>=0?h:zi.CopySrc|zi.CopyDst|zi.TextureBinding;c|=t&&!_?zi.CopySrc|m:0,_||(c|=m|zi.CopyDst);const S=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${u?u+"_":""}${d}x${f}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:d,height:f,depthOrArrayLayers:6},dimension:Ba.E2d,format:n,usage:E|c,sampleCount:o,mipLevelCount:x});return Zt.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,S,d,f,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(S,n,x,l)),S}generateCubeMipmaps(e,t,i,s){var n,o;const r=s===void 0;r&&(s=this._device.createCommandEncoder({})),(n=s.pushDebugGroup)==null||n.call(s,`create cube mipmaps - ${i} levels`);for(let l=0;l<6;++l)this.generateMipmaps(e,t,i,l,!1,s);(o=s.popDebugGroup)==null||o.call(s),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){var d,f,m,_;const o=n===void 0,[l,h]=this._getPipeline(t);s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),(d=n.pushDebugGroup)==null||d.call(n,`create mipmaps for face #${s} - ${i} levels`);let c;if(Zt.IsHardwareTexture(e)?(c=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(c=e,e=void 0),!c)return;const u=e;for(let x=1;xc;)this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,c),u+=c;this._device.queue.writeBuffer(n,t+u,i.buffer,o+u,r-u)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=Co(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,l=0,h=null,c=!0,u=!1){const d=o===1?2:o===2?1:0,f=this._engine.uniqueId;return new Promise((m,_)=>{e.mapAsync(ac.Read,l,t).then(()=>{const x=e.getMappedRange(l,t);let E=h;if(u)E===null?E=HE(o,t,!0,x):E=HE(o,E.buffer,void 0,x);else if(E===null)switch(d){case 0:E=new Uint8Array(t),E.set(new Uint8Array(x));break;case 1:E=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,x);break;case 2:E=new Float32Array(t/4),E.set(new Float32Array(x));break}else switch(d){case 0:E=new Uint8Array(E.buffer),E.set(new Uint8Array(x));break;case 1:E=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,x,h);break;case 2:E=new Float32Array(E.buffer),E.set(new Float32Array(x));break}if(r!==n){d===1&&!u&&(r*=2,n*=2);const S=new Uint8Array(E.buffer);let C=r,y=0;for(let A=1;A{this._engine.isDisposed||this._engine.uniqueId!==f?m(new Uint8Array):_(x)})})}releaseBuffer(e){return Sg._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 vW[e.samplingMode]+CW[(e._comparisonFunction||514)-512+1]+bW[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,s,r,n,o;const l=e.useMipMaps;switch(e.samplingMode){case 11:i=wt.Linear,s=wt.Linear,r=wt.Nearest,l||(n=o=0);break;case 3:case 3:i=wt.Linear,s=wt.Linear,l?r=wt.Linear:(r=wt.Nearest,n=o=0);break;case 8:i=wt.Nearest,s=wt.Nearest,l?r=wt.Linear:(r=wt.Nearest,n=o=0);break;case 4:i=wt.Nearest,s=wt.Nearest,r=wt.Nearest,l||(n=o=0);break;case 5:i=wt.Nearest,s=wt.Linear,r=wt.Nearest,l||(n=o=0);break;case 6:i=wt.Nearest,s=wt.Linear,l?r=wt.Linear:(r=wt.Nearest,n=o=0);break;case 7:i=wt.Nearest,s=wt.Linear,r=wt.Nearest,n=o=0;break;case 1:case 1:i=wt.Nearest,s=wt.Nearest,r=wt.Nearest,n=o=0;break;case 9:i=wt.Linear,s=wt.Nearest,r=wt.Nearest,l||(n=o=0);break;case 10:i=wt.Linear,s=wt.Nearest,l?r=wt.Linear:(r=wt.Nearest,n=o=0);break;case 2:case 2:i=wt.Linear,s=wt.Linear,r=wt.Nearest,n=o=0;break;case 12:i=wt.Linear,s=wt.Nearest,r=wt.Nearest,n=o=0;break;default:i=wt.Nearest,s=wt.Nearest,r=wt.Nearest,n=o=0;break}return t>1&&(n!==0||o!==0)&&r!==wt.Nearest?{magFilter:wt.Linear,minFilter:wt.Linear,mipmapFilter:wt.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return tu.Repeat;case 0:return tu.ClampToEdge;case 2:return tu.MirrorRepeat}return tu.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,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?Jh.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return cr.Always;case 514:return cr.Equal;case 516:return cr.Greater;case 518:return cr.GreaterEqual;case 513:return cr.Less;case 515:return cr.LessEqual;case 512:return cr.Never;case 517:return cr.NotEqual;default:return cr.Less}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(Jh._GetSamplerDescriptor(e,s));t?i=0:i===0&&(i=Jh.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(Jh._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var ps;(function(a){a[a.StencilReadMask=0]="StencilReadMask",a[a.StencilWriteMask=1]="StencilWriteMask",a[a.DepthBias=2]="DepthBias",a[a.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",a[a.DepthStencilState=4]="DepthStencilState",a[a.MRTAttachments1=5]="MRTAttachments1",a[a.MRTAttachments2=6]="MRTAttachments2",a[a.RasterizationState=7]="RasterizationState",a[a.ColorStates=8]="ColorStates",a[a.ShaderStage=9]="ShaderStage",a[a.TextureStage=10]="TextureStage",a[a.VertexState=11]="VertexState",a[a.NumStates=12]="NumStates"})(ps||(ps={}));const wm={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},Yc={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},yW={[P.PositionKind]:!0,[P.NormalKind]:!0,[P.TangentKind]:!0,[P.UVKind]:!0,[P.UV2Kind]:!0,[P.UV3Kind]:!0,[P.UV4Kind]:!0,[P.UV5Kind]:!0,[P.UV6Kind]:!0,[P.ColorKind]:!0,[P.ColorInstanceKind]:!0,[P.MatricesIndicesKind]:!0,[P.MatricesWeightsKind]:!0,[P.MatricesIndicesExtraKind]:!0,[P.MatricesWeightsExtraKind]:!0};class Wi{static _IsSignedType(e){switch(e){case P.BYTE:case P.SHORT:case P.INT:case P.FLOAT:return!0;case P.UNSIGNED_BYTE:case P.UNSIGNED_SHORT:case P.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}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=[V.BGRA8Unorm],this.setColorFormat(V.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(V.Depth24PlusStencil8),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,s=0){if(i=Zt.GetSample(i),this.disabled){const n=Wi._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,i),Wi.NumCacheMiss++,Wi._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,Wi.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return Wi.NumCacheHitWithHash++,this._parameter.pipeline;const r=Wi._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),Wi.NumCacheMiss++,Wi._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){Wi.NumPipelineCreationLastFrame=Wi._NumPipelineCreationCurrentFrame,Wi._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,s,r,n,o,l){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(l??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[ps.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[ps.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Oo[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 s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,(this._mrtAttachments1!==i[0]||this._mrtAttachments2!==i[1])&&(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[ps.MRTAttachments1]=i[0],this._states[ps.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.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:Oo[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:Yc[e]}setStencilPassOp(e){this._stencilFrontPassOp=e===null?2:Yc[e]}setStencilFailOp(e){this._stencilFrontFailOp=e===null?1:Yc[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[ps.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[ps.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=i===null?1:Yc[i],this._stencilFrontPassOp=s===null?2:Yc[s],this._stencilFrontFailOp=r===null?1:Yc[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:return Vn.TriangleList;case 2:return Vn.PointList;case 1:return Vn.LineList;case 3:return Vn.PointList;case 4:return Vn.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Vn.LineStrip;case 7:return Vn.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return Vn.TriangleList}}static _GetAphaBlendOperation(e){switch(e){case 32774:return ql.Add;case 32778:return ql.Subtract;case 32779:return ql.ReverseSubtract;case 32775:return ql.Min;case 32776:return ql.Max;default:return ql.Add}}static _GetAphaBlendFactor(e){switch(e){case 0:return Fr.Zero;case 1:return Fr.One;case 768:return Fr.Src;case 769:return Fr.OneMinusSrc;case 770:return Fr.SrcAlpha;case 771:return Fr.OneMinusSrcAlpha;case 772:return Fr.DstAlpha;case 773:return Fr.OneMinusDstAlpha;case 774:return Fr.Dst;case 775:return Fr.OneMinusDst;case 776:return Fr.SrcAlphaSaturated;case 32769:return Fr.Constant;case 32770:return Fr.OneMinusConstant;case 32771:return Fr.Constant;case 32772:return Fr.OneMinusConstant;default:return Fr.One}}static _GetCompareFunction(e){switch(e){case 0:return cr.Never;case 1:return cr.Less;case 2:return cr.Equal;case 3:return cr.LessEqual;case 4:return cr.Greater;case 5:return cr.NotEqual;case 6:return cr.GreaterEqual;case 7:return cr.Always}return cr.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Ka.Zero;case 1:return Ka.Keep;case 2:return Ka.Replace;case 3:return Ka.IncrementClamp;case 4:return Ka.DecrementClamp;case 5:return Ka.Invert;case 6:return Ka.IncrementWrap;case 7:return Ka.DecrementWrap}return Ka.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case P.BYTE:switch(s){case 1:case 2:return i?Ki.Snorm8x2:Ki.Sint8x2;case 3:case 4:return i?Ki.Snorm8x4:Ki.Sint8x4}break;case P.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Ki.Unorm8x2:Ki.Uint8x2;case 3:case 4:return i?Ki.Unorm8x4:Ki.Uint8x4}break;case P.SHORT:switch(s){case 1:case 2:return i?Ki.Snorm16x2:Ki.Sint16x2;case 3:case 4:return i?Ki.Snorm16x4:Ki.Sint16x4}break;case P.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Ki.Unorm16x2:Ki.Uint16x2;case 3:case 4:return i?Ki.Unorm16x4:Ki.Uint16x4}break;case P.INT:switch(s){case 1:return Ki.Sint32;case 2:return Ki.Sint32x2;case 3:return Ki.Sint32x3;case 4:return Ki.Sint32x4}break;case P.UNSIGNED_INT:switch(s){case 1:return Ki.Uint32;case 2:return Ki.Uint32x2;case 3:return Ki.Uint32x3;case 4:return Ki.Uint32x4}break;case P.FLOAT:switch(s){case 1:return Ki.Float32;case 2:return Ki.Float32x2;case 3:return Ki.Float32x3;case 4:return Ki.Float32x4}break}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:Wi._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:Wi._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:Wi._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:Wi._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:Wi._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:Wi._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[ps.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace,s=this._cullEnabled?this._cullFace:0,r=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,o=i-1+(s<<1)+(r<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==o&&(this._rasterizationState=o,this._states[ps.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.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:wm[this._alphaBlendFuncParams[0]])<<0)+((this._alphaBlendFuncParams[1]===null?2:wm[this._alphaBlendFuncParams[1]])<<4)+((this._alphaBlendFuncParams[2]===null?2:wm[this._alphaBlendFuncParams[2]])<<8)+((this._alphaBlendFuncParams[3]===null?2:wm[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[ps.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.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[ps.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ps.DepthStencilState))}_setVertexState(e){var h;const t=this._statesLength;let i=ps.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,l=0;for(let c=0;c0)for(let m=0;m=this._video.HAVE_CURRENT_DATA}dispose(){}}class px{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=px._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],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?Jh.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){var n;let i=this.textures[e],s=-1;i?s=((n=i.texture)==null?void 0:n.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=JP.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==((t==null?void 0:t.uniqueId)??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}px._Counter=0;class _x{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,gi.CopyDst|gi.Indirect|gi.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=_x._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}}_x._Counter=0;class Jf{constructor(){this.values={}}}class _i{static get Statistics(){return{totalCreated:_i.NumBindGroupsCreatedTotal,lastFrameCreated:_i.NumBindGroupsCreatedLastFrame,lookupLastFrame:_i.NumBindGroupsLookupLastFrame,noLookupLastFrame:_i.NumBindGroupsNoLookupLastFrame}}static ResetCache(){_i._Cache=new Jf,_i.NumBindGroupsCreatedTotal=0,_i.NumBindGroupsCreatedLastFrame=0,_i.NumBindGroupsLookupLastFrame=0,_i.NumBindGroupsNoLookupLastFrame=0,_i._NumBindGroupsCreatedCurrentFrame=0,_i._NumBindGroupsLookupCurrentFrame=0,_i._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){_i.NumBindGroupsCreatedLastFrame=_i._NumBindGroupsCreatedCurrentFrame,_i.NumBindGroupsLookupLastFrame=_i._NumBindGroupsLookupCurrentFrame,_i.NumBindGroupsNoLookupLastFrame=_i._NumBindGroupsNoLookupCurrentFrame,_i._NumBindGroupsCreatedCurrentFrame=0,_i._NumBindGroupsLookupCurrentFrame=0,_i._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var l,h,c,u,d,f;let s,r=_i._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return _i._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const m of e.shaderProcessingContext.bufferNames){const _=((l=t.buffers[m])==null?void 0:l.uniqueId)??0;let x=r.values[_];x||(x=new Jf,r.values[_]=x),r=x}for(const m of e.shaderProcessingContext.samplerNames){const _=((h=i.samplers[m])==null?void 0:h.hashCode)??0;let x=r.values[_];x||(x=new Jf,r.values[_]=x),r=x}for(const m of e.shaderProcessingContext.textureNames){const _=((u=(c=i.textures[m])==null?void 0:c.texture)==null?void 0:u.uniqueId)??0;let x=r.values[_];x||(x=new Jf,r.values[_]=x),r=x}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,_i._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),_i.NumBindGroupsCreatedTotal++,_i._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let m=0;mN==="texture"?"":k)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}x[S].resource=this._cacheSampler.getSampler(R,!1,I.hashCode,R.label)}else U.Error(`Sampler "${A}" could not be bound. entry=${JSON.stringify(C)}, materialContext=${JSON.stringify(i,(R,N)=>R==="texture"||R==="sampler"?"":N)}`,50)}else if(C.texture||C.storageTexture){const I=i.textures[A];if(I){if(this._engine.dbgSanityChecks&&I.texture===null){U.Error(`Trying to bind a null texture! entry=${JSON.stringify(C)}, bindingInfo=${JSON.stringify(I,(N,k)=>N==="texture"?"":k)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const R=I.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!R||C.texture&&!R.view||C.storageTexture&&!R.viewForWriting)){U.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(C)}, name=${A}, bindingInfo=${JSON.stringify(I,(N,k)=>N==="texture"?"":k)}, isReady=${(d=I.texture)==null?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}x[S].resource=C.storageTexture?R.viewForWriting:R.view}else U.Error(`Texture "${A}" could not be bound. entry=${JSON.stringify(C)}, materialContext=${JSON.stringify(i,(R,N)=>R==="texture"||R==="sampler"?"":N)}`,50)}else if(C.externalTexture){const I=i.textures[A];if(I){if(this._engine.dbgSanityChecks&&I.texture===null){U.Error(`Trying to bind a null external texture! entry=${JSON.stringify(C)}, name=${A}, bindingInfo=${JSON.stringify(I,(N,k)=>N==="texture"?"":k)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const R=I.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!R){U.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(C)}, name=${A}, bindingInfo=${JSON.stringify(I,(N,k)=>N==="texture"?"":k)}, isReady=${(f=I.texture)==null?void 0:f.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}x[S].resource=this._device.importExternalTexture({source:R})}else U.Error(`Texture "${A}" could not be bound. entry=${JSON.stringify(C)}, materialContext=${JSON.stringify(i,(R,N)=>R==="texture"||R==="sampler"?"":N)}`,50)}else if(C.buffer){const I=t.buffers[A];if(I){const R=I.underlyingResource;x[S].resource.buffer=R,x[S].resource.size=I.capacity}else U.Error(`Can't find buffer "${A}". entry=${JSON.stringify(C)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const E=o[m];s[m]=this._device.createBindGroup({layout:E,entries:x})}return s}}_i.NumBindGroupsCreatedTotal=0;_i.NumBindGroupsCreatedLastFrame=0;_i.NumBindGroupsLookupLastFrame=0;_i.NumBindGroupsNoLookupLastFrame=0;_i._Cache=new Jf;_i._NumBindGroupsCreatedCurrentFrame=0;_i._NumBindGroupsLookupCurrentFrame=0;_i._NumBindGroupsNoLookupCurrentFrame=0;const IW="clearQuadVertexShader",PW=`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 +} +`;j.ShadersStoreWGSL[IW]=PW;const MW="clearQuadPixelShader",OW=`uniform color: vec4f;@fragment +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;} +`;j.ShadersStoreWGSL[MW]=OW;class DW{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 Za(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,vt.WGSL)}clear(e,t,i,s,r=1){let n,o=null,l;const h=!!this._engine._currentRenderTarget;if(e)n=e;else{let x=0;this._keyTemp.length=0;for(let S=0;S1?2**36:0)+E*2**37,l=this._keyTemp.join("_"),o=this._bundleCache[l],o)return o;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Zt.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Zt.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const d=h?this._engine._ubInvertY:this._engine._ubDontInvertY,f=u.uniformBuffer.getBuffer(),m=f.uniqueId+"-"+d.uniqueId;let _=this._bindGroups[m];if(!_){const x=u.bindGroupLayouts[0];_=this._bindGroups[m]=[],_.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${m}`,layout:x[0],entries:[]})),Yn._SimplifiedKnownBindings||_.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${m}`,layout:x[1],entries:[]})),_.push(this._device.createBindGroup({label:`clearQuadBindGroup${Yn._SimplifiedKnownBindings?1:2}-${m}`,layout:x[Yn._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:d.underlyingResource,size:d.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}n.setPipeline(c);for(let x=0;x<_.length;++x)n.setBindGroup(x,_[x]);return n.draw(4,1,0,0),e||(o=n.finish(),this._bundleCache[l]=o),o}}class jv{constructor(e,t,i,s){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(s)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new jv(this.x,this.y,this.w,this.h)}}class qv{constructor(e,t,i,s){this.x=e,this.y=t,this.w=i,this.h=s}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new qv(this.x,this.y,this.w,this.h)}}class vg{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new vg(this.ref)}}class Qv{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new Qv(this.color)}}class Zv{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new Zv(this.query)}}class Jv{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new Jv}}class eC{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){const e=new eC;return e.bundles=this.bundles,e}}class tC{constructor(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){const t=new eC;this._list[this._listLength++]=t,this._currentBundleList=t.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:Zt.GetSample(i)})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t{const r=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,r},r=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw r})}async readValue(e=0){const t=this._getBuffer(e,1);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(ac.Read).then(()=>{const s=new BigUint64Array(t.getMappedRange()),r=Number(s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(t===null)return null;const i=this._engine.uniqueId;return t.mapAsync(ac.Read).then(()=>{const s=new BigUint64Array(t.getMappedRange()),r=Number(s[1]-s[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r},s=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw s})}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(s=>{t._addDuration(i,s!==null&&s>0?s:0)})}dispose(){var e;(e=this._measureDuration)==null||e.dispose()}}class wW{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new eM(e,s,Tg.Timestamp,t,i,!0,r)}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 FW{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,s=50,r=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=r,this._allocateNewIndices(s)}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 kn{async initTwgsl(e){if(!kn._Twgsl)return e=e||{},e={...kn._TWgslDefaultOptions,...e},e.twgsl?(kn._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Z.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(kn._Twgsl=await self.twgsl(Z.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=kn._Twgsl.convertSpirV2WGSL(e,kn.DisableUniformityAnalysis||t);return kn.ShowWGSLShaderCode&&(U.Log(i),U.Log("***********************************************")),kn.DisableUniformityAnalysis||t?`diagnostic(off, derivative_uniformity); +`+i:i}}kn._TWgslDefaultOptions={jsPath:`${Z._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Z._DefaultCdnUrl}/twgsl/twgsl.wasm`};kn.ShowWGSLShaderCode=!1;kn.DisableUniformityAnalysis=!1;kn._Twgsl=null;class LW{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}}const BW="postprocessVertexShader",UW=`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 +} +`;j.ShadersStoreWGSL[BW]=UW;const A0={label:"TextureView_SwapChain_ResolveTarget",dimension:Ba.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},R0={label:"TextureView_SwapChain",dimension:Ba.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Fm="/* disable_uniformity_analysis */",VW=new Oe;class pt extends He{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 eP(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return U.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 Uv:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new pt(e,t);return new Promise(s=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>s(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._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._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 QI,this._name="WebGPU",this._drawCalls=new Xn,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,U.Log(`Babylon.js v${ee.Version} - ${this.description} engine`),!navigator.gpu){U.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 C4,this._shaderProcessorWGSL=new hW}initAsync(e,t){var i;return this.uniqueId=pt._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??((i=this._options)==null?void 0:i.glslangOptions)).then(s=>{var r;return this._glslang=s,this._tintWASM=pt.UseTWGSL?new kn:null,this._tintWASM?this._tintWASM.initTwgsl(t??((r=this._options)==null?void 0:r.twgslOptions)).then(()=>navigator.gpu.requestAdapter(this._options)):navigator.gpu.requestAdapter(this._options)}).then(s=>{var r;if(s){this._adapter=s,this._adapterSupportedExtensions=[],(r=this._adapter.features)==null||r.forEach(l=>this._adapterSupportedExtensions.push(l)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(l=>{this._adapterInfo=l});const n=this._options.deviceDescriptor??{},o=(n==null?void 0:n.requiredFeatures)??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(o){const l=o,h=[];for(const c of l)this._adapterSupportedExtensions.indexOf(c)!==-1&&h.push(c);n.requiredFeatures=h}if(this._options.setMaximumLimits&&!n.requiredLimits){n.requiredLimits={};for(const l in this._adapterSupportedLimits)l==="minSubgroupSize"||l==="maxSubgroupSize"||(n.requiredLimits[l]=this._adapterSupportedLimits[l])}return n.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(n)}else throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(s=>{var n,o;this._device=s,this._deviceEnabledExtensions=[],(n=this._device.features)==null||n.forEach(l=>this._deviceEnabledExtensions.push(l)),this._deviceLimits=s.limits;let r=-1;this._device.addEventListener("uncapturederror",l=>{++r{this._isDisposed||(this._contextWasLost=!0,U.Warn("WebGPU context lost. "+l),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var _,x;const h=this.snapshotRenderingMode,c=this.snapshotRendering,u=this.disableCacheSamplers,d=this.disableCacheRenderPipelines,f=this.disableCacheBindGroups,m=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??((_=this._options)==null?void 0:_.glslangOptions),this._twgslOptions??((x=this._options)==null?void 0:x.twgslOptions)),this.snapshotRenderingMode=h,this.snapshotRendering=c,this.disableCacheSamplers=u,this.disableCacheRenderPipelines=d,this.disableCacheBindGroups=f,this.enableGPUTimingMeasurements=m,this._currentRenderPass=null}))})}).then(()=>{this._bufferManager=new Sg(this,this._device),this._textureHelper=new EW(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Jh(this._device),this._cacheBindGroups=new _i(this._device,this._cacheSampler,this),this._timestampQuery=new NW(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new FW(this,this._device,this._bufferManager):void 0,this._bundleList=new tC(this._device),this._snapshotRendering=new LW(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),gi.Uniform|gi.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),gi.Uniform|gi.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&this._count===void 0&&(this._count=0,U.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new P(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Za(this._device,this._emptyVertexBuffer),this._depthCullingState=new RW(this._cacheRenderPipeline),this._stencilStateComposer=new AW(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 DW(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(s=>{throw U.Error("A fatal error occurred during WebGPU creation/initialization."),s})}_initGlslang(e){return e=e||{},e={...pt._GLSLslangDefaultOptions,...e},e.glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Z.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(Z.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(Ro.TextureCompressionASTC)>=0?!0:void 0,s3tc:this._deviceEnabledExtensions.indexOf(Ro.TextureCompressionBC)>=0?!0:void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Ro.TextureCompressionETC2)>=0?!0:void 0,bptc:this._deviceEnabledExtensions.indexOf(Ro.TextureCompressionBC)>=0?!0:void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(Ro.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Ro.Float32Filterable)>=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(Ro.TimestampQuery)!==-1?!0:void 0,supportOcclusionQuery:typeof BigUint64Array<"u",canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_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 Jm],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 r={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ba.E2d,format:this._options.swapChainFormat,usage:zi.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(r),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:Ba.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Oe(0,0,0,1),loadOp:Fs.Clear,storeOp:na.Store}]}else t=[{view:void 0,clearValue:new Oe(0,0,0,1),loadOp:Fs.Clear,storeOp:na.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?V.Depth24PlusStencil8:V.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:Ba.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:zi.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:Ba.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Fs.Clear,depthStoreOp:na.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Fs.Clear:void 0,stencilStoreOp:this.isStencilEnable?na.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),ZI(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:zi.RenderAttachment|zi.CopySrc,alphaMode:this.premultipliedAlpha?Eg.Premultiplied:Eg.Opaque})}resizeImageBitmap(e,t,i){return iP(this,e,t,i)}_createImageBitmapFromSource(e,t){return tP(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&sP(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&rP()}enterPointerlock(){this._renderingCanvas&&fv(this._renderingCanvas)}exitPointerlock(){nP()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Za.ResetCache(),_i.ResetCache();const t=s=>{var r;for(const n of s){for(const o of n.meshes){const l=o.subMeshes;if(l)for(const h of l)h._drawWrappers=[]}for(const o of n.materials)(r=o._materialContext)==null||r.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const s of this._uniformBuffers)s.name.indexOf("leftOver")<0&&i.push(s);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setDepthStencilTexture(e,t,i,s){e!==void 0&&(!i||!i.depthStencilTexture?this._setTexture(e,null,void 0,void 0,s):this._setTexture(e,i,!1,!0,s))}setTextureFromPostProcess(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,(s==null?void 0:s.texture)??null,i)}setTextureFromPostProcessOutput(e,t,i){var s;this._bindTexture(e,((s=t==null?void 0:t._outputTexture)==null?void 0:s.texture)??null,i)}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,r=t.indexOf(Fm)>=0,n=i===vt.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===vt.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf(Fm)>=0,n=t.indexOf(Fm)>=0,o=`#version 450 +`,l=s===vt.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),h=s===vt.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(l,h,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),c}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new nc(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new E4(e,this)}createMaterialContext(){return new px}createDrawContext(){return new _x(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,l){const h=e,c=h.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(U.Log(["defines",l]),U.Log(t),U.Log(i),U.Log("***********************************************")),h.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},s?h.stages=this._compileRawPipelineStageDescriptor(t,i,c):h.stages=this._compilePipelineStageDescriptor(t,i,l,c)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let r=0;r0,n.is3D=h>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,l,c||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,l=null,h=null,c=null,u=null,d,f,m,_){return this._createTextureBase(e,t,i,s,r,n,o,(x,E,S,C,y,A,I,R)=>{var k;const N=C;if(x.baseWidth=N.width,x.baseHeight=N.height,x.width=N.width,x.height=N.height,x.format=x.format!==-1?x.format:c??5,x.type=x.type!==-1?x.type:0,x._creationFlags=m??0,R(x.width,x.height,N,E,x,()=>{}),(k=x._hardwareTexture)!=null&&k.underlyingResource)!A&&!I&&this._generateMipmaps(x,this._uploadEncoder);else{const B=this._textureHelper.createGPUTextureForInternalTexture(x,N.width,N.height,void 0,m);Zt.IsImageBitmap(N)&&(this._textureHelper.updateTexture(N,x,N.width,N.height,x.depth,B.format,0,0,y,!1,0,0),!A&&!I&&this._generateMipmaps(x,this._uploadEncoder))}S&&S.removePendingData(x),x.isReady=!0,x.onLoadedObservable.notifyObservers(x),x.onLoadedObservable.clear()},()=>!1,l,h,c,u,d,f,_)}wrapWebGPUTexture(e){const t=new Jm(e),i=new $t(this,xt.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;e.generateMipMaps&&((t=e._hardwareTexture)!=null&&t.underlyingResource||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))}_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,s=null){t!==null&&(e._cachedWrapU=t),i!==null&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&s!==null&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){const n=i+Xi.AutoSamplerSuffix;this._currentMaterialContext.setSampler(n,t)}}}createPrefilteredCubeTexture(e,t,i,s,r=null,n=null,o,l=null,h=!0){const c=u=>{if(!u){r&&r(null);return}const d=u.texture;h?u.info.sphericalPolynomial&&(d._sphericalPolynomial=u.info.sphericalPolynomial):d._sphericalPolynomial=new zo,d._source=xt.CubePrefiltered,r&&r(d)};return this.createCubeTexture(e,t,null,!1,c,n,o,l,h,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let r=0;r0;for(const r in e){const n=e[r],o=i[r],l=o.group,h=o.binding,c=n.type,u=n.object;let d=n.indexInGroupEntries,f=this._bindGroupEntries[l];switch(f||(f=this._bindGroupEntries[l]=[]),c){case Si.Sampler:{const m=u;d!==void 0&&s?f[d].resource=this._cacheSampler.getSampler(m):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._cacheSampler.getSampler(m)}));break}case Si.Texture:case Si.TextureWithoutSampler:{const m=u,_=m._texture._hardwareTexture;d!==void 0&&s?(c===Si.Texture&&(f[d++].resource=this._cacheSampler.getSampler(m._texture)),f[d].resource=_.view):(n.indexInGroupEntries=f.length,c===Si.Texture&&f.push({binding:h-1,resource:this._cacheSampler.getSampler(m._texture)}),f.push({binding:h,resource:_.view}));break}case Si.StorageTexture:{const m=u,_=m._texture._hardwareTexture;_.textureAdditionalUsages&zi.StorageBinding||U.Error(`computeDispatch: The texture (name=${m.name}, uniqueId=${m.uniqueId}) is not a storage texture!`,50),d!==void 0&&s?f[d].resource=_.viewForWriting:(n.indexInGroupEntries=f.length,f.push({binding:h,resource:_.viewForWriting}));break}case Si.ExternalTexture:{const _=u.underlyingResource;d!==void 0&&s?f[d].resource=this._device.importExternalTexture({source:_}):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:this._device.importExternalTexture({source:_})}));break}case Si.UniformBuffer:case Si.StorageBuffer:case Si.DataBuffer:{const m=c===Si.DataBuffer?u:(c===Si.UniformBuffer,u.getBuffer()),_=m.underlyingResource;d!==void 0&&s?(f[d].resource.buffer=_,f[d].resource.size=m.capacity):(n.indexInGroupEntries=f.length,f.push({binding:h,resource:{buffer:_,offset:0,size:m.capacity}}));break}}}for(let r=0;r0&&d.dispatchWorkgroups(i,s,r),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)};pt.prototype.releaseComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a].getPipelineContext();this._deleteComputePipelineContext(e)}this._compiledComputeEffects={}};pt.prototype._prepareComputePipelineContext=function(a,e,t,i,s){const r=a;this.dbgShowShaderCode&&(U.Log(i),U.Log(e)),r.sources={compute:e,rawCompute:t},r.stage=this._createComputePipelineStageDescriptor(e,i,s)};pt.prototype._releaseComputeEffect=function(a){this._compiledComputeEffects[a._key]&&(delete this._compiledComputeEffects[a._key],this._deleteComputePipelineContext(a.getPipelineContext()))};pt.prototype._rebuildComputeEffects=function(){for(const a in this._compiledComputeEffects){const e=this._compiledComputeEffects[a];e._pipelineContext=null,e._wasPreviouslyReady=!1,e._prepareEffect()}};pt.prototype._executeWhenComputeStateIsCompiled=function(a,e){a.stage.module.getCompilationInfo().then(t=>{const i={numErrors:0,messages:[]};for(const s of t.messages)s.type==="error"&&i.numErrors++,i.messages.push({type:s.type,text:s.message,line:s.lineNum,column:s.linePos,length:s.length,offset:s.offset});e(i)})};pt.prototype._deleteComputePipelineContext=function(a){a&&a.dispose()};pt.prototype._createComputePipelineStageDescriptor=function(a,e,t){return e?e="//"+e.split(` +`).join(` +//`)+` +`:e="",{module:this._device.createShaderModule({code:e+a}),entryPoint:t}};pt.prototype._createDepthStencilCubeTexture=function(a,e){const t=new $t(this,e.generateStencil?xt.DepthStencil:xt.Depth);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,a,i.generateStencil,i.bilinearFiltering,i.comparisonFunction,i.samples),this._textureHelper.createGPUTextureForInternalTexture(t);const s=t._hardwareTexture;return t.type=Zt.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(t),t};pt.prototype.createCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(a,e,t,!!i,s,r,n,o,l,h,c,u,null,(f,m)=>{const _=m,x=_[0].width,E=x;this._setCubeMapTextureParams(f,!i),f.format=n??-1;const S=this._textureHelper.createGPUTextureForInternalTexture(f,x,E);this._textureHelper.updateCubeTextures(_,S.underlyingResource,x,E,S.format,!1,!1,0,0),i||this._generateMipmaps(f,this._uploadEncoder),f.isReady=!0,f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),s&&s()},!!d)};pt.prototype._setCubeMapTextureParams=function(a,e,t){a.samplingMode=e?3:2,a._cachedWrapU=0,a._cachedWrapV=0,t&&(a._maxLodLevel=t)};pt.prototype._debugPushGroup=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.pushDebugGroup(a):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(a):this._pendingDebugCommands.push(["push",a]))};pt.prototype._debugPopGroup=function(a){this._options.enableGPUDebugMarkers&&(a===0||a===1?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))};pt.prototype._debugInsertMarker=function(a,e){this._options.enableGPUDebugMarkers&&(e===0||e===1?this._renderEncoder.insertDebugMarker(a):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(a):this._pendingDebugCommands.push(["insert",a]))};pt.prototype._debugFlushPendingCommands=function(){for(let a=0;a{e==null||e.removePendingData(d),h&&_&&h(_.status+" "+_.statusText,x)},m=_=>{const x=d.width,E=n(_);if(E){if(o){const S=i===4,C=o(E),y=d._hardwareTexture,A=[0,1,2,3,4,5];for(let I=0;I>I,N=[];for(let k=0;k<6;k++){let B=C[I][A[k]];S&&(B=f_(B,R,R,s)),N.push(new Uint8Array(B.buffer,B.byteOffset,B.byteLength))}this._textureHelper.updateCubeTextures(N,y.underlyingResource,R,R,y.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,E,i,s,u);d.isReady=!0,e==null||e.removePendingData(d),l&&l()}};return this._loadFile(a,_=>{m(_)},void 0,e==null?void 0:e.offlineProvider,!0,f),d};pt.prototype.createRawTexture3D=function(a,e,t,i,s,r,n,o,l=null,h=0,c=0){const u=xt.Raw3D,d=new $t(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=o,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,void 0,c),this.updateRawTexture3D(d,a,s,n,l,h),this._internalTexturesCache.push(d),d};pt.prototype.updateRawTexture3D=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=f_(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};pt.prototype.createRawTexture2DArray=function(a,e,t,i,s,r,n,o,l=null,h=0,c=0){const u=xt.Raw2DArray,d=new $t(this,u);return d.baseWidth=e,d.baseHeight=t,d.baseDepth=i,d.width=e,d.height=t,d.depth=i,d.format=s,d.type=h,d.generateMipMaps=r,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=a),this._textureHelper.createGPUTextureForInternalTexture(d,e,t,i,c),this.updateRawTexture2DArray(d,a,s,n,l,h),this._internalTexturesCache.push(d),d};pt.prototype.updateRawTexture2DArray=function(a,e,t,i,s=null,r=0){if(this._doNotHandleContextLost||(a._bufferView=e,a.format=t,a.invertY=i,a._compression=s),e){const n=a._hardwareTexture;t===4&&(e=f_(e,a.width,a.height,r));const l=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this._textureHelper.updateTexture(l,a,a.width,a.height,a.depth,n.format,0,0,i,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a,this._uploadEncoder)}a.isReady=!0};function f_(a,e,t,i){let s,r=1;i===1?s=new Float32Array(e*t*4):i===2?(s=new Uint16Array(e*t*4),r=15360):i===7?s=new Uint32Array(e*t*4):s=new Uint8Array(e*t*4);for(let n=0;n0,a.is3D=h>0,a.depth=l||h,a.isReady=!0,a.samples=r,a.generateMipMaps=!1,a.samplingMode=i?2:1,a.type=1,a._comparisonFunction=s,a._cachedWrapU=0,a._cachedWrapV=0};pt.prototype.updateRenderTargetTextureSampleCount=function(a,e){return!a||!a.texture||a.samples===e||(e=Math.min(e,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(a.texture,e),a._depthStencilTexture&&(this._textureHelper.createMSAATexture(a._depthStencilTexture,e),a._depthStencilTexture.samples=e),a._samples=e,a.texture.samples=e),e};pt.prototype.createRenderTargetCubeTexture=function(a,e){const t=this._createHardwareRenderTargetWrapper(!1,!0,a),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 s=new $t(this,xt.RenderTarget);return s.width=a,s.height=a,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=i.samples,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),(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&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),e&&e.createMipMaps&&!i.generateMipMaps&&(s.generateMipMaps=!1),t};ri.prototype.setTextureSampler=function(a,e){this._engine.setTextureSampler(a,e)};pt.prototype.setTextureSampler=function(a,e){var t;(t=this._currentMaterialContext)==null||t.setSampler(a,e)};ri.prototype.setStorageBuffer=function(a,e){this._engine.setStorageBuffer(a,e)};pt.prototype.createStorageBuffer=function(a,e,t){return this._createBuffer(a,e|32,t)};pt.prototype.updateStorageBuffer=function(a,e,t,i){const s=a;t===void 0&&(t=0);let r;i===void 0?(e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,i=r.byteLength):e instanceof Array?r=new Float32Array(e):e instanceof ArrayBuffer?r=new Uint8Array(e):r=e,this._bufferManager.setSubData(s,t,r,0,i)};pt.prototype.readFromStorageBuffer=function(a,e,t,i,s){t=t||a.capacity;const r=this._bufferManager.createRawBuffer(t,gi.MapRead|gi.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(a.underlyingResource,e??0,r,0,t),new Promise((n,o)=>{const l=()=>{r.mapAsync(ac.Read,0,t).then(()=>{const h=r.getMappedRange(0,t);let c=i;if(c===void 0)c=new Uint8Array(t),c.set(new Uint8Array(h));else{const u=c.constructor;c=new u(c.buffer),c.set(new u(h))}r.unmap(),this._bufferManager.releaseBuffer(r),n(c)},h=>{this.isDisposed?n(new Uint8Array):o(h)})};s?(this.flushFramebuffer(),l()):this.onEndFrameObservable.addOnce(()=>{l()})})};pt.prototype.setStorageBuffer=function(a,e){var t;(t=this._currentDrawContext)==null||t.setBuffer(a,(e==null?void 0:e.getBuffer())??null)};function WW(a){return!!(a&&a.underlyingResource!==void 0)}pt.prototype.updateVideoTexture=function(a,e,t){var s;if(!a||a._isDisabled)return;this._videoTextureSupported===void 0&&(this._videoTextureSupported=!0);let i=a._hardwareTexture;(s=a._hardwareTexture)!=null&&s.underlyingResource||(i=this._textureHelper.createGPUTextureForInternalTexture(a)),WW(e)?(this._textureHelper.copyVideoToTexture(e,a,i.format,!t),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0):e&&this.createImageBitmap(e).then(r=>{this._textureHelper.updateTexture(r,a,a.width,a.height,a.depth,i.format,0,0,!t,!1,0,0),a.generateMipMaps&&this._generateMipmaps(a),a.isReady=!0}).catch(()=>{a.isReady=!0})};class Tc extends yt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=L.Identity(),this._projectionMatrix=L.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=T.Zero()),T.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=T.Zero()),T.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=T.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=T.Cross(this.direction,Vr.Y),t=T.Cross(e,this.direction);return T.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=T.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=L.Identity()),L.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=W.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),T.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(T.Dot(t,T.Up()))===1&&(t.z=1e-13);const s=W.Vector3[1];return i.addToRef(t,s),L.LookAtLHToRef(i,s,T.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}v([Sr()],Tc.prototype,"position",null);v([Sr()],Tc.prototype,"direction",null);v([O()],Tc.prototype,"shadowMinZ",null);v([O()],Tc.prototype,"shadowMaxZ",null);Qt.AddNodeConstructor("Light_Type_1",(a,e)=>()=>new ga(a,T.Zero(),e));class ga extends Tc{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 yt.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&&L.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 s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const c=T.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let u=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let f=0;fthis._orthoRight&&(this._orthoRight=c.x),c.y>this._orthoTop&&(this._orthoTop=c.y),this.autoCalcShadowZBounds&&(c.zd&&(d=c.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=u,this._shadowMaxZ=d)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;L.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?l:o,h?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([O()],ga.prototype,"shadowFrustumSize",null);v([O()],ga.prototype,"shadowOrthoScale",null);v([O()],ga.prototype,"autoUpdateExtends",void 0);v([O()],ga.prototype,"autoCalcShadowZBounds",void 0);v([O("orthoLeft")],ga.prototype,"_orthoLeft",void 0);v([O("orthoRight")],ga.prototype,"_orthoRight",void 0);v([O("orthoTop")],ga.prototype,"_orthoTop",void 0);v([O("orthoBottom")],ga.prototype,"_orthoBottom",void 0);function HW(a,e={},t){e.diameter||(e.diameter=1),e.segments||(e.segments=16);const i=Go("",{slice:.5,diameter:e.diameter,segments:e.segments},t),s=FP("",{radius:e.diameter/2,tessellation:e.segments*3+(4-e.segments)},t);s.rotation.x=-Math.PI/2,s.parent=i;const r=q.MergeMeshes([s,i],!0);return r.name=a,r}q.CreateHemisphere=(a,e,t,i)=>HW(a,{segments:e,diameter:t},i);Qt.AddNodeConstructor("Light_Type_2",(a,e)=>()=>new Cn(a,T.Zero(),T.Zero(),0,0,e));class Cn extends Tc{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()&&(Cn._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):Cn._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,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=L.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=T.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=T.Zero(),this._projectionTextureViewLightMatrix=L.Zero(),this._projectionTextureProjectionLightMatrix=L.Zero(),this._projectionTextureScalingMatrix=L.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=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return yt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;L.PerspectiveFovLHToRef(r,1,l?o:n,l?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),L.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),s=-i*t,r=1/Math.tan(this._angle/2);L.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof X){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;L.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("projectionLightSampler"+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=T.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=T.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=T.Normalize(this.transformedDirection):i=T.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([O()],Cn.prototype,"angle",null);v([O()],Cn.prototype,"innerAngle",null);v([O()],Cn.prototype,"shadowAngleScale",null);v([O()],Cn.prototype,"exponent",void 0);v([O()],Cn.prototype,"projectionTextureLightNear",null);v([O()],Cn.prototype,"projectionTextureLightFar",null);v([O()],Cn.prototype,"projectionTextureUpDirection",null);v([Dt("projectedLightTexture")],Cn.prototype,"_projectionTexture",void 0);const XW="kernelBlurVaryingDeclaration",YW="varying vec2 sampleCoord{X};";j.IncludesShadersStore[XW]=YW;const $W="packingFunctions",KW=`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);}`;j.IncludesShadersStore[$W]=KW;const jW="kernelBlurFragment",qW=`#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 +`;j.IncludesShadersStore[jW]=qW;const QW="kernelBlurFragment2",ZW=`#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 +`;j.IncludesShadersStore[QW]=ZW;const JW="kernelBlurPixelShader",eH=`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 +}`;j.ShadersStore[JW]=eH;const tH="kernelBlurVertex",iH="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";j.IncludesShadersStore[tH]=iH;const sH="kernelBlurVertexShader",rH=`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 +}`;j.ShadersStore[sH]=rH;class Hs extends je{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=X.BILINEAR_SAMPLINGMODE,o,l,h=0,c="",u=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,l,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=c,this.direction=t,this.onApplyObservable.add(f=>{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}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let x=0;x0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,s=-(e*e/(2*t*t));return 1/i*Math.exp(s)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return Pe.Parse(()=>new Hs(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,s)}}v([O("kernel")],Hs.prototype,"_kernel",void 0);v([O("packedFloat")],Hs.prototype,"_packedFloat",void 0);v([ev()],Hs.prototype,"direction",void 0);H("BABYLON.BlurPostProcess",Hs);class gx extends Yi{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,s,r=0,n=X.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new nn(0,1,0,1),this._transformMatrix=L.Zero(),this._mirrorMatrix=L.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 c;(c=l._debugPushGroup)==null||c.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var c;(c=l._debugPopGroup)==null||c.call(l,1)});let h;this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),L.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),h=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=T.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=h})}_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 Hs("horizontal blur",new ce(1,0),this._blurKernelX,this._blurRatio,null,X.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 Hs("vertical blur",new ce(0,1),this._blurKernelY,this._blurRatio,null,X.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 gx(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()}}X._CreateMirror=(a,e,t,i)=>new gx(a,e,t,i);class Ms extends Kt{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(L.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach(r=>s+=r),new Ms(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new Ms(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,l=5,h=!1,c=null,u=!1,d=.8,f=0,m,_){var x;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new K,this.boundingBoxPosition=T.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new L,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=l,this.isCube=!0,this._textureMatrix=L.Identity(),this._createPolynomials=u,this.coordinatesMode=X.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=c,this._loaderOptions=m,this._useSRGBBuffer=_,this._lodScale=d,this._lodOffset=f,!(!e&&!r)&&this.updateURL(e,c,n,h,o,i,(x=this.getScene())==null?void 0:x.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,l=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);const h=e.lastIndexOf("."),c=t||(h>-1?e.substring(h).toLowerCase():""),u=c.indexOf(".dds")===0,d=c.indexOf(".env")===0,f=c.indexOf(".basis")===0;if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),l)this._files=l;else if(!f&&!d&&!u&&!n&&(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let m=0;mo.getActiveTextures().indexOf(this)!==-1)),this._textureMatrix=e,!((n=this.getScene())!=null&&n.useRightHandedSystem)))return;const t=W.Vector3[0],i=W.Quaternion[0],s=W.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,L.ComposeToRef(t,i,s,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(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{var l;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),(l=this.getScene())==null||l.markAllMaterialsAsDirty(1)),e&&e()},n=(l,h)=>{this._loadingError=!0,this._errorObject={message:l,exception:h},t&&t(l,h),X.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Z.SetImmediate(()=>r()):this._texture.onLoadedObservable.add(()=>r()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),(o=this._texture)==null||o.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){const s=Pe.Parse(()=>{let r=!1;return e.prefiltered&&(r=e.prefiltered),new Ms(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.FromArray(e.boundingBoxSize)),e.animations)for(let r=0;r{const i=new Ms(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=i.uniqueId,i},this);return t.uniqueId=e,t}}v([O()],Ms.prototype,"url",void 0);v([Sr()],Ms.prototype,"boundingBoxPosition",void 0);v([Sr()],Ms.prototype,"boundingBoxSize",null);v([O("rotationY")],Ms.prototype,"rotationY",null);v([O("files")],Ms.prototype,"_files",void 0);v([O("forcedExtension")],Ms.prototype,"_forcedExtension",void 0);v([O("extensions")],Ms.prototype,"_extensions",void 0);v([iv("textureMatrix")],Ms.prototype,"_textureMatrix",void 0);v([iv("textureMatrixRefraction")],Ms.prototype,"_textureMatrixRefraction",void 0);X._CubeTextureParser=Ms.Parse;H("BABYLON.CubeTexture",Ms);const nH="backgroundFragmentDeclaration",aH=`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 +`;j.IncludesShadersStore[nH]=aH;const oH="backgroundUboDeclaration",lH=`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 +`;j.IncludesShadersStore[oH]=lH;const hH="backgroundPixelShader",cH=`#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 +} +`;j.ShadersStore[hH]=cH;const uH="backgroundVertexDeclaration",dH=`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 +`;j.IncludesShadersStore[uH]=dH;const fH="backgroundVertexShader",pH=`precision highp float; +#include<__decl__backgroundVertex> +#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 +} +`;j.ShadersStore[fH]=pH;class _H extends Gr{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 Ot extends cf{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=Ot.StandardReflectance0*t,this.reflectionReflectance90=Ot.StandardReflectance90*t):(t=t*2-1,this.reflectionReflectance0=Ot.StandardReflectance0+(1-Ot.StandardReflectance0)*t,this.reflectionReflectance90=Ot.StandardReflectance90+(1-Ot.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){super(e,t),this.primaryColor=re.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=T.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 Ps(16),this._reflectionControls=tt.Zero(),this._white=re.White(),this._primaryShadowColor=re.Black(),this._primaryHighlightColor=re.Black(),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 s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new _H);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(c_(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,Yg(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Ce.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Oi(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const l=this._reflectionTexture;if(l&&Ce.ReflectionTextureEnabled){if(!l.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=l.gammaSpace,n.RGBDREFLECTION=l.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=l.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,l.coordinatesMode===X.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=l.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!l.invertZ:l.invertZ,l.coordinatesMode){case X.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case X.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case X.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case X.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case X.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case X.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case X.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case X.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case X.CUBIC_MODE:case X.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0;break}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.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):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(this._primaryColorShadowLevel!==0||this._primaryColorHighlightLevel!==0),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),Wg(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Hg(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),Xg(e,n,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),U.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const l=new gc;n.FOG&&l.addFallback(0,"FOG"),n.POINTSIZE&&l.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&l.addFallback(0,"MULTIVIEW"),xv(n,l,this._maxSimultaneousLights);const h=[P.PositionKind];n.NORMAL&&h.push(P.NormalKind),n.UV1&&h.push(P.UVKind),n.UV2&&h.push(P.UV2Kind),gv(h,e,n,l),zg(h,n);const c=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Va(c);const u=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];Mt&&(Mt.PrepareUniforms(c,n),Mt.PrepareSamplers(u,n)),$g({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const f=n.toString(),m=r.getEngine().createEffect("background",{attributes:h,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(m,n,this._materialContext),this.buildUniformLayout()}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._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 s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),l_(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const l=this._reflectionTexture;(!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync||i._drawWrapper._forceRebindOnNextCall)&&(s.texturesEnabled&&(this._diffuseTexture&&Ce.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),wi(this._diffuseTexture,this._uniformBuffer,"diffuse")),l&&Ce.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),r.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),s.texturesEnabled&&(this._diffuseTexture&&Ce.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),l&&Ce.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",l):r.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),r.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))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),pa(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&h_(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),mc(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&Ch(r,n,s),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 Pe.Clone(()=>new Ot(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Pe.Parse(()=>new Ot(e.name,t),e,t,i)}}Ot.StandardReflectance0=.05;Ot.StandardReflectance90=.5;v([Vi()],Ot.prototype,"_primaryColor",void 0);v([_e("_markAllSubMeshesAsLightsDirty")],Ot.prototype,"primaryColor",void 0);v([Vi()],Ot.prototype,"__perceptualColor",void 0);v([O()],Ot.prototype,"_primaryColorShadowLevel",void 0);v([O()],Ot.prototype,"_primaryColorHighlightLevel",void 0);v([_e("_markAllSubMeshesAsLightsDirty")],Ot.prototype,"primaryColorHighlightLevel",null);v([Dt()],Ot.prototype,"_reflectionTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionTexture",void 0);v([O()],Ot.prototype,"_reflectionBlur",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionBlur",void 0);v([Dt()],Ot.prototype,"_diffuseTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"diffuseTexture",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"shadowLights",void 0);v([O()],Ot.prototype,"_shadowLevel",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"shadowLevel",void 0);v([Sr()],Ot.prototype,"_sceneCenter",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"sceneCenter",void 0);v([O()],Ot.prototype,"_opacityFresnel",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"opacityFresnel",void 0);v([O()],Ot.prototype,"_reflectionFresnel",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionFresnel",void 0);v([O()],Ot.prototype,"_reflectionFalloffDistance",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionFalloffDistance",void 0);v([O()],Ot.prototype,"_reflectionAmount",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionAmount",void 0);v([O()],Ot.prototype,"_reflectionReflectance0",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionReflectance0",void 0);v([O()],Ot.prototype,"_reflectionReflectance90",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"reflectionReflectance90",void 0);v([O()],Ot.prototype,"_useRGBColor",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"useRGBColor",void 0);v([O()],Ot.prototype,"_enableNoise",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"enableNoise",void 0);v([O()],Ot.prototype,"_maxSimultaneousLights",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Ot.prototype,"maxSimultaneousLights",void 0);v([O()],Ot.prototype,"_shadowOnly",void 0);v([_e("_markAllSubMeshesAsLightsDirty")],Ot.prototype,"shadowOnly",void 0);v([dI()],Ot.prototype,"_imageProcessingConfiguration",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Ot.prototype,"enableGroundProjection",void 0);v([O()],Ot.prototype,"projectedGroundRadius",void 0);v([O()],Ot.prototype,"projectedGroundHeight",void 0);H("BABYLON.BackgroundMaterial",Ot);class dc{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new re(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new re(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:T.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,s)=>{this.onErrorObservable.notifyObservers({message:i,exception:s})},this._options={...dc._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new K,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 Oe(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 Kt){this._scene.environmentTexture=this._options.environmentTexture;return}const e=Ms.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new q("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 s=this._scene.getWorldExtends(n=>n!==this._ground&&n!==this._rootMesh&&n!==this._skybox),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Ii&&this._scene.activeCamera.upperRadiusLimit&&(e=this._scene.activeCamera.upperRadiusLimit*2,t=e);const n=r.length();n>e&&(e=n*2,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=bv("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new Ot("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 Kt){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new X(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=X.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new gx("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,X.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new nn(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let s=0;s{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Ot("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 Kt){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new Ms(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=X.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)}}dc._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png";dc._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds";dc._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class an extends ut{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=X.CLAMP_ADDRESSMODE,this._texture.wrapV=X.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=X.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=X.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,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=an.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new K,this.onLoadObservable=new K,s=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)||(s.activeCamera?s.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=Go(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:q.BACKSIDE},s);const n=this._material=new Ot(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Go("",{slice:.5,diameter:i.size*.98,segments:i.resolution*2,sideOrientation:q.BACKSIDE},s),this._halfDomeMask.rotate(Vr.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&&s.activeCamera){const l=s.activeCamera,h=T.Forward(),c=T.TransformNormal(h,l.getViewMatrix());c.normalize(),this.rotation.y=Math.acos(T.Dot(h,c))}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 an.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case an.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(s=>{let r=s.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=t:this._texture.uOffset=i});break}case an.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)}}an.MODE_MONOSCOPIC=0;an.MODE_TOPBOTTOM=1;an.MODE_SIDEBYSIDE=2;class iC extends an{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 X(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(s,r)=>{this.onLoadErrorObservable.notifyObservers(s||"Unknown error occured"),this.onError&&this.onError(s,r)})}}iC.MODE_MONOSCOPIC=an.MODE_MONOSCOPIC;iC.MODE_TOPBOTTOM=an.MODE_TOPBOTTOM;iC.MODE_SIDEBYSIDE=an.MODE_SIDEBYSIDE;const mH="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 gH=0;const sC=a=>{if(!a.environmentBRDFTexture){const e=a.useDelayedTextureLoading;a.useDelayedTextureLoading=!1;const t=a._blockEntityCollection;a._blockEntityCollection=!1;const i=X.CreateFromBase64String(mH,"EnvironmentBRDFTexture"+gH++,a,!0,!1,X.BILINEAR_SAMPLINGMODE);a._blockEntityCollection=t;const s=a.getEngine().getLoadedTexturesCache(),r=s.indexOf(i.getInternalTexture());r!==-1&&s.splice(r,1),i.isRGBD=!0,i.wrapU=X.CLAMP_ADDRESSMODE,i.wrapV=X.CLAMP_ADDRESSMODE,a.environmentBRDFTexture=i,a.useDelayedTextureLoading=e,a0.ExpandRGBDTexture(i);const n=a.getEngine().onContextRestoredObservable.add(()=>{i.isRGBD=!0;const o=a.onBeforeRenderObservable.add(()=>{i.isReady()&&(a.onBeforeRenderObservable.remove(o),a0.ExpandRGBDTexture(i))})});a.onDisposeObservable.add(()=>{a.getEngine().onContextRestoredObservable.remove(n)})}return a.environmentBRDFTexture};class xH extends Gr{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 Br extends hn{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new xH,t),this._useEnergyConservation=Br.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Br.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Br.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Br.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Br.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Br.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Br.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Br.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"}}Br.DEFAULT_USE_ENERGY_CONSERVATION=!0;Br.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Br.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Br.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;v([O(),_e("_markAllSubMeshesAsMiscDirty")],Br.prototype,"useEnergyConservation",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Br.prototype,"useSmithVisibilityHeightCorrelated",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Br.prototype,"useSphericalHarmonics",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Br.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const TH="pbrFragmentDeclaration",EH=`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 +`;j.IncludesShadersStore[TH]=EH;const SH="pbrUboDeclaration",vH=`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 +`;j.IncludesShadersStore[SH]=vH;const CH="pbrFragmentExtraDeclaration",bH=`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 +`;j.IncludesShadersStore[CH]=bH;const yH="samplerFragmentAlternateDeclaration",AH=`#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 +`;j.IncludesShadersStore[yH]=AH;const RH="pbrFragmentSamplersDeclaration",IH=`#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 +`;j.IncludesShadersStore[RH]=IH;const PH="subSurfaceScatteringFunctions",MH=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;j.IncludesShadersStore[PH]=MH;const OH="importanceSampling",DH=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;j.IncludesShadersStore[OH]=DH;const NH="pbrHelperFunctions",wH=`#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`;j.IncludesShadersStore[NH]=wH;const FH="harmonicsFunctions",LH=`#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 +`;j.IncludesShadersStore[FH]=LH;const BH="pbrDirectLightingSetupFunctions",UH=`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) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;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;}`;j.IncludesShadersStore[BH]=UH;const VH="pbrDirectLightingFalloffFunctions",kH=`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 +}`;j.IncludesShadersStore[VH]=kH;const GH="pbrBRDFFunctions",zH=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=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) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(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 +#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 +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);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;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 +#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 +`;j.IncludesShadersStore[WH]=HH;const XH="pbrDirectLightingFunctions",YH=`#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){vec4 strq=textureProjectionMatrix*vec4(vPositionW,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 +`;j.IncludesShadersStore[XH]=YH;const $H="pbrIBLFunctions",KH=`#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 +`;j.IncludesShadersStore[$H]=KH;const jH="pbrBlockAlbedoOpacity",qH=`struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +void 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 +out 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 +void 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 +out 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;} +`;j.IncludesShadersStore[QH]=ZH;const JH="pbrBlockAmbientOcclusion",eX=`struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +}; +#define pbr_inline +void ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos, +#endif +out 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;} +`;j.IncludesShadersStore[JH]=eX;const tX="pbrBlockAlphaFresnel",iX=`#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +void alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface, +out 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 +void anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW, +out 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);} +#endif +`;j.IncludesShadersStore[sX]=rX;const nX="pbrBlockReflection",aX=`#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 +void 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 +out 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;} +#endif +`;j.IncludesShadersStore[nX]=aX;const oX="pbrBlockSheen",lX=`#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 +void 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 +out 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;} +#endif +`;j.IncludesShadersStore[oX]=lX;const hX="pbrBlockClearcoat",cX=`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 +void 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 +out 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 +} +#endif +`;j.IncludesShadersStore[hX]=cX;const uX="pbrBlockIridescence",dX=`struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +void 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 +out 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;} +#endif +`;j.IncludesShadersStore[uX]=dX;const fX="pbrBlockSubSurface",pX=`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 +void 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 +out 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 +} +#endif +`;j.IncludesShadersStore[fX]=pX;const _X="pbrBlockNormalGeometric",mX=`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 +`;j.IncludesShadersStore[_X]=mX;const gX="pbrBlockNormalFinal",xX=`#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 +`;j.IncludesShadersStore[gX]=xX;const TX="pbrBlockLightmapInit",EX=`#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 +`;j.IncludesShadersStore[TX]=EX;const SX="pbrBlockGeometryInfo",vX=`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 +`;j.IncludesShadersStore[SX]=vX;const CX="pbrBlockReflectance0",bX=`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 +`;j.IncludesShadersStore[CX]=bX;const yX="pbrBlockReflectance",AX=`#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 +`;j.IncludesShadersStore[yX]=AX;const RX="pbrBlockDirectLighting",IX=`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 +`;j.IncludesShadersStore[RX]=IX;const PX="pbrBlockFinalLitComponents",MX=`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 +`;j.IncludesShadersStore[PX]=MX;const OX="pbrBlockFinalUnlitComponents",DX=`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; +`;j.IncludesShadersStore[OX]=DX;const NX="pbrBlockFinalColorComposition",wX=`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); +`;j.IncludesShadersStore[NX]=wX;const FX="pbrBlockImageProcessing",LX=`#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 +`;j.IncludesShadersStore[FX]=LX;const BX="pbrDebug",UX=`#if DEBUGMODE>0 +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+gl_FragCoord.y)/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 +`;j.IncludesShadersStore[BX]=UX;const VX="pbrPixelShader",kX=`#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 +albedoOpacityBlock( +vAlbedoColor, +#ifdef ALBEDO +albedoTexture, +vAlbedoInfos, +#endif +#ifdef OPACITY +opacityMap, +vOpacityInfos, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +#ifdef DECAL +decalColor, +vDecalInfos, +#endif +albedoOpacityOut +);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 +ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos, +#endif +aoOut +); +#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 +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 +reflectivityOut +);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;alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface, +alphaFresnelOut +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW, +anisotropicOut +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +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 +reflectionOut +); +#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 +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 +sheenOut +); +#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 +iridescenceBlock( +vIridescenceParams, +NdotV, +specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#endif +iridescenceOut +);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 +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 +clearcoatOut +); +#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 +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 +subSurfaceOut +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#endif +#include +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include +#include +#include(color,finalColor) +#include +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); +irradiance/=sqAlbedo; +#else +gl_FragData[0]=finalColor; +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#else +gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;j.ShadersStore[VX]=kX;const GX="pbrVertexDeclaration",zX=`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 +`;j.IncludesShadersStore[GX]=zX;const WX="pbrVertexShader",HX=`precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#include[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#include +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x) +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`;j.ShadersStore[WX]=HX;class XX extends Gr{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 ir extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new XX,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=ir._DefaultIndexOfRefraction,this.indexOfRefraction=ir._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=re.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const s=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Ce.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Ce.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&Ce.ClearCoatBumpTextureEnabled&&!s&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&Ce.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&&Ce.ClearCoatTextureEnabled?Oi(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Ce.ClearCoatTextureEnabled?Oi(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Ce.ClearCoatBumpTextureEnabled?Oi(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===ir._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Ce.ClearCoatTintTextureEnabled?(Oi(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,s){var c,u,d,f;if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,h=this._material._invertNormalMapY;if(!e.useUbo||!n||!e.isSync){(this._texture||this._textureRoughness)&&Ce.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",((c=this._texture)==null?void 0:c.coordinatesIndex)??0,((u=this._texture)==null?void 0:u.level)??0,((d=this._textureRoughness)==null?void 0:d.coordinatesIndex)??0,((f=this._textureRoughness)==null?void 0:f.level)??0),this._texture&&wi(this._texture,e,"clearCoat"),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&wi(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Ce.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),wi(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,h?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,h?-1:1)),this._tintTexture&&Ce.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),wi(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const m=1-this._indexOfRefraction,_=1+this._indexOfRefraction,x=Math.pow(-m/_,2),E=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",x,E,m,_),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&Ce.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ce.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Ce.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Ce.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,s,r;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(s=this._bumpTexture)==null||s.dispose(),(r=this._tintTexture)==null||r.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"}]}}}ir._DefaultIndexOfRefraction=1.5;v([O(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"isEnabled",void 0);v([O()],ir.prototype,"intensity",void 0);v([O()],ir.prototype,"roughness",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"indexOfRefraction",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"texture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"useRoughnessFromMainTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"textureRoughness",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"remapF0OnInterfaceChange",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"bumpTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"isTintEnabled",void 0);v([Vi()],ir.prototype,"tintColor",void 0);v([O()],ir.prototype,"tintColorAtDistance",void 0);v([O()],ir.prototype,"tintThickness",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],ir.prototype,"tintTexture",void 0);class YX extends Gr{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 jr extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new YX,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=jr._DefaultMinimumThickness,this.maximumThickness=jr._DefaultMaximumThickness,this.indexOfRefraction=jr._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&&Ce.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&Ce.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Ce.IridescenceTextureEnabled?Oi(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Ce.IridescenceTextureEnabled?Oi(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 s,r,n,o;if(!this._isEnabled)return;const i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&&Ce.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",((s=this._texture)==null?void 0:s.coordinatesIndex)??0,((r=this._texture)==null?void 0:r.level)??0,((n=this._thicknessTexture)==null?void 0:n.coordinatesIndex)??0,((o=this._thicknessTexture)==null?void 0:o.level)??0),this._texture&&wi(this._texture,e,"iridescence"),this._thicknessTexture&&wi(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Ce.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Ce.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"}]}}}jr._DefaultMinimumThickness=100;jr._DefaultMaximumThickness=400;jr._DefaultIndexOfRefraction=1.3;v([O(),_e("_markAllSubMeshesAsTexturesDirty")],jr.prototype,"isEnabled",void 0);v([O()],jr.prototype,"intensity",void 0);v([O()],jr.prototype,"minimumThickness",void 0);v([O()],jr.prototype,"maximumThickness",void 0);v([O()],jr.prototype,"indexOfRefraction",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],jr.prototype,"texture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],jr.prototype,"thicknessTexture",void 0);class $X extends Gr{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class pf extends hn{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()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new $X,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new ce(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&&Ce.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(P.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Ce.AnisotropicTextureEnabled?Oi(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&&Ce.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),wi(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Ce.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([O(),_e("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"isEnabled",void 0);v([O()],pf.prototype,"intensity",void 0);v([ev()],pf.prototype,"direction",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"texture",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],pf.prototype,"legacy",void 0);class KX extends Gr{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 Ho extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new KX,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=re.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Ce.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&Ce.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&&Ce.SheenTextureEnabled?(Oi(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Ce.SheenTextureEnabled?Oi(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,s){var o,l,h,c;if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;(!e.useUbo||!n||!e.isSync)&&((this._texture||this._textureRoughness)&&Ce.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",((o=this._texture)==null?void 0:o.coordinatesIndex)??0,((l=this._texture)==null?void 0:l.level)??0,((h=this._textureRoughness)==null?void 0:h.coordinatesIndex)??0,((c=this._textureRoughness)==null?void 0:c.level)??0),this._texture&&wi(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&wi(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&&Ce.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ce.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([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"isEnabled",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"linkSheenWithAlbedo",void 0);v([O()],Ho.prototype,"intensity",void 0);v([Vi()],Ho.prototype,"color",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"texture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"useRoughnessFromMainTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"roughness",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"textureRoughness",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Ho.prototype,"albedoScaling",void 0);class jX extends Gr{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 Qi extends hn{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()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new jX,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=re.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=re.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Ce.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&&Ce.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;const i=this._getRefractionTexture(t);if(i&&Ce.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&&Ce.ThicknessTextureEnabled&&Oi(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Ce.RefractionIntensityTextureEnabled&&Oi(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Ce.TranslucencyIntensityTextureEnabled&&Oi(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Ce.TranslucencyColorTextureEnabled&&Oi(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&&Ce.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,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(W.Vector3[0]);const r=Math.max(Math.abs(W.Vector3[0].x),Math.abs(W.Vector3[0].y),Math.abs(W.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,l=r.LODBASEDMICROSFURACE,h=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Ce.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),wi(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Ce.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),wi(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Ce.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),wi(this._translucencyColorTexture,e,"translucencyColor")),h&&Ce.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",h.getRefractionTextureMatrix());let c=1;h.isCube||h.depth&&(c=h.depth);const u=h.getSize().width,d=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",h.level,1/d,c,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",u,h.lodGenerationScale,h.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",u,Ne.Log2(u)),h.boundingBoxSize){const f=h;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&&Ce.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Ce.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Ce.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Ce.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),h&&Ce.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",h):(e.setTexture("refractionSampler",h._lodTextureMid||h),e.setTexture("refractionSamplerLow",h._lodTextureLow||h),e.setTexture("refractionSamplerHigh",h._lodTextureHigh||h))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Ce.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!!(Ce.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)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.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([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"isRefractionEnabled",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"isTranslucencyEnabled",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"isDispersionEnabled",void 0);v([O(),_e("_markScenePrePassDirty")],Qi.prototype,"isScatteringEnabled",void 0);v([O()],Qi.prototype,"_scatteringDiffusionProfileIndex",void 0);v([O()],Qi.prototype,"refractionIntensity",void 0);v([O()],Qi.prototype,"translucencyIntensity",void 0);v([O()],Qi.prototype,"useAlbedoToTintRefraction",void 0);v([O()],Qi.prototype,"useAlbedoToTintTranslucency",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"thicknessTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"refractionTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"indexOfRefraction",void 0);v([O()],Qi.prototype,"_volumeIndexOfRefraction",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"volumeIndexOfRefraction",null);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"invertRefractionY",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"linkRefractionWithTransparency",void 0);v([O()],Qi.prototype,"minimumThickness",void 0);v([O()],Qi.prototype,"maximumThickness",void 0);v([O()],Qi.prototype,"useThicknessAsDepth",void 0);v([Vi()],Qi.prototype,"tintColor",void 0);v([O()],Qi.prototype,"tintColorAtDistance",void 0);v([O()],Qi.prototype,"dispersion",void 0);v([Vi()],Qi.prototype,"diffusionDistance",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"useMaskFromThicknessTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"refractionIntensityTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"translucencyIntensityTexture",void 0);v([Vi()],Qi.prototype,"translucencyColor",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"translucencyColorTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Qi.prototype,"useGltfStyleTextures",void 0);const $c={effect:null,subMesh:null};class P0 extends Gr{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class ei extends cf{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){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new tt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=ei.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=re.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new re(0,0,0),this._albedoColor=new re(1,1,1),this._reflectivityColor=new re(1,1,1),this._reflectionColor=new re(1,1,1),this._emissiveColor=new re(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=ei.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 Ps(16),this._globalAmbientColor=new re(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Br(this),this.clearCoat=new ir(this),this.iridescence=new jr(this),this.anisotropy=new pf(this),this.sheen=new Ho(this),this.subSurface=new Qi(this),this.detailMap=new Ah(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Ce.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=sC(this.getScene()),this.prePassConfiguration=new pg}get hasRenderTargetTextures(){return Ce.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===ei.PBRMATERIAL_OPAQUE||this._transparencyMode===ei.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===ei.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==ei.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 s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(gr.GetDefineNames,this._eventInfo),t.materialDefines=new P0(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&Ce.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&Ce.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&Ce.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const f=this._getReflectionTexture();if(f&&Ce.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&&Ce.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&Ce.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Ce.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&&Ce.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&Ce.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;!o.getCaps().standardDerivatives&&!e.isVerticesDataPresent(P.NormalKind)&&(e.createNormals(!0),U.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const l=t.effect,h=r._areLightsDisposed;let c=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(c)if(this._onEffectCreatedObservable&&($c.effect=c,$c.subMesh=t,this._onEffectCreatedObservable.notifyObservers($c)),this.allowShaderHotSwapping&&l&&!c.isReady()){if(c=l,r.markAsUnprocessed(),u=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(c,r,this._materialContext);return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!u,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!!(this._metallic!=null||this._roughness!=null||this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const h=this.getScene().getEngine(),c=new gc;let u=0;t.USESPHERICALINVERTEX&&c.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&c.addFallback(u,"FOG"),t.SPECULARAA&&c.addFallback(u,"SPECULARAA"),t.POINTSIZE&&c.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&c.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&c.addFallback(u,"PARALLAX"),t.PARALLAX_RHS&&c.addFallback(u,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&c.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&c.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&c.addFallback(u++,"TANGENT"),t.BUMP&&c.addFallback(u++,"BUMP"),u=xv(t,c,this._maxSimultaneousLights,u++),t.SPECULARTERM&&c.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&c.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&c.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&c.addFallback(u++,"LIGHTMAP"),t.NORMAL&&c.addFallback(u++,"NORMAL"),t.AMBIENT&&c.addFallback(u++,"AMBIENT"),t.EMISSIVE&&c.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&c.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&c.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&c.addFallback(0,"MULTIVIEW");const d=[P.PositionKind];t.NORMAL&&d.push(P.NormalKind),t.TANGENT&&d.push(P.TangentKind);for(let A=1;A<=6;++A)t["UV"+A]&&d.push(`uv${A===1?"":A}`);t.VERTEXCOLOR&&d.push(P.ColorKind),gv(d,e,t,c),zg(d,t),pv(d,e,t),_v(d,e,t);let f="pbr";const m=["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"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],x=["Material","Scene","Mesh"],E={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=c,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=m,this._eventInfo.attributes=d,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=x,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=E,this._callbackPluginEventGeneric(gr.PrepareEffect,this._eventInfo),pg.AddUniforms(m),Va(m),Mt&&(Mt.PrepareUniforms(m,t),Mt.PrepareSamplers(_,t)),$g({uniformsNames:m,uniformBuffersNames:x,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const S={};this.customShaderNameResolve&&(f=this.customShaderNameResolve(f,m,x,_,t,d,S));const C=t.toString(),y=h.createEffect(f,{attributes:d,uniformsNames:m,uniformBuffersNames:x,samplers:_,defines:C,fallbacks:c,onCompiled:i,onError:s,indexParameters:E,processFinalCode:S.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},h);return this._eventInfo.customCode=void 0,y}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();c_(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Yg(n,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Ev(n,t,this.canRenderToMRT&&!l),hP(n,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let h=1;h<=6;++h)t["MAINUV"+h]=!1;if(n.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&&Ce.DiffuseTextureEnabled?(Oi(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Ce.AmbientTextureEnabled?(Oi(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Ce.OpacityTextureEnabled?(Oi(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const h=this._getReflectionTexture();if(h&&Ce.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=h.gammaSpace,t.RGBDREFLECTION=h.isRGBD,t.LODINREFLECTIONALPHA=h.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=h.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=h.coordinatesMode===X.INVCUBIC_MODE,t.REFLECTIONMAP_3D=h.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!h.invertZ:h.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,h.coordinatesMode){case X.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case X.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case X.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case X.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case X.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case X.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case X.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case X.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case X.CUBIC_MODE:case X.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!h.boundingBoxSize;break}h.coordinatesMode!==X.SKYBOX_MODE&&(h.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):h.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&&Ce.LightmapTextureEnabled?(Oi(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Ce.EmissiveTextureEnabled?(Oi(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Ce.SpecularTextureEnabled?(this._metallicTexture?(Oi(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?(Oi(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?(Oi(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Oi(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Oi(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&Ce.BumpTextureEnabled&&!this._disableBumpMap?(Oi(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Ce.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.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&&Ce.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===ei.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===ei.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&&(Wg(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(P.NormalKind),t.DEBUGMODE=this._debugMode),Hg(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Xg(e,t,!0,!0,!0,this._transparencyMode!==ei.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(gr.GetDefineNames,this._eventInfo);const r=new P0(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&($c.effect=n,$c.subMesh=null,this._onEffectCreatedObservable.notifyObservers($c)),n.isReady()?t&&t(this):n.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 u,d,f;const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=this._mustRebind(s,n,i,t.visibility);l_(t,this._activeEffect,this.prePassConfiguration);let h=null;const c=this._uniformBuffer;if(l){if(this.bindViewProjection(n),h=this._getReflectionTexture(),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&Ce.DiffuseTextureEnabled&&(c.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),wi(this._albedoTexture,c,"albedo")),this._ambientTexture&&Ce.AmbientTextureEnabled&&(c.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),wi(this._ambientTexture,c,"ambient")),this._opacityTexture&&Ce.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),wi(this._opacityTexture,c,"opacity")),h&&Ce.ReflectionTextureEnabled){if(c.updateMatrix("reflectionMatrix",h.getReflectionTextureMatrix()),c.updateFloat2("vReflectionInfos",h.level,0),h.boundingBoxSize){const m=h;c.updateVector3("vReflectionPosition",m.boundingBoxPosition),c.updateVector3("vReflectionSize",m.boundingBoxSize)}if(this.realTimeFiltering){const m=h.getSize().width;c.updateFloat2("vReflectionFilteringInfo",m,Ne.Log2(m))}if(!r.USEIRRADIANCEMAP){const m=h.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&m)if(r.SPHERICAL_HARMONICS){const _=m.preScaledHarmonics;c.updateVector3("vSphericalL00",_.l00),c.updateVector3("vSphericalL1_1",_.l1_1),c.updateVector3("vSphericalL10",_.l10),c.updateVector3("vSphericalL11",_.l11),c.updateVector3("vSphericalL2_2",_.l2_2),c.updateVector3("vSphericalL2_1",_.l2_1),c.updateVector3("vSphericalL20",_.l20),c.updateVector3("vSphericalL21",_.l21),c.updateVector3("vSphericalL22",_.l22)}else c.updateFloat3("vSphericalX",m.x.x,m.x.y,m.x.z),c.updateFloat3("vSphericalY",m.y.x,m.y.y,m.y.z),c.updateFloat3("vSphericalZ",m.z.x,m.z.y,m.z.z),c.updateFloat3("vSphericalXX_ZZ",m.xx.x-m.zz.x,m.xx.y-m.zz.y,m.xx.z-m.zz.z),c.updateFloat3("vSphericalYY_ZZ",m.yy.x-m.zz.x,m.yy.y-m.zz.y,m.yy.z-m.zz.z),c.updateFloat3("vSphericalZZ",m.zz.x,m.zz.y,m.zz.z),c.updateFloat3("vSphericalXY",m.xy.x,m.xy.y,m.xy.z),c.updateFloat3("vSphericalYZ",m.yz.x,m.yz.y,m.yz.z),c.updateFloat3("vSphericalZX",m.zx.x,m.zx.y,m.zx.z)}c.updateFloat3("vReflectionMicrosurfaceInfos",h.getSize().width,h.lodGenerationScale,h.lodGenerationOffset)}this._emissiveTexture&&Ce.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),wi(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&Ce.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),wi(this._lightmapTexture,c,"lightmap")),Ce.SpecularTextureEnabled&&(this._metallicTexture?(c.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),wi(this._metallicTexture,c,"reflectivity")):this._reflectivityTexture&&(c.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),wi(this._reflectivityTexture,c,"reflectivity")),this._metallicReflectanceTexture&&(c.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),wi(this._metallicReflectanceTexture,c,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(c.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),wi(this._reflectanceTexture,c,"reflectance")),this._microSurfaceTexture&&(c.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),wi(this._microSurfaceTexture,c,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&Ce.BumpTextureEnabled&&!this._disableBumpMap&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),wi(this._bumpTexture,c,"bump"),s._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){Yt.Color3[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,Yt.Color3[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness,c.updateColor4("vReflectivityColor",Yt.Color3[0],1);const m=((u=this.subSurface)==null?void 0:u._indexOfRefraction)??1.5,_=1,x=Math.pow((m-_)/(m+_),2);this._metallicReflectanceColor.scaleToRef(x*this._metallicF0Factor,Yt.Color3[0]);const E=this._metallicF0Factor;c.updateColor4("vMetallicReflectanceFactors",Yt.Color3[0],E)}else c.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);c.updateColor3("vEmissiveColor",Ce.EmissiveTextureEnabled?this._emissiveColor:re.BlackReadOnly),c.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&((d=this.subSurface)!=null&&d._linkRefractionWithTransparency)?c.updateColor4("vAlbedoColor",this._albedoColor,1):c.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,c.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor),c.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&Ce.DiffuseTextureEnabled&&c.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Ce.AmbientTextureEnabled&&c.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Ce.OpacityTextureEnabled&&c.setTexture("opacitySampler",this._opacityTexture),h&&Ce.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?c.setTexture("reflectionSampler",h):(c.setTexture("reflectionSampler",h._lodTextureMid||h),c.setTexture("reflectionSamplerLow",h._lodTextureLow||h),c.setTexture("reflectionSamplerHigh",h._lodTextureHigh||h)),r.USEIRRADIANCEMAP&&c.setTexture("irradianceSampler",h.irradianceTexture)),r.ENVIRONMENTBRDF&&c.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Ce.EmissiveTextureEnabled&&c.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Ce.LightmapTextureEnabled&&c.setTexture("lightmapSampler",this._lightmapTexture),Ce.SpecularTextureEnabled&&(this._metallicTexture?c.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&c.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&c.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&c.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&c.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&Ce.BumpTextureEnabled&&!this._disableBumpMap&&c.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),pa(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&h_(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Ue.FOGMODE_NONE||h||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),mc(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&Al(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(n,r.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Ch(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),c.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,s,r,n,o,l,h,c,u,d,f,m;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(s=this._ambientTexture)==null||s.dispose(),(r=this._opacityTexture)==null||r.dispose(),(n=this._reflectionTexture)==null||n.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._metallicTexture)==null||l.dispose(),(h=this._reflectivityTexture)==null||h.dispose(),(c=this._bumpTexture)==null||c.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(d=this._metallicReflectanceTexture)==null||d.dispose(),(f=this._reflectanceTexture)==null||f.dispose(),(m=this._microSurfaceTexture)==null||m.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}ei.PBRMATERIAL_OPAQUE=pe.MATERIAL_OPAQUE;ei.PBRMATERIAL_ALPHATEST=pe.MATERIAL_ALPHATEST;ei.PBRMATERIAL_ALPHABLEND=pe.MATERIAL_ALPHABLEND;ei.PBRMATERIAL_ALPHATESTANDBLEND=pe.MATERIAL_ALPHATESTANDBLEND;ei.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;ei.LIGHTFALLOFF_PHYSICAL=0;ei.LIGHTFALLOFF_GLTF=1;ei.LIGHTFALLOFF_STANDARD=2;v([dI()],ei.prototype,"_imageProcessingConfiguration",void 0);v([_e("_markAllSubMeshesAsMiscDirty")],ei.prototype,"debugMode",void 0);class Xe extends ei{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===ei.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=ei.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=ei.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===ei.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=ei.LIGHTFALLOFF_GLTF:this._lightFalloff=ei.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){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=Xe.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=re.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new re(0,0,0),this.albedoColor=new re(1,1,1),this.reflectivityColor=new re(1,1,1),this.reflectionColor=new re(1,1,1),this.emissiveColor=new re(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=sC(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Pe.Clone(()=>new Xe(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=Pe.Parse(()=>new Xe(e.name,t),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),pe._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Xe.PBRMATERIAL_OPAQUE=ei.PBRMATERIAL_OPAQUE;Xe.PBRMATERIAL_ALPHATEST=ei.PBRMATERIAL_ALPHATEST;Xe.PBRMATERIAL_ALPHABLEND=ei.PBRMATERIAL_ALPHABLEND;Xe.PBRMATERIAL_ALPHATESTANDBLEND=ei.PBRMATERIAL_ALPHATESTANDBLEND;Xe.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=ei.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"directIntensity",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"emissiveIntensity",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"environmentIntensity",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"specularIntensity",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"disableBumpMap",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"albedoTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"ambientTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"ambientTextureStrength",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Xe.prototype,"opacityTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"reflectionTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"emissiveTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"reflectivityTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"metallicTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"metallic",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"roughness",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"metallicF0Factor",void 0);v([Vi(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"metallicReflectanceColor",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"metallicReflectanceTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"reflectanceTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"microSurfaceTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"bumpTexture",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty",null)],Xe.prototype,"lightmapTexture",void 0);v([Vi("ambient"),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"ambientColor",void 0);v([Vi("albedo"),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"albedoColor",void 0);v([Vi("reflectivity"),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"reflectivityColor",void 0);v([Vi("reflection"),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"reflectionColor",void 0);v([Vi("emissive"),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"emissiveColor",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"microSurface",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useLightmapAsShadowmap",void 0);v([O(),_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Xe.prototype,"useAlphaFromAlbedoTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Xe.prototype,"forceAlphaTest",void 0);v([O(),_e("_markAllSubMeshesAsTexturesAndMiscDirty")],Xe.prototype,"alphaCutOff",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useSpecularOverAlpha",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useRoughnessFromMetallicTextureGreen",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useMetallnessFromMetallicTextureBlue",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useAmbientInGrayScale",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);v([O()],Xe.prototype,"usePhysicalLightFalloff",null);v([O()],Xe.prototype,"useGLTFLightFalloff",null);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useRadianceOverAlpha",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useObjectSpaceNormalMap",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useParallax",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useParallaxOcclusion",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"parallaxScaleBias",void 0);v([O(),_e("_markAllSubMeshesAsLightsDirty")],Xe.prototype,"disableLighting",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"forceIrradianceInFragment",void 0);v([O(),_e("_markAllSubMeshesAsLightsDirty")],Xe.prototype,"maxSimultaneousLights",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"invertNormalMapX",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"invertNormalMapY",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"twoSidedLighting",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useAlphaFresnel",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useLinearAlphaFresnel",void 0);v([_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"environmentBRDFTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"forceNormalForward",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"enableSpecularAntiAliasing",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useHorizonOcclusion",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Xe.prototype,"useRadianceOcclusion",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Xe.prototype,"unlit",void 0);v([O(),_e("_markAllSubMeshesAsMiscDirty")],Xe.prototype,"applyDecalMapAfterDetailMap",void 0);H("BABYLON.PBRMaterial",Xe);const qX=542327876,M0=131072,O0=512,D0=4,N0=64,w0=131072;function xx(a){return a.charCodeAt(0)+(a.charCodeAt(1)<<8)+(a.charCodeAt(2)<<16)+(a.charCodeAt(3)<<24)}function QX(a){return String.fromCharCode(a&255,a>>8&255,a>>16&255,a>>24&255)}const F0=xx("DXT1"),L0=xx("DXT3"),B0=xx("DXT5"),xE=xx("DX10"),U0=113,V0=116,k0=2,G0=10,ZX=88,TE=31,JX=0,e5=1,z0=2,W0=3,EE=4,H0=7,SE=20,X0=21,t5=22,i5=23,s5=24,r5=25,n5=26,a5=28,o5=32;class pi{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,TE),i=new Int32Array(e.buffer,e.byteOffset,TE+4);let s=1;t[z0]&M0&&(s=Math.max(1,t[H0]));const r=t[X0],n=r===xE?i[o5]:0;let o=0;switch(r){case U0:o=2;break;case V0:o=1;break;case xE:if(n===G0){o=2;break}if(n===k0){o=1;break}}return{width:t[EE],height:t[W0],mipmapCount:s,isFourCC:(t[SE]&D0)===D0,isRGB:(t[SE]&N0)===N0,isLuminance:(t[SE]&w0)===w0,isCube:(t[a5]&O0)===O0,isCompressed:r===F0||r===L0||r===B0,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),l=new Uint16Array(r,i);let h=0;for(let c=0;c>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,l){const h=new Uint8Array(s),c=new Uint8Array(r,i);let u=0;for(let d=0;d0?s.sphericalPolynomial=ff.ConvertCubeMapToSphericalPolynomial({size:d[EE],right:c[0],left:c[1],up:c[2],down:c[3],front:c[4],back:c[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}pi.StoreLODInAlphaChannel=!1;nt.prototype.createPrefilteredCubeTexture=function(a,e,t,i,s=null,r=null,n,o=null,l=!0){const h=c=>{if(!c){s&&s(null);return}const u=c.texture;if(l?c.info.sphericalPolynomial&&(u._sphericalPolynomial=c.info.sphericalPolynomial):u._sphericalPolynomial=new zo,u._source=xt.CubePrefiltered,this.getCaps().textureLOD){s&&s(u);return}const d=3,f=this._gl,m=c.width;if(!m)return;const _=[];for(let x=0;x1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pi.UploadDDSLevels(r,t,c,n,o,6,-1,h),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t):l=n.mipmapCount-1}else{const h=e;n=pi.GetDDSInfo(h),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new zo),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pi.UploadDDSLevels(r,t,h,n,o,6),!n.isFourCC&&n.mipmapCount===1?r.generateMipMapsForCubemap(t,!1):l=n.mipmapCount-1}r._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=pi.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1===1;i(s.width,s.height,r,s.isFourCC,()=>{pi.UploadDDSLevels(t.getEngine(),t,e,s,r,1)})}}ee._TextureLoaders.push(new l5);class h5{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=KP(e);if(n){t.width=n.width,t.height=n.width;try{qP(t,n),r4(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()},o=>{r==null||r("Can not upload environment levels",o)})}catch(o){r==null||r("Can not upload environment file",o)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}ee._TextureLoaders.push(new h5);class ca{constructor(e,t){if(this.data=e,this.isInvalid=!1,!ca.IsValid(e)){this.isInvalid=!0,U.Error("texture missing KTX identifier");return}const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),n=s.getUint32(0,!0)===67305985;if(this.glType=s.getUint32(1*i,n),this.glTypeSize=s.getUint32(2*i,n),this.glFormat=s.getUint32(3*i,n),this.glInternalFormat=s.getUint32(4*i,n),this.glBaseInternalFormat=s.getUint32(5*i,n),this.pixelWidth=s.getUint32(6*i,n),this.pixelHeight=s.getUint32(7*i,n),this.pixelDepth=s.getUint32(8*i,n),this.numberOfArrayElements=s.getUint32(9*i,n),this.numberOfFaces=s.getUint32(10*i,n),this.numberOfMipmapLevels=s.getUint32(11*i,n),this.bytesOfKeyValueData=s.getUint32(12*i,n),this.glType!==0){U.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){U.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){U.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){U.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=ca.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case ca.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break}}_upload2DCompressedLevels(e,t){let i=ca.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=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}}ca.HEADER_LEN=12+13*4;ca.COMPRESSED_2D=0;ca.COMPRESSED_3D=1;ca.TEX_2D=2;ca.TEX_3D=3;class c5{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 s=this._pendingActions.shift();s?this._execute(e,s):e.idle=!0})})}}class p_ extends c5{constructor(e,t,i=p_.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{s(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(n=>{n.terminate()});const r=this._workerInfos.indexOf(e);r!==-1&&this._workerInfos.splice(r,1)},this._options.idleTimeElapsedBeforeRelease))})})}}p_.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};var Y0;(function(a){a[a.ETC1S=0]="ETC1S",a[a.UASTC4x4=1]="UASTC4x4"})(Y0||(Y0={}));var op;(function(a){a[a.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",a[a.BC7_RGBA=1]="BC7_RGBA",a[a.BC3_RGBA=2]="BC3_RGBA",a[a.BC1_RGB=3]="BC1_RGB",a[a.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",a[a.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",a[a.ETC2_RGBA=6]="ETC2_RGBA",a[a.ETC1_RGB=7]="ETC1_RGB",a[a.RGBA32=8]="RGBA32",a[a.R8=9]="R8",a[a.RG8=10]="RG8"})(op||(op={}));var ZE;(function(a){a[a.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",a[a.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",a[a.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",a[a.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",a[a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",a[a.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",a[a.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",a[a.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",a[a.RGBA8Format=32856]="RGBA8Format",a[a.R8Format=33321]="R8Format",a[a.RG8Format=33323]="RG8Format"})(ZE||(ZE={}));function Cg(a,e){const t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;a&&(a.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=a.wasmUASTCToASTC),a.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=a.wasmUASTCToBC7),a.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=a.wasmUASTCToRGBA_UNORM),a.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=a.wasmUASTCToRGBA_SRGB),a.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=a.wasmUASTCToR8_UNORM),a.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=a.wasmUASTCToRG8_UNORM),a.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=a.jsMSCTranscoder),a.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=a.wasmMSCTranscoder),a.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=a.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 u5(a){typeof a>"u"&&typeof KTX2DECODER<"u"&&(a=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;i&&(i.jsDecoderModule&&typeof a>"u"&&(importScripts(i.jsDecoderModule),a=KTX2DECODER),Cg(i)),t.data.wasmBinaries&&Cg(void 0,{...t.data.wasmBinaries,jsDecoderModule:a}),e=new a.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{a.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{const s=[];for(let r=0;r{postMessage({action:"decoded",success:!1,msg:i})});break}}}function d5(a,e,t){return new Promise((i,s)=>{const r=o=>{a.removeEventListener("error",r),a.removeEventListener("message",n),s(o)},n=o=>{o.data.action==="init"&&(a.removeEventListener("error",r),a.removeEventListener("message",n),i(a))};a.addEventListener("error",r),a.addEventListener("message",n),a.postMessage({action:"init",urls:t,wasmBinaries:e})})}class f5{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:[op.BC1_RGB,op.BC3_RGBA],yes:{transcodeFormat:op.RGBA32,engineFormat:ZE.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class Ei{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(Ei._WorkerPoolPromise||Ei._DecoderModulePromise)return;const t={jsDecoderModule:Z.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Z.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Z.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Z.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Z.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL<"u"?Ei._WorkerPoolPromise=new Promise(i=>{const s=`${Cg}(${u5})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new p_(e,()=>d5(new Worker(r),void 0,t)))}):typeof Ei._KTX2DecoderModule>"u"?Ei._DecoderModulePromise=Z.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(Ei._KTX2DecoderModule=KTX2DECODER,Ei._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Ei._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Cg(t,Ei._KTX2DecoderModule),new Ei._KTX2DecoderModule.KTX2Decoder)):(Ei._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,Ei._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Ei._DecoderModulePromise=Promise.resolve(new Ei._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=Ei.DefaultNumWorkers){var s;this._engine=e;const i=typeof t=="object"&&t.workerPool||Ei.WorkerPool;if(i)Ei._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?Ei._KTX2DecoderModule=(s=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:s.jsDecoderModule:typeof KTX2DECODER<"u"&&(Ei._KTX2DecoderModule=KTX2DECODER);const r=typeof t=="number"?t:t.numWorkers??Ei.DefaultNumWorkers;Ei._Initialize(r)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(Ei._WorkerPoolPromise)return Ei._WorkerPoolPromise.then(n=>new Promise((o,l)=>{n.push((h,c)=>{const u=m=>{h.removeEventListener("error",u),h.removeEventListener("message",d),l(m),c()},d=m=>{if(m.data.action==="decoded"){if(h.removeEventListener("error",u),h.removeEventListener("message",d),!m.data.success)l({message:m.data.msg});else try{this._createTexture(m.data.decodedData,t,i),o()}catch(_){l({message:_})}c()}};h.addEventListener("error",u),h.addEventListener("message",d),h.postMessage({action:"setDefaultDecoderOptions",options:Ei.DefaultDecoderOptions._getKTX2DecoderOptions()});const f=new Uint8Array(e.byteLength);f.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),h.postMessage({action:"decode",data:f,caps:r,options:i},[f.buffer])})}));if(Ei._DecoderModulePromise)return Ei._DecoderModulePromise.then(n=>(Ei.DefaultDecoderOptions.isDirty&&(Ei._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=Ei.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((o,l)=>{n.decode(e,s).then(h=>{this._createTexture(h,t),o()}).catch(h=>{l({message:h})})})));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 r=!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,r=!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 n=0;n=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}}Ei.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};Ei.DefaultNumWorkers=Ei.GetDefaultNumWorkers();Ei.DefaultDecoderOptions=new f5;function p5(a){switch(a){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 _5{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||t==="image/ktx"||t==="image/ktx2"}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new ca(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(ca.IsValid(e)){t._invertVScale=!t.invertY;const r=new ca(e,1),n=p5(r.glInternalFormat);n?(t.format=n,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else Ei.IsValid(e)?new Ei(t.getEngine())._uploadAsync(e,t,s).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},n=>{U.Warn(`Failed to load KTX2 texture data: ${n.message}`),i(0,0,!1,!1,()=>{},!0)}):(U.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}ee._TextureLoaders.unshift(new _5);class Vp extends ln{constructor(e,t,i){super(e,T.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=ae.Identity(),this._referencedPosition=new T,this._trackingState=eu.NOT_TRACKING,this.onXRCameraInitializedObservable=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onTrackingStateChanged=new K,this.compensateOnFirstFrame=!0,this._rotate180=new ae(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new ae,this.cameraRigMode=Ve.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 da(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new da(.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,ae.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=W.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),ae.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(eu.NOT_TRACKING);return}const t=e.emulatedPosition?eu.TRACKING_LOST:eu.TRACKING;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 s=e.transform.position;this._referencedPosition.set(s.x,s.y,s.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,s)=>{var u;const r=this.rigCameras[s];!r.isLeftCamera&&!r.isRightCamera&&(i.eye==="right"?r._isRightCamera=!0:i.eye==="left"&&(r._isLeftCamera=!0));const n=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=W.Matrix[0],t=W.Matrix[1],i=W.Matrix[2];L.ComposeToRef(Vp._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),L.ComposeToRef(Vp._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 s=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(s)}}}Vp._ScaleReadOnly=T.One();class rC{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 K,this.onStateChangedObservable=new K,this.state=Bs.NOT_IN_XR,this.sessionManager=new cx(e),this.camera=new Vp("webxr",e,this.sessionManager),this.featuresManager=new qi(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){const t=new rC(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(i=>{throw t._setState(Bs.NOT_IN_XR),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(),s={}){var r,n,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Bs.ENTERING_XR),t!=="viewer"&&t!=="local"&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),e==="immersive-ar"&&t!=="unbounded"&&U.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(Vt.LAYERS)){const h=await i.initializeXRLayerAsync(this.sessionManager.session);l.baseLayer=h}return this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!((n=(r=this._nonVRCamera)==null?void 0:r.inputs)!=null&&n.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)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==Bs.EXITING_XR&&this._setState(Bs.EXITING_XR),this.camera.rigCameras.forEach(h=>{h.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(Bs.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(Bs.IN_XR)}),this.sessionManager}catch(l){throw U.Log(l),U.Log(l.message),this._setState(Bs.NOT_IN_XR),l}}exitXRAsync(){return this.state!==Bs.IN_XR?Promise.resolve():(this._setState(Bs.EXITING_XR),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,s=e!=null&&e.preferredCameraIndex?e==null?void 0:e.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[s].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[s].absoluteRotation))};if(this._spectatorMode){if(s>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const n=()=>{this.state===Bs.IN_XR?(this._spectatorCamera=new uf("webxr-spectator",T.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new ae,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(o=>{o===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===Bs.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(n),n()}else this.sessionManager.onXRFrameObservable.removeCallback(r),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 $n{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new K,this.onButtonStateChangedObservable=new K}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 s=e.buttons[this._buttonIndex];if(!s)return;this._currentValue!==s.value&&(this.changes.value={current:s.value,previous:this._currentValue},t=!0,this._currentValue=s.value),this._touched!==s.touched&&(this.changes.touched={current:s.touched,previous:this._touched},t=!0,this._touched=s.touched),this._pressed!==s.pressed&&(this.changes.pressed={current:s.pressed,previous:this._pressed},t=!0,this._pressed=s.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))}}$n.BUTTON_TYPE="button";$n.SQUEEZE_TYPE="squeeze";$n.THUMBSTICK_TYPE="thumbstick";$n.TOUCHPAD_TYPE="touchpad";$n.TRIGGER_TYPE="trigger";class _f{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=o=>{if(!o)return;const l=this.layout.components[o],h=l.type,c=l.gamepadIndices.button,u=[];l.gamepadIndices.xAxis!==void 0&&l.gamepadIndices.yAxis!==void 0&&u.push(l.gamepadIndices.xAxis,l.gamepadIndices.yAxis),this.components[o]=new $n(o,h,c,u)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new K,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?U.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,s)=>{const r=n=>{e?this._getGenericParentMesh(n):this._setRootMesh(n),this._processLoadedModel(n),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const n=this._controllerCache.filter(o=>o.filename===t.filename&&o.path===t.path);if(n[0]){n[0].meshes.forEach(o=>o.setEnabled(!0)),r(n[0].meshes);return}}ft.ImportMesh("",t.path,t.filename,this.scene,n=>{this._controllerCache&&this._controllerCache.push({...t,meshes:n}),r(n)},null,(n,o)=>{U.Log(o),U.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(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 s=i?t*.5+.5:t;ae.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),T.LerpToRef(e.minMesh.position,e.maxMesh.position,s,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 q(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.parent||(t.isPickable=!1,t.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=ae.FromEulerAngles(0,Math.PI,0)}}class kp extends _f{constructor(e,t,i){super(e,m5[i],t,i),this.profileId=kp.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new q(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1,t.parent||t.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=ae.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}kp.ProfileId="generic-trigger";const m5={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 g5 extends _f{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,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=ft.IsPluginForExtensionAvailable(".glb");return e||U.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(s=>{const r=i.visualResponses[s];if(r.valueNodeProperty==="transform")this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{const n=i.type===$n.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[t].states[s]={valueMesh:this._getChildByName(this.rootMesh,n)},i.type===$n.TOUCHPAD_TYPE&&!this._touchDots[s]){const o=Go(s+"dot",{diameter:.0015,segments:8},this.scene);o.material=new Ie(s+"mat",this.scene),o.material.diffuseColor=re.Red(),o.parent=this._buttonMeshMapping[t].states[s].valueMesh||null,o.isVisible=!1,this._touchDots[s]=o}}})})}_setRootMesh(e){this.rootMesh=new q(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 s=this._buttonMeshMapping[t],r=this.layout.components[t];Object.keys(r.visualResponses).forEach(n=>{const o=r.visualResponses[n];let l=i.value;if(o.componentProperty==="xAxis"?l=i.axes.x:o.componentProperty==="yAxis"&&(l=i.axes.y),o.valueNodeProperty==="transform")this._lerpTransform(s.states[n],l,o.componentProperty!=="button");else{const h=s.states[n].valueMesh;h&&(h.isVisible=i.touched||i.pressed),this._touchDots[n]&&(this._touchDots[n].isVisible=i.touched||i.pressed)}})})}}const vE=[];class Js{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 s=[];if(i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id)switch(e.gamepad.id){case(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0):s.push("oculus-touch-v2");break}const r=s.indexOf("windows-mixed-reality");if(r!==-1&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const n=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,o=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return n.call(this,s,e,t).catch(()=>o.call(this,s,e,t))}else return this._LoadProfilesFromAvailableControllers(s,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=Z.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){vE.forEach(e=>{e.meshes.forEach(t=>{t.dispose(!1,!0)})}),vE.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(s=>{for(let r=0;r(this._ProfileLoadingPromises[s]||(this._ProfileLoadingPromises[s]=Z.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${s}/profile.json`,!1).then(r=>JSON.parse(r))),this._ProfileLoadingPromises[s])).then(s=>new g5(i,t,s,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:vE))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew kp(e,a.gamepad,a.handedness));Js.DefaultFallbacks();let x5=0;class T5{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new T,this._disposed=!1,this.onDisposeObservable=new K,this.onMeshLoadedObservable=new K,this.onMotionControllerInitObservable=new K,this._uniqueId=`controller-${x5++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Ft(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new ae,this.inputSource.gripSpace&&(this.grip=new Ft(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new ae),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&this.inputSource.targetRayMode==="tracked-pointer"&&Js.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(s=>{this.motionController=s,this.onMotionControllerInitObservable.notifyObservers(s),!this._options.doNotLoadControllerMesh&&!this.motionController._doNotLoadControllerMesh&&this.motionController.loadModel().then(r=>{var n;r&&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&&((n=this.motionController)==null||n.dispose())})},()=>{Z.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;T.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const n=r.transform.position;this.pointer.position.set(n.x,n.y,n.z).scaleInPlace(s.worldScalingFactor);const o=r.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(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const o=n.transform.position,l=n.transform.orientation;this.grip.position.set(o.x,o.y,o.z).scaleInPlace(s.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(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class E5{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new K,this.onControllerRemovedObservable=new K,this._onInputSourcesChange=s=>{this._addAndRemoveControllers(s.added,s.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(s=>s.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(s=>{s.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(s=>{this.controllers.forEach(r=>{r.updateFromXRFrame(s,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)})}),this._options.customControllersRepositoryURL&&(Js.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Js.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Js.UseOnlineRepository)try{Js.UpdateProfilesList().catch(()=>{Js.UseOnlineRepository=!1})}catch{Js.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map(n=>n.inputSource);for(const n of e)if(i.indexOf(n)===-1){const o=new T5(this.xrSessionManager.scene,n,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(o),this.onControllerAddedObservable.notifyObservers(o)}const s=[],r=[];this.controllers.forEach(n=>{t.indexOf(n.inputSource)===-1?s.push(n):r.push(n)}),this.controllers=s,r.forEach(n=>{this.onControllerRemovedObservable.notifyObservers(n),n.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(),Js.ClearControllerCache()}}class Uo extends nr{constructor(e,t){super(e),this._options=t,this._attachController=i=>{if(this._controllers[i.uniqueId])return;const{laserPointer:s,selectionMesh:r}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&i.grip?i.grip:i.pointer);switch(this._controllers[i.uniqueId]={xrController:i,laserPointer:s,selectionMesh:r,meshUnderPointer:null,pick:null,tmpRay:new Ct(new T,new T),disabledByNearInteraction:!1,id:Uo._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 T,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new re(.9,.9,.9),this.laserPointerDefaultColor=new re(.7,.7,.7),this.selectionMeshDefaultColor=new re(.8,.8,.8),this.selectionMeshPickedColor=new re(.3,.3,1),this._identityMatrix=L.Identity(),this._screenCoordinatesRef=T.Zero(),this._viewportRef=new da(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 Ct(new T,new T),disabledByNearInteraction:!1,id:Uo._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 s;if(i.xrController)s=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)s=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay);else return;if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&s){const h=this._xrSessionManager.scene,c=this._options.xrInput.xrCamera;c&&(c.viewport.toGlobalToRef(h.getEngine().getRenderWidth()/c.rigCameras.length,h.getEngine().getRenderHeight(),this._viewportRef),T.ProjectToRef(s,this._identityMatrix,c.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&&(h.pointerX=this._screenCoordinatesRef.x,h.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const n=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);!r||!r.hit?i.pick=n:!n||!n.hit||r.distance{if(t.pick){if(this._augmentPointerInit(h,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))l&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,h)),l=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,h),l=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,h),n.isVisible=!1;else{const c=1-o/i;n.scaling.set(c,c,c)}else l=!1,o=0;this._scene.simulatePointerMove(t.pick,h),r=t.pick}}),this._options.renderingGroupId!==void 0&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&l&&(this._scene.simulatePointerUp(t.pick,h),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!(!t.pick||this._options.disablePointerUpOnTouchOut&&i)&&(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),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 s=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(n=>{if(n.changes.pressed){const o=n.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 zs,{pointerId:l.id,pointerType:"xr"}),l.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}})};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const s=n=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.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)})},r=n=>{this._xrSessionManager.onXRFrameObservable.addOnce(()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&n.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:r,selectstart:s},this._xrSessionManager.session.addEventListener("selectstart",s),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(T.Dot(e,t.direction)){const s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),!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 zs,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{Z.Warn("controller already detached.")}})}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Cs.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():kv("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new Ie("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():vu("gazeTracker",{diameter:.0035*3,thickness:.0025*3,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new Ie("targetMat",t);return n.specularColor=re.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,this._options.renderingGroupId!==void 0&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){var r;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;(r=e.pickedPoint)==null||r.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}}Uo._IdCounter=200;Uo.Name=Vt.POINTER_SELECTION;Uo.Version=1;qi.AddWebXRFeature(Uo.Name,(a,e)=>()=>new Uo(a,e),Uo.Version,!0);xr.prototype._projectOnTrianglesToRef=function(a,e,t,i,s,r){const n=W.Vector3[0],o=W.Vector3[1];let l=1/0;for(let h=this.indexStart;h{if(this._controllers[i.uniqueId])return;const{touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),o=this._generateVisualCue();switch(this._controllers[i.uniqueId]={xrController:i,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:s,touchCollisionMeshFunction:r,hydrateCollisionMeshFunction:n,currentAnimationState:Fn.DEHYDRATED,grabRay:new Ct(new T,new T),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Vo._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:h,touchCollisionMeshFunction:c,hydrateCollisionMeshFunction:u}=this._generateNewTouchPointMesh();this._controllers[i.uniqueId].touchCollisionMesh=h,this._controllers[i.uniqueId].touchCollisionMeshFunction=c,this._controllers[i.uniqueId].hydrateCollisionMeshFunction=u,this._controllers[i.uniqueId].pickedPointVisualCue=this._generateVisualCue()}}),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&i.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=i.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=i.uniqueId),i.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(i);case"gaze":return null;case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new re(.8,.8,.8),this.selectionMeshPickedColor=new re(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,this._options.nearInteractionControllerMode===void 0&&(this._options.nearInteractionControllerMode=$h.CENTERED_IN_FRONT),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 Fn.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Fn.HOVER)break;case Fn.HOVER:if(e.touchCollisionMeshFunction(!0),t===Fn.TOUCH)break}else switch(e.currentAnimationState){case Fn.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Fn.HOVER)break;case Fn.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Fn.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(W.Vector3[0]),s.grabRay.direction.copyFrom(W.Vector3[0]),this._options.nearInteractionControllerMode===$h.CENTERED_IN_FRONT&&!((r=s.xrController)!=null&&r.inputSource.hand)&&(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var l;const i=this._controllers[t],s=(l=i.xrController)==null?void 0:l.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad)){i.pick=null;return}if(i.hoverInteraction=!1,i.nearInteraction=!1,i.xrController){if(s){const h=s.get("index-finger-tip");if(h){const c=e.getJointPose(h,this._xrSessionManager.referenceSpace);if(c&&c.transform){const u=this._scene.useRightHandedSystem?1:-1;W.Vector3[0].set(c.transform.position.x,c.transform.position.y,c.transform.position.z*u),W.Quaternion[0].set(c.transform.orientation.x,c.transform.orientation.y,c.transform.orientation.z*u,c.transform.orientation.w*u),this._processTouchPoint(t,W.Vector3[0],W.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==$h.DISABLED){let h=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===$h.CENTERED_ON_CONTROLLER&&(h=i.xrController.grip),this._processTouchPoint(t,h.position,h.rotationQuaternion)}}else return;const r=(h,c)=>{let u=null;return!c||!c.hit?u=h:!h||!h.hit||c.distance{let c=new zs,u=!1;const d=h&&h.pickedPoint&&h.hit;return h!=null&&h.pickedPoint&&(u=h.pickedPoint.x===0&&h.pickedPoint.y===0&&h.pickedPoint.z===0),d&&!u&&(c=h),c};if(!i.grabInteraction){let h=null,c=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(c=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,f=>this._nearInteractionPredicate(f)));const u=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,f=>this._nearInteractionPredicate(f)),d=r(u,c);if(d&&d.hit&&(h=n(d),h.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let f=null;const m=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(f=this._pickWithSphere(i,m,this._utilityLayerScene,S=>this._nearPickPredicate(S)));const _=this._pickWithSphere(i,m,this._scene,S=>this._nearPickPredicate(S)),x=r(_,f),E=n(x);E.hit&&(h=E,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=h,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=Fn.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=Fn.TOUCH:i.hoverInteraction&&(o=Fn.HOVER),this._handleTransitionAnimation(i,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Cs.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Cs.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Go("nearInteraction",{diameter:.0035*3*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=ae.Identity();const i=new Ie("targetMat",e);return i.specularColor=re.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return this._farInteractionFeature?this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e):!0}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{!this._options.enableNearInteractionOnAllControllers&&e.uniqueId!==this._attachedController||!t.xrController||!t.xrController.inputSource.hand&&(!this._options.nearInteractionControllerMode||!t.xrController.inputSource.gamepad)||(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))});const s=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):r&&!this._options.enableNearInteractionOnAllControllers&&!this._options.disableSwitchOnClick&&(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const r=n=>{t.squeezeComponent=n.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}):(t.selectionComponent=n.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(o=>{if(o.changes.pressed){const l=o.changes.pressed.current;s(l)}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const r=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)},n=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:n,selectstart:r},this._xrSessionManager.session.addEventListener("selectstart",r),this._xrSessionManager.session.addEventListener("selectend",n)}}_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 s=t.eventListeners&&t.eventListeners[i];s&&this._xrSessionManager.session.removeEventListener(i,s)}),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 zs,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||Cs.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Go("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:ss.ParseFromSnippetAsync("8RUNKL#3",t).then(N=>{i.material=N});const s=new TV;s.setEasingMode(kr.EASINGMODE_EASEINOUT);const r=new T(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new T(n,n,n).scaleInPlace(e),l=this._controllerPickRadius*(7/6),h=new T(l,l,l).scaleInPlace(e),c=this._controllerPickRadius*(4/5),u=new T(c,c,c).scaleInPlace(e),d=this._controllerPickRadius*(3/2),f=new T(d,d,d).scaleInPlace(e),m=[{frame:0,value:r},{frame:10,value:f},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:u},{frame:18,value:r}],x=[{frame:0,value:T.ZeroReadOnly},{frame:12,value:h},{frame:15,value:r}],E=[{frame:0,value:r},{frame:10,value:T.ZeroReadOnly},{frame:15,value:T.ZeroReadOnly}],S=new te("touch","scaling",60,te.ANIMATIONTYPE_VECTOR3,te.ANIMATIONLOOPMODE_CONSTANT),C=new te("release","scaling",60,te.ANIMATIONTYPE_VECTOR3,te.ANIMATIONLOOPMODE_CONSTANT),y=new te("hydrate","scaling",60,te.ANIMATIONTYPE_VECTOR3,te.ANIMATIONLOOPMODE_CONSTANT),A=new te("dehydrate","scaling",60,te.ANIMATIONTYPE_VECTOR3,te.ANIMATIONLOOPMODE_CONSTANT);return S.setEasingFunction(s),C.setEasingFunction(s),y.setEasingFunction(s),A.setEasingFunction(s),S.setKeys(m),C.setKeys(_),y.setKeys(x),A.setKeys(E),{touchCollisionMesh:i,touchCollisionMeshFunction:N=>{const k=N?S:C;t.beginDirectAnimation(i,[k],0,18,!1,1)},hydrateCollisionMeshFunction:N=>{const k=N?y:A;N&&(i.isVisible=!0),t.beginDirectAnimation(i,[k],0,15,!1,1,()=>{N||(i.isVisible=!1)})}}}_pickWithSphere(e,t,i,s){const r=new zs;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=gl.CreateFromCenterAndRadius(n,t);for(let l=0;ld&&(u=0,l.copyFrom(t.center)),u!==-1&&u()=>new Vo(a,e),Vo.Version,!0);class S5{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class nC{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new K,this._onSessionGranted=s=>{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 Z.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 s=t.sessionMode||"immersive-vr",r=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 h=document.createElement("button");h.className="babylonVRicon",h.title=`${s} - ${r}`,this._buttons.push(new S5(h,s,r)),this._buttons[this._buttons.length-1].update=function(c){this.element.style.display=c===null||c===this?"":"none",h.className="babylonVRicon"+(c===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(r=>e.sessionManager.isSessionSupportedAsync(r.sessionMode));e.onStateChangedObservable.add(r=>{r==Bs.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((r,n)=>{r?(this.overlay.appendChild(this._buttons[n].element),this._buttons[n].element.onclick=this._enterXRWithButtonIndex.bind(this,n)):Z.Warn(`Session mode "${this._buttons[n].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){const s=new nC(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Bs.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Bs.NOT_IN_XR)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,s=i.title;i.title="Error entering XR session : "+s,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 Kh;(function(a){a[a.INIT=0]="INIT",a[a.STARTED=1]="STARTED",a[a.ENDED=2]="ENDED"})(Kh||(Kh={}));function Lm(a){let e=0;const t=Date.now();a.observableParameters=a.observableParameters??{};const i=a.contextObservable.add(s=>{const r=Date.now();e=r-t;const n={startTime:t,currentTime:r,deltaTime:e,completeRate:e/a.timeout,payload:s};a.onTick&&a.onTick(n),a.breakCondition&&a.breakCondition()&&(a.contextObservable.remove(i),a.onAborted&&a.onAborted(n)),e>=a.timeout&&(a.contextObservable.remove(i),a.onEnded&&a.onEnded(n))},a.observableParameters.mask,a.observableParameters.insertFirst,a.observableParameters.scope);return i}class v5{constructor(e){this.onEachCountObservable=new K,this.onTimerAbortedObservable=new K,this.onTimerEndedObservable=new K,this.onStateChangedObservable=new K,this._observer=null,this._breakOnNextTick=!1,this._tick=t=>{const i=Date.now();this._timer=i-this._startTime;const s={startTime:this._startTime,currentTime:i,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:t},r=this._breakOnNextTick||this._breakCondition(s);r||this._timer>=this._timeToEnd?this._stop(s,r):this.onEachCountObservable.notifyObservers(s)},this._setState(Kh.INIT),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===Kh.STARTED)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(Kh.STARTED)}stop(){this._state===Kh.STARTED&&(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(Kh.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class uu extends nr{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 Oe(1,1,1,1),this._tmpRay=new Ct(new T,new T),this._tmpVector=new T,this._tmpQuaternion=new ae,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 K,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new K,this.onAfterCameraTeleportRotation=new K,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 s=this._controllers[i.uniqueId];if(s.xrController.inputSource.targetRayMode==="tracked-pointer"&&s.xrController.inputSource.gamepad){const r=()=>{if(i.motionController){const n=i.motionController.getComponentOfType($n.THUMBSTICK_TYPE)||i.motionController.getComponentOfType($n.TOUCHPAD_TYPE);if(!n||this._options.useMainComponentOnly){const o=i.motionController.getMainComponent();if(!o)return;s.teleportationState.mainComponentUsed=!0,s.teleportationComponent=o,s.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{if(!this.teleportationEnabled)return;const l=()=>{s.teleportationState.forward=!0,s.teleportationState.initialHit=!1,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const h=this._options.timeToTeleport||3e3;Lm({timeout:h,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!o.pressed,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};o.changes.pressed&&(o.changes.pressed.current?this._options.timeToTeleportStart?Lm({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{o.pressed&&l()}}):l():(s.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else s.teleportationComponent=n,s.onAxisChangedObserver=n.onAxisValueChangedObservable.add(o=>{if(o.y<=.7&&s.teleportationState.backwards&&(s.teleportationState.backwards=!1),o.y>.7&&!s.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!s.teleportationState.backwards){s.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,ae.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,h=>this._floorMeshes.indexOf(h)!==-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&&!s.teleportationState.rotating&&this.teleportationEnabled&&(s.teleportationState.forward=!0,this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),o.x){if(s.teleportationState.forward)this._currentTeleportationControllerId===s.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{s.teleportationState.currentRotation=Math.atan2(o.x,o.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):s.teleportationState.currentRotation=0);else if(!s.teleportationState.rotating&&Math.abs(o.x)>.7){s.teleportationState.rotating=!0;const l=this.rotationAngle*(o.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(l),ae.FromEulerAngles(0,l,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else s.teleportationState.rotating=!1;o.x===0&&o.y===0&&(s.teleportationState.blocked&&(s.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),s.teleportationState.forward&&this._teleportForward(i.uniqueId))})}};i.motionController?r():i.onMotionControllerInitObservable.addOnce(()=>{r()})}else{s.teleportationState.mainComponentUsed=!0;let r=!1;const n=()=>{this._currentTeleportationControllerId=s.xrController.uniqueId,s.teleportationState.forward=!0,s.teleportationState.initialHit=!1,s.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,s.teleportationState.currentRotation=0;const o=this._options.timeToTeleport||3e3;Lm({timeout:o,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&s.teleportationState.forward&&this._teleportForward(i.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add(o=>{o.type===Ke.POINTERDOWN?(r=!1,this._options.timeToTeleportStart?Lm({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===s.xrController.uniqueId&&n()},breakCondition:()=>r?(r=!1,!0):!1}):n()):o.type===Ke.POINTERUP&&(r=!0,s.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 Oe(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 s;this.parabolicCheckRadius=this.parabolicCheckRadius/i.previousScaleFactor*i.newScaleFactor,(s=this._options.teleportationTargetMesh)==null||s.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(c)||this._options.blockAllPickableMeshes&&c.isPickable||this._options.pickBlockerMeshes&&this._options.pickBlockerMeshes.indexOf(c)!==-1)return!0;const u=this._floorMeshes.indexOf(c);return u===-1?!1:this._floorMeshes[u].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=u&&u.pickedMesh&&this._floorMeshes.indexOf(u.pickedMesh)!==-1;if(u&&u.pickedMesh&&!d){if(r.teleportationState.mainComponentUsed&&!r.teleportationState.initialHit){r.teleportationState.forward=!1;return}r.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,o),this._showParabolicPath(u);return}else u&&u.pickedPoint&&(r.teleportationState.initialHit=!0,r.teleportationState.blocked=!1,n=!0,this._setTargetMeshPosition(u),this._setTargetMeshVisibility(!0,!1,o),this._showParabolicPath(u))}this._setTargetMeshVisibility(n,!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||Cs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Lv("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const n=new Bp("teleportationPlaneDynamicTexture",512,e,!0);n.hasAlpha=!0;const o=n.getContext(),l=512/2,h=512/2,c=200;o.beginPath(),o.arc(l,h,c,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(),n.update();const u=new Ie("teleportationPlaneMaterial",e);u.diffuseTexture=n,t.material=u}const i=vu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const r=new te("animationInnerCircle","position.y",30,te.ANIMATIONTYPE_FLOAT,te.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new KI;o.setEasingMode(kr.EASINGMODE_EASEINOUT),r.setEasingFunction(o),i.animations=[],i.animations.push(r),e.beginAnimation(i,0,60,!0)}const s=kv("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Vr.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const r=new Ie("torusConsMat",e);r.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,r.disableLighting?r.emissiveColor=new re(.3,.3,1):r.diffuseColor=new re(.3,.3,1),r.alpha=.9,i.material=r,s.material=r,this._teleportationRingMaterial=r}this._options.renderingGroupId!==void 0&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.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,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach(n=>{const o=T.DistanceSquared(n,e);o<=r&&o{s.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||Cs.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=yo.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Yv("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},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,ae.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)}}}}uu.Name=Vt.TELEPORTATION;uu.Version=1;qi.AddWebXRFeature(uu.Name,(a,e)=>()=>new uu(a,e),uu.Version,!0);class aC{constructor(){}static CreateAsync(e,t={}){const i=new aC;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&(typeof t.optionalFeatures=="boolean"?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new nC(e,s)}return rC.CreateAsync(e).then(s=>{if(i.baseExperience=s,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new E5(s.sessionManager,s.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const r={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(Uo.Name,t.useStablePlugins?"stable":"latest",r),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(uu.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(Vo.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(ci.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(s=>(U.Error("Error initializing XR"),U.Error(s),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}Ue.prototype.createDefaultLight=function(a=!1){if(a&&this.lights)for(let e=0;el.isVisible&&l.isEnabled()),s=i.max.subtract(i.min),r=i.min.add(s.scale(.5));let n,o=s.length()*1.5;if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),a){const l=new Ii("default camera",-(Math.PI/2),Math.PI/2,o,r,this);l.lowerRadiusLimit=o*.01,l.wheelPrecision=100/o,n=l}else{const l=new ln("default camera",new T(r.x,r.y,-o),this);l.setTarget(r),n=l}n.minZ=o*.01,n.maxZ=o*1e3,n.speed=o*.2,this.activeCamera=n,t&&n.attachControl()}};Ue.prototype.createDefaultCameraOrLight=function(a=!1,e=!1,t=!1){this.createDefaultLight(e),this.createDefaultCamera(a,e,t)};Ue.prototype.createDefaultSkybox=function(a,e=!1,t=1e3,i=0,s=!0){if(!a)return U.Warn("Can not create default skybox without environment texture."),null;s&&a&&(this.environmentTexture=a);const r=zv("hdrSkyBox",{size:t},this);if(e){const n=new Xe("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=X.SKYBOX_MODE),n.microSurface=1-i,n.disableLighting=!0,n.twoSidedLighting=!0,r.material=n}else{const n=new Ie("skyBox",this);n.backFaceCulling=!1,n.reflectionTexture=a.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=X.SKYBOX_MODE),n.disableLighting=!0,r.material=n}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r};Ue.prototype.createDefaultEnvironment=function(a){return dc?new dc(a,this):null};Ue.prototype.createDefaultVRExperience=function(a={}){return new Cu(this,a)};Ue.prototype.createDefaultXRExperienceAsync=function(a={}){return aC.CreateAsync(this,a).then(e=>e)};function $0(a){for(;a.firstChild;)a.removeChild(a.firstChild);a.srcObject=null,a.src="",a.removeAttribute("src")}class vl extends X{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new K),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e==null?void 0:e.message):U.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){U.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,s=!1,r=!1,n=X.TRILINEAR_SAMPLINGMODE,o={},l,h=5){var u;super(null,i,!s,r),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||Z.IsExponentOfTwo(this.video.videoWidth)&&Z.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=X.WRAP_ADDRESSMODE,this.wrapV=X.WRAP_ADDRESSMODE):(this.wrapU=X.CLAMP_ADDRESSMODE,this.wrapV=X.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 d=this.video.onplaying,f=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=f,this.video.onplaying=d,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||!c)?(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0):c&&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 Z.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return typeof e=="string"?(Z.SetCorsBehavior(e,t),t.src=e):(Z.SetCorsBehavior(e[0],t),e.forEach(i=>{const s=document.createElement("source");s.src=i,t.appendChild(s)})),this.onDisposeObservable.addOnce(()=>{$0(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 vl(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,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(r.mozSrcObject!==void 0?r.mozSrcObject=t:typeof r.srcObject=="object"?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise(n=>{const o=()=>{const l=new vl("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&l.onDisposeObservable.addOnce(()=>{r.remove()}),l.onDisposeObservable.addOnce(()=>{$0(r)}),n(l),r.removeEventListener("playing",o)};r.addEventListener("playing",o),r.play()})}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce(()=>{r.getTracks().forEach(o=>{o.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then(function(n){t&&t(n)}).catch(function(n){U.Error(n.name)})}}v([O("settings")],vl.prototype,"_settings",void 0);v([O("src")],vl.prototype,"_currentSrc",void 0);v([O()],vl.prototype,"isVideo",void 0);X._CreateVideoTexture=(a,e,t,i=!1,s=!1,r=X.TRILINEAR_SAMPLINGMODE,n={},o,l=5)=>new vl(a,e,t,i,s,r,n,o,l);H("BABYLON.VideoTexture",vl);class oC extends an{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new vl((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,X.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(n=>{var o;((o=n.pickInfo)==null?void 0:o.pickedMesh)===this.mesh&&this._texture.video.play()},Ke.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}oC.MODE_MONOSCOPIC=an.MODE_MONOSCOPIC;oC.MODE_TOPBOTTOM=an.MODE_TOPBOTTOM;oC.MODE_SIDEBYSIDE=an.MODE_SIDEBYSIDE;const C5="glowMapGenerationPixelShader",b5=`#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 +}`;j.ShadersStore[y5]=A5;class xa{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}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 s=0;s{this.onBeforeRenderMainTextureObservable.notifyObservers(this);let r;const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{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 S;const s=this._scene.getEngine(),r=e.getMesh(),n=(S=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:S[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[P.PositionKind];let c=!1,u=!1;if(o){const C=o.needAlphaTesting(),y=o.getAlphaTestTexture(),A=y&&y.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);y&&(C||A)&&(l.push("#define DIFFUSE"),r.isVerticesDataPresent(P.UV2Kind)&&y.coordinatesIndex===1?(l.push("#define DIFFUSEUV2"),u=!0):r.isVerticesDataPresent(P.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),C&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),y.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const I=o.opacityTexture;I&&(l.push("#define OPACITY"),r.isVerticesDataPresent(P.UV2Kind)&&I.coordinatesIndex===1?(l.push("#define OPACITYUV2"),u=!0):r.isVerticesDataPresent(P.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),r.isVerticesDataPresent(P.UV2Kind)&&i.coordinatesIndex===1?(l.push("#define EMISSIVEUV2"),u=!0):r.isVerticesDataPresent(P.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(P.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==pe.MATERIAL_OPAQUE&&(h.push(P.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(P.UVKind),l.push("#define UV1")),u&&(h.push(P.UV2Kind),l.push("#define UV2"));const d=new gc;if(r.useBones&&r.computeBonesUsingShaders){h.push(P.MatricesIndicesKind),h.push(P.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(P.MatricesIndicesExtraKind),h.push(P.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const C=r.skeleton;C&&C.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(C?C.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else l.push("#define NUM_BONE_INFLUENCERS 0");const f=r.morphTargetManager;let m=0;f&&(m=f.numMaxInfluencers||f.numInfluencers,m>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+m),f.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),o_(h,r,m))),t&&(l.push("#define INSTANCES"),bh(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),vh(o,this._scene,l),this._addCustomEffectDefines(l);const _=e._getDrawWrapper(void 0,!0),x=_.defines,E=l.join(` +`);if(x!==E){const C=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Va(C),_.setEffect(this._engine.createEffect("glowMapGeneration",h,C,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],E,d,void 0,void 0,{maxSimultaneousMorphTargets:m}),E)}return _.effect.isReady()}render(){for(let n=0;nS.setMatrix("world",y))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[P.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 Z.Instantiate(e.customType).Parse(e,t,i)}}xa._SceneComponentInitialization=a=>{throw ot("EffectLayerSceneComponent")};v([O()],xa.prototype,"name",void 0);v([tv()],xa.prototype,"neutralColor",void 0);v([O()],xa.prototype,"isEnabled",void 0);v([SU()],xa.prototype,"camera",null);v([O()],xa.prototype,"renderingGroupId",null);v([O()],xa.prototype,"disableBoundingBoxesFromEffectLayer",void 0);xs.AddParser(ve.NAME_EFFECTLAYER,(a,e,t,i)=>{if(a.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let s=0;s{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,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const n=r._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const o of e.subMeshes)if(!r.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 s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===Ve.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==Ve.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const r=s._mainTexture;r._shouldRender()&&(this.scene.incrementRenderId(),r.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=a._getComponent(ve.NAME_EFFECTLAYER);e||(e=new R5(a),a._addComponent(e))};const I5="glowMapMergePixelShader",P5=`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 +}`;j.ShadersStore[I5]=P5;const M5="glowMapMergeVertexShader",O5=`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 +}`;j.ShadersStore[M5]=O5;xs.prototype.getGlowLayerByName=function(a){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===a&&this.effectLayers[t].getEffectName()===ua.EffectName)return this.effectLayers[t];return null};class ua extends xa{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 Oe(0,0,0,1),this._options={mainTextureRatio:ua.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})}getEffectName(){return ua.EffectName}_createMergeEffect(){let e=`#define EMISSIVE +`;return this._options.ldrMerge&&(e+=`#define LDR +`),this._engine.createEffect("glowMapMerge",[P.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?on(e,this._maxSize):e,t=this._engine.needPOTTextures?on(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture1=new Yi("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=X.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=X.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(X.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const s=Math.floor(e/2),r=Math.floor(t/2);this._blurTexture2=new Yi("GlowLayerBlurRTT2",{width:s,height:r},this._scene,!1,!0,i),this._blurTexture2.wrapU=X.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=X.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(X.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new Hs("GlowLayerHBP1",new ce(1,0),n,{width:e,height:t},null,X.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 Hs("GlowLayerVBP1",new ce(0,1),n,{width:e,height:t},null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Hs("GlowLayerHBP2",new ce(1,0),n,{width:s,height:r},null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(o=>{o.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new Hs("GlowLayerVBP2",new ce(0,1),n,{width:s,height:r},null,X.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(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}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(pe.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){const r=i.emissiveIntensity??1;s*=r,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,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=Pe.Serialize(this);e.customType="BABYLON.GlowLayer";let t;if(e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew ua(e.name,t,e.options),e,t,i);let r;for(r=0;r{h.setFloat2("screenSize",this.width,this.height),h.setVector2("direction",this.direction),h.setFloat("blurWidth",this.kernel)})}}class Kr extends xa{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),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new K,this.onAfterBlurObservable=new K,this._instanceGlowingMeshStencilReference=Kr.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Kr.NeutralColor,this._engine.isStencilEnable||U.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,...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}getEffectName(){return Kr.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[P.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE +`:void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?on(e,this._maxSize):e,t=this._engine.needPOTTextures?on(t,this._maxSize):t;let i=0;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new Yi("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=X.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=X.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(X.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new uo("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new K0("HighlightLayerHBP",new ce(1,0),this._options.blurHorizontalSize,1,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new K0("HighlightLayerVBP",new ce(0,1),this._options.blurVerticalSize,1,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(s=>{s.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Hs("HighlightLayerHBP",new ce(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(s=>{s.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new Hs("HighlightLayerVBP",new ce(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);const s=this._blurTexture.renderTarget;s&&(this._scene.postProcessManager.directRender(this._postProcesses,s,!0),this._engine.unBindFramebuffer(s,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(s=>{s.autoClear=!1})}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_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(pe.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(pe.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 s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.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(s=>{i.stencilState=s.getEngine().getStencilBuffer(),s.getEngine().setStencilBuffer(!1)}),i.afterRender=e.onAfterRenderObservable.add(s=>{s.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 s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(r=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[r.uniqueId]?this._defaultStencilReference(r):r.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(r=>{this.isEnabled&&this._defaultStencilReference(r)}),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(Kr.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=Pe.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 s=Pe.Parse(()=>new Kr(e.name,t,e.options),e,t,i);let r;for(r=0;r +#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 +}`;j.ShadersStore[w5]=F5;const L5="layerVertexShader",B5=`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 +}`;j.ShadersStore[L5]=B5;class lC{static AddFlare(e,t,i,s,r){return new lC(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new re(1,1,1),this.texture=s?new X(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Ws(n),this._drawWrapper.effect=n.createEffect("lensFlare",[P.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}const U5="lensFlarePixelShader",V5=`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 +}`;j.ShadersStore[U5]=V5;const k5="lensFlareVertexShader",G5=`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 +}`;j.ShadersStore[k5]=G5;class Pu{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||We.LastCreatedScene,Pu._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=n=>i.activeCamera&&n.material&&n.isVisible&&n.isEnabled()&&n.isBlocker&&(n.layerMask&i.activeCamera.layerMask)!=0;const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[P.PositionKind]=new P(s,r,P.PositionKind,!1,!1,2),this._createIndexBuffer()}_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=T.Project(t,L.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=T.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)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 s,r;this._positionXi.x+i.width-this.borderLimit?s=this._positionX-i.x-i.width+this.borderLimit:s=0,this._positionYi.y+i.height-this.borderLimit?r=this._positionY-i.y-i.height+this.borderLimit:r=0;let n=s>r?s:r;n-=this.viewportBorder,n>this.borderLimit&&(n=this.borderLimit);let o=1-Ne.Clamp(n/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,h=i.y+i.height/2,c=l-this._positionX,u=h-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d{throw ot("LensFlareSystemSceneComponent")};xs.AddParser(ve.NAME_LENSFLARESYSTEM,(a,e,t,i)=>{if(a.lensFlareSystems!==void 0&&a.lensFlareSystems!==null){t.lensFlareSystems||(t.lensFlareSystems=[]);for(let s=0,r=a.lensFlareSystems.length;s{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;Z.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Z.EndPerformanceCounter("Lens flares",t.length>0)}}}Pu._SceneComponentInitialization=a=>{let e=a._getComponent(ve.NAME_LENSFLARESYSTEM);e||(e=new z5(a),a._addComponent(e))};const W5="bayerDitherFunctions",H5=`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);} +`;j.IncludesShadersStore[W5]=H5;const X5="shadowMapFragmentExtraDeclaration",Y5=`#if SM_FLOAT==0 +#include +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include +uniform float 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 +`;j.IncludesShadersStore[X5]=Y5;const $5="shadowMapFragment",K5=`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;`;j.IncludesShadersStore[$5]=K5;const j5="shadowMapPixelShader",q5=`#include +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEXTURE +float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; +#endif +#endif +#include +}`;j.ShadersStore[j5]=q5;const Q5="sceneVertexDeclaration",Z5=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;j.IncludesShadersStore[Q5]=Z5;const J5="meshVertexDeclaration",eY=`uniform mat4 world;uniform float visibility; +`;j.IncludesShadersStore[J5]=eY;const tY="shadowMapVertexDeclaration",iY=`#include +#include +`;j.IncludesShadersStore[tY]=iY;const sY="shadowMapUboDeclaration",rY=`layout(std140,column_major) uniform; +#include +#include +`;j.IncludesShadersStore[sY]=rY;const nY="shadowMapVertexExtraDeclaration",aY=`#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 +`;j.IncludesShadersStore[nY]=aY;const oY="shadowMapVertexNormalBias",lY=`#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 +`;j.IncludesShadersStore[oY]=lY;const hY="shadowMapVertexMetric",cY=`#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 +`;j.IncludesShadersStore[hY]=cY;const uY="shadowMapVertexShader",dY=`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 +}`;j.ShadersStore[uY]=dY;const fY="depthBoxBlurPixelShader",pY=`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)));}`;j.ShadersStore[fY]=pY;const _Y="shadowMapFragmentSoftTransparentShadow",mY=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;j.IncludesShadersStore[_Y]=mY;class lt{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===lt.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===lt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===lt.FILTER_PCF||e===lt.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===lt.FILTER_PCF||e===lt.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===lt.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(lt.FILTER_POISSONSAMPLING);!e&&this.filter!==lt.FILTER_POISSONSAMPLING||(this.filter=e?t:lt.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===lt.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(lt.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==lt.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:lt.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===lt.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(lt.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==lt.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:lt.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===lt.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(lt.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==lt.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:lt.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===lt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(lt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==lt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:lt.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===lt.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(lt.FILTER_PCF);!e&&this.filter!==lt.FILTER_PCF||(this.filter=e?t:lt.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===lt.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(lt.FILTER_PCSS);!e&&this.filter!==lt.FILTER_PCSS||(this.filter=e?t:lt.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 lt.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 s of e.getChildren())this.removeShadowCaster(s);return this}getLight(){return this._light}_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,s,r){this.onBeforeShadowMapRenderObservable=new K,this.onAfterShadowMapRenderObservable=new K,this.onBeforeShadowMapRenderMeshObservable=new K,this.onAfterShadowMapRenderMeshObservable=new K,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=lt.FILTER_NONE,this._filteringQuality=lt.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=T.Zero(),this._viewMatrix=L.Zero(),this._projectionMatrix=L.Zero(),this._transformMatrix=L.Zero(),this._cachedPosition=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=L.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.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}")`))),lt._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.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 Yi(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 Yi(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=X.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=X.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(X.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(s,r,n,o)=>this._renderForShadowMap(s,r,n,o),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var s;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),(s=e._debugPushGroup)==null||s.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(s=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=s,this._filter===lt.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 r,n;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===lt.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(r=e._debugPopGroup)==null||r.call(e,1);return}const s=this.getShadowMapForRendering();s&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,s.renderTarget,!0),e.unBindFramebuffer(s.renderTarget,!0),(n=e._debugPopGroup)==null||n.call(e,1))});const t=new Oe(0,0,0,0),i=new Oe(1,1,1,1);this._shadowMap.onClearObservable.add(s=>{this._filter===lt.FILTER_PCF?s.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?s.clear(t,!0,!0,!1):s.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(s=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=s.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let s=mr.MIN_RENDERINGGROUPS;s{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new Hs(this._light.name+"KernelBlurY",new ce(0,1),this.blurKernel,1,null,X.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 je(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,X.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),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,s){let r;if(s.length)for(r=0;r{s!==i&&!S?(i.getMeshUniformBuffer().bindToEffect(_,"Mesh"),i.transferToEffect(C)):(s.getMeshUniformBuffer().bindToEffect(_,"Mesh"),s.transferToEffect(S?C:E))}),this.forceBackFacesOnly&&n.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===lt.FILTER_NONE||this.filter===lt.FILTER_PCSS?this._shadowMap.updateSamplingMode(X.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(X.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s){e&&e(this);return}const r=s.renderList;if(!r){e&&e(this);return}const n=[];for(const h of r)n.push(...h.subMeshes);if(n.length===0){e&&e(this);return}let o=0;const l=()=>{var h;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(n[o],i.useInstances,((h=n[o].getMaterial())==null?void 0:h.needAlphaBlendingForMesh(n[o].getMesh()))??!1);)if(o++,o>=n.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,s){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 r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(P.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===yt.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s==null?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const o=e._getDrawWrapper(void 0,!0);let l=o.effect,h=o.defines;const c=[P.PositionKind],u=e.getMesh();this.normalBias&&u.isVerticesDataPresent(P.NormalKind)&&(c.push(P.NormalKind),n.push("#define NORMAL"),u.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const d=s.needAlphaTesting();if((d||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const S=s.alphaCutOff??lt.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),d&&n.push(`#define ALPHATESTVALUE ${S}${S%1===0?".":""}`),u.isVerticesDataPresent(P.UVKind)&&(c.push(P.UVKind),n.push("#define UV1")),u.isVerticesDataPresent(P.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(c.push(P.UV2Kind),n.push("#define UV2"))}const f=new gc;if(u.useBones&&u.computeBonesUsingShaders&&u.skeleton){c.push(P.MatricesIndicesKind),c.push(P.MatricesWeightsKind),u.numBoneInfluencers>4&&(c.push(P.MatricesIndicesExtraKind),c.push(P.MatricesWeightsExtraKind));const S=u.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+u.numBoneInfluencers),u.numBoneInfluencers>0&&f.addCPUSkinningFallback(0,u),S.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(S.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const m=u.morphTargetManager;let _=0;if(m&&(_=m.numMaxInfluencers||m.numInfluencers,_>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+_),m.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),o_(c,u,_))),vh(s,this._scene,n),t&&(n.push("#define INSTANCES"),bh(c),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const S of this.customShaderOptions.defines)n.indexOf(S)===-1&&n.push(S);const x=u.bakedVertexAnimationManager;t&&x&&x.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),c.push("bakedVertexAnimationSettingsInstanced"));const E=n.join(` +`);if(h!==E){h=E;let S="shadowMap";const C=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],y=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],A=["Scene","Mesh"];if(Va(C),this.customShaderOptions){if(S=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const R of this.customShaderOptions.attributes)c.indexOf(R)===-1&&c.push(R);if(this.customShaderOptions.uniforms)for(const R of this.customShaderOptions.uniforms)C.indexOf(R)===-1&&C.push(R);if(this.customShaderOptions.samplers)for(const R of this.customShaderOptions.samplers)y.indexOf(R)===-1&&y.push(R)}const I=this._scene.getEngine();l=I.createEffect(S,{attributes:c,uniformsNames:C,uniformBuffersNames:A,samplers:y,defines:E,fallbacks:f,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_}},I),o.setEffect(l,h)}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,s=this._light;!i.shadowsEnabled||!s.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===lt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===lt.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===lt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===lt.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),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();n&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===lt.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===lt.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),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),T.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(T.Dot(this._lightDirection,T.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),L.LookAtLHToRef(t,t.add(this._lightDirection),T.Up(),this._viewMatrix);const i=this.getShadowMap();if(i){const s=i.renderList;s&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,s)}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,s]=t.value;s===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 s=0;s{throw ot("ShadowGeneratorSceneComponent")};const gY="depthPixelShader",xY=`#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 +}`;j.ShadersStore[gY]=xY;const TY="pointCloudVertexDeclaration",EY=`#ifdef POINTSIZE +uniform float pointSize; +#endif +`;j.IncludesShadersStore[TY]=EY;const SY="depthVertexShader",vY=`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 +} +`;j.ShadersStore[SY]=vY;class Ec{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=X.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=t===0,this.isPacked?this.clearColor=new Oe(1,1,1,1):this.clearColor=new Oe(n?1e8:1,0,0,1),Ec._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,r!==X.NEAREST_SAMPLINGMODE&&(t===1&&!l._caps.textureFloatLinearFiltering&&(r=X.NEAREST_SAMPLINGMODE),t===2&&!l._caps.textureHalfFloatLinearFiltering&&(r=X.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Yi(o??"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=X.CLAMP_ADDRESSMODE,this._depthMap.wrapV=X.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(u=>{u.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var u;(u=l._debugPushGroup)==null||u.call(l,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var u;(u=l._debugPopGroup)==null||u.call(l,1)}),this._depthMap.customIsReadyFunction=(u,d,f)=>{if((f||d===0)&&u.subMeshes)for(let m=0;m{var R;const d=u.getRenderingMesh(),f=u.getEffectiveMesh(),m=this._scene,_=m.getEngine(),x=u.getMaterial();if(f._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!x||f.infiniteDistance||x.disableDepthWrite||u.verticesCount===0||u._renderId===m.getRenderId())return;const E=f._getWorldMatrixDeterminant()<0;let S=d.overrideMaterialSideOrientation??x.sideOrientation;E&&(S=S===0?1:0);const C=S===0;_.setState(x.backFaceCulling,0,!1,C,this.reverseCulling?!x.cullBackFaces:x.cullBackFaces);const y=d._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(y.mustReturn)return;const A=_.getCaps().instancedArrays&&(y.visibleInstances[u._id]!==null&&y.visibleInstances[u._id]!==void 0||d.hasThinInstances),I=this._camera||m.activeCamera;if(this.isReady(u,A)&&I){u._renderId=m.getRenderId();const N=(R=f._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:R[_.currentRenderPassId];let k=u._getDrawWrapper();!k&&N&&(k=N._getDrawWrapper());const B=I.mode===Ve.ORTHOGRAPHIC_CAMERA;if(!k)return;const Q=k.effect;_.enableEffect(k),A||d._bind(u,Q,x.fillMode),N?N.bindForSubMesh(f.getWorldMatrix(),f,u):(Q.setMatrix("viewProjection",m.getTransformMatrix()),Q.setMatrix("world",f.getWorldMatrix()),this._storeCameraSpaceZ&&Q.setMatrix("view",m.getViewMatrix()));let ne,de;if(B?(ne=!_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1,de=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1):(ne=_.useReverseDepthBuffer&&_.isNDCHalfZRange?I.minZ:_.isNDCHalfZRange?0:I.minZ,de=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:I.maxZ),Q.setFloat2("depthValues",ne,ne+de),!N){if(x.needAlphaTesting()){const ge=x.getAlphaTestTexture();ge&&(Q.setTexture("diffuseSampler",ge),Q.setMatrix("diffuseMatrix",ge.getTextureMatrix()))}if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){const ge=d.skeleton;if(ge.isUsingTextureForMatrices){const fe=ge.getTransformMatrixTexture(d);if(!fe)return;Q.setTexture("boneSampler",fe),Q.setFloat("boneTextureWidth",4*(ge.bones.length+1))}else Q.setMatrices("mBones",ge.getTransformMatrices(d))}pa(Q,x,m),Al(d,Q),d.morphTargetManager&&d.morphTargetManager.isUsingTextureForTargets&&d.morphTargetManager._bind(Q),x.pointsCloud&&Q.setFloat("pointSize",x.pointSize)}d._processRendering(f,u,Q,x.fillMode,y,A,(ge,fe)=>Q.setMatrix("world",fe))}};this._depthMap.customRenderFunction=(u,d,f,m)=>{let _;if(m.length)for(_=0;_4&&(h.push(P.MatricesIndicesExtraKind),h.push(P.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const x=e.getRenderingMesh().skeleton;x!=null&&x.isUsingTextureForMatrices&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),o_(h,s,u))),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),bh(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),vh(o,r,l);const d=e._getDrawWrapper(void 0,!0),f=d.defines,m=l.join(` +`);if(f!==m){const x=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Va(x),d.setEffect(i.createEffect("depth",h,x,["diffuseSampler","morphTargets","boneSampler"],m,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),m)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Ec._SceneComponentInitialization=a=>{throw ot("DepthRendererSceneComponent")};const CY="minmaxReduxPixelShader",bY=`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 +`;j.ShadersStore[CY]=bY;class yY{constructor(e){this.onAfterReductionPerformed=new K,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new ug(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new je("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?` +#define DEPTH_REDUX`:""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();n.onApply=((c,u)=>d=>{d.setTexture("sourceTexture",this._sourceTexture),d.setFloat2("texSize",c,u)})(o,l),this._reductionSteps.push(n);let h=1;for(;o>1||l>1;){o=Math.max(Math.round(o/2),1),l=Math.max(Math.round(l/2),1);const c=new je("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:o,height:l},null,1,r.getEngine(),!1,"#define "+(o==1&&l==1?"LAST":o==1||l==1?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(c.autoClear=!1,c.forceFullscreenViewport=s,c.onApply=((u,d)=>f=>{u==1||d==1?f.setInt2("texSize",u,d):f.setFloat2("texSize",u,d)})(o,l),this._reductionSteps.push(c),h++,o==1&&l==1){const u=(d,f,m)=>{const _=new Float32Array(4*d*f),x={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(m.inputTexture.texture,d,f,-1,0,_,!1),x.min=_[0],x.max=_[1],this.onAfterReductionPerformed.notifyObservers(x)}};c.onAfterRenderObservable.add(u(o,l,c))}}}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 hr.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 s=i.min,r=i.max;s>=r&&(s=0,r=1),(s!=this._minDistance||r!=this._maxDistance)&&this.setMinMaxDistance(s,r)}),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,s=i-t,r=this._minDistance,n=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+r*s,l=t+n*s,h=l-o,c=l/o;for(let u=0;u{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===lt.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!==lt.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.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 r=this._getCamera();if(!r)return;const n=this.getShadowMap();if(!n)return;const o=n.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===lt.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===lt.FILTER_PCSS){for(let l=0;lnew hr(s,r,void 0,n));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}}hr._FrustumCornersNDCSpace=[new T(-1,1,-1),new T(1,1,-1),new T(1,-1,-1),new T(-1,-1,-1),new T(-1,1,1),new T(1,1,1),new T(1,-1,1),new T(-1,-1,1)];hr.CLASSNAME="CascadedShadowGenerator";hr.DEFAULT_CASCADES_COUNT=4;hr.MIN_CASCADES_COUNT=2;hr.MAX_CASCADES_COUNT=4;hr._SceneComponentInitialization=a=>{throw ot("ShadowGeneratorSceneComponent")};xs.AddParser(ve.NAME_SHADOWGENERATOR,(a,e)=>{if(a.shadowGenerators!==void 0&&a.shadowGenerators!==null)for(let t=0,i=a.shadowGenerators.length;t{let e=a._getComponent(ve.NAME_SHADOWGENERATOR);e||(e=new IY(a),a._addComponent(e))};Qt.AddNodeConstructor("Light_Type_0",(a,e)=>()=>new mf(a,T.Zero(),e));class mf extends Tc{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 s=i.next();s.done!==!0;s=i.next())s.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return yt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new T(1,0,0);case 1:return new T(-1,0,0);case 2:return new T(0,-1,0);case 3:return new T(0,1,0);case 4:return new T(0,0,1);case 5:return new T(0,0,-1)}return T.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=this.shadowMinZ!==void 0?this.shadowMinZ:s.minZ,n=this.shadowMaxZ!==void 0?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;L.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,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([O()],mf.prototype,"shadowAngle",null);class ih{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const s=this._renderingCanvas.getBoundingClientRect(),r=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position=r==="fixed"?"fixed":"absolute",this._loadingDiv.style.left=s.left+"px",this._loadingDiv.style.top=s.top+"px",this._loadingDiv.style.width=s.width+"px",this._loadingDiv.style.height=s.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;ih.DefaultLogoUrl?i.src=ih.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 s=document.createElement("div");s.style.width="300px",s.style.gridColumn="1",s.style.gridRow="1",s.style.top="50%",s.style.left="50%",s.style.transform="translate(-50%, -50%)",s.style.position="absolute";const r=new Image;if(ih.DefaultSpinnerUrl?r.src=ih.DefaultSpinnerUrl:r.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",r.style.animation="spin1 0.75s infinite linear",r.style.webkitAnimation="spin1 0.75s infinite linear",r.style.transformOrigin="50% 50%",r.style.webkitTransformOrigin="50% 50%",!t){const n={w:16,h:18.5},o={w:30,h:30};i.style.width=`${n.w}vh`,i.style.height=`${n.h}vh`,i.style.left=`calc(50% - ${n.w/2}vh)`,i.style.top=`calc(50% - ${n.h/2}vh)`,r.style.width=`${o.w}vh`,r.style.height=`${o.h}vh`,r.style.left=`calc(50% - ${o.w/2}vh)`,r.style.top=`calc(50% - ${o.h/2}vh)`}s.appendChild(r),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(s),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)}}ih.DefaultLogoUrl="";ih.DefaultSpinnerUrl="";He.DefaultLoadingScreenFactory=a=>new ih(a);class Ih{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";const n=this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),o=this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),l=this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),h=this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),c=this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),u=this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r);return{front:n,back:o,left:l,right:h,up:c,down:u,size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),l=new Float32Array(o),h=n?Math.max(1,Math.round(s/4/e)):1,c=1/h,u=c*c,d=t[1].subtract(t[0]).scale(c/e),f=t[3].subtract(t[2]).scale(c/e),m=1/e;let _=0;for(let x=0;xMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const l=n/Math.PI;o=o*.5+.5;let h=Math.round(o*i);h<0?h=0:h>=i&&(h=i-1);let c=Math.round(l*s);c<0?c=0:c>=s&&(c=s-1);const u=s-c-1,d=t[u*i*3+h*3+0],f=t[u*i*3+h*3+1],m=t[u*i*3+h*3+2];return{r:d,g:f,b:m}}}Ih.FACE_LEFT=[new T(-1,-1,-1),new T(1,-1,-1),new T(-1,1,-1),new T(1,1,-1)];Ih.FACE_RIGHT=[new T(1,-1,1),new T(-1,-1,1),new T(1,1,1),new T(-1,1,1)];Ih.FACE_FRONT=[new T(1,-1,-1),new T(1,-1,1),new T(1,1,-1),new T(1,1,1)];Ih.FACE_BACK=[new T(-1,-1,1),new T(-1,-1,-1),new T(-1,1,1),new T(-1,1,-1)];Ih.FACE_DOWN=[new T(1,1,-1),new T(1,1,1),new T(-1,1,-1),new T(-1,1,1)];Ih.FACE_UP=[new T(-1,-1,-1),new T(-1,-1,1),new T(1,-1,-1),new T(1,-1,1)];class JE{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return Ih.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,l,h,c=t.dataPosition,u=0,d=0,f=0;const m=new ArrayBuffer(s*4),_=new Uint8Array(m),x=new ArrayBuffer(t.width*t.height*4*3),E=new Float32Array(x);for(;i>0;){if(r=e[c++],n=e[c++],o=e[c++],l=e[c++],r!=2||n!=2||o&128||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|l)!=s)throw"HDR Bad header format, wrong scan line width";for(u=0,f=0;f<4;f++)for(d=(f+1)*s;u128){if(h=r-128,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (run)";for(;h-- >0;)_[u++]=n}else{if(h=r,h==0||h>d-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=n,--h>0)for(let S=0;S0;){for(h=0;h +#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);}`;j.ShadersStore[OY]=DY;class tM{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=Ne.ILog2(t)+1,s=this._effectWrapper.effect,r=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();const n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);const o=[[new T(0,0,-1),new T(0,-1,0),new T(1,0,0)],[new T(0,0,1),new T(0,-1,0),new T(-1,0,0)],[new T(1,0,0),new T(0,0,1),new T(0,1,0)],[new T(1,0,0),new T(0,0,-1),new T(0,-1,0)],[new T(1,0,0),new T(0,-1,0),new T(0,0,1)],[new T(-1,0,0),new T(0,-1,0),new T(0,0,-1)]];s.setFloat("hdrScale",this.hdrScale),s.setFloat2("vFilteringInfo",e.getSize().width,i),s.setTexture("inputTexture",e);for(let c=0;c<6;c++){s.setVector3("up",o[c][0]),s.setVector3("right",o[c][1]),s.setVector3("front",o[c][2]);for(let u=0;u{this._effectRenderer=new Qg(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(U.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 oc extends Kt{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(L.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,s=!1,r=!0,n=!1,o=!1,l=null,h=null,c=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=T.Zero(),this.onLoadObservable=new K,e&&(this._coordinatesMode=X.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=L.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),l&&l()},this._onError=h,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=c,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Z.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(u=this.getScene())!=null&&u.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 s=r=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const n=JE.GetCubeMapTextureData(r,this._size,this._supersample);if(this._generateHarmonics){const c=ff.ConvertCubeMapToSphericalPolynomial(n);this.sphericalPolynomial=c}const o=[];let l=null,h=null;for(let c=0;c<6;c++){i===2?h=new Uint16Array(this._size*this._size*3):i===0&&(l=new Uint8Array(this._size*this._size*3));const u=n[oc._FacesMapping[c]];if(this.gammaSpace||h||l){for(let d=0;d255){const E=255/x;f*=E,m*=E,_*=E}l[d*3+0]=f,l[d*3+1]=m,l[d*3+2]=_}}h?o.push(h):l?o.push(l):o.push(u)}return o};if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const r=this._onLoad,n=new tM(e);this._onLoad=()=>{n.prefilter(this,r)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,s,null,this._onLoad,this._onError)}clone(){const e=new oc(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 s=null;return e.name&&!e.isRenderTarget&&(s=new oc(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=T.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=T.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}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}}oc._FacesMapping=["right","left","up","down","front","back"];H("BABYLON.HDRCubeTexture",oc);class lc{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 K,this._onDataLayoutChanged=new K,this._animationPropertiesOverride=null,this._scene=i||We.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=Pe.Clone(()=>new lc(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())),Pe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new lc(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 s=0;s0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Ps(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=We.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 Fo.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]}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 Fo(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 s of this._targets){if(i++,s.influence===0&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Fo.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(s),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=s.influence,this._supportsNormals=this._supportsNormals&&s.hasNormals,this._supportsTangents=this._supportsTangents&&s.hasTangents,this._supportsUVs=this._supportsUVs&&s.hasUVs;const r=s.getPositions();if(r){const n=r.length/3;if(this._vertexCount===0)this._vertexCount=n;else if(this._vertexCount!==n){U.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 s=0;s0)){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,s=new Float32Array(i*this._textureWidth*this._textureHeight*4);let r=0;for(let n=0;n-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 Fo(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(lc.Parse(s,t));return i}}Fo.EnableTextureStorage=!0;Fo.MaxActiveMorphTargetsInVertexAttributeMode=8;class NY{constructor(){this._hasHit=!1,this._hitNormal=T.Zero(),this._hitPoint=T.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 Tx extends NY{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=T.Zero(),this._rayToWorld=T.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=T.Distance(this._rayFromWorld,this._hitPoint)}reset(e=T.Zero(),t=T.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}let iM=class sM{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ot("CannonJSPlugin")}constructor(e,t=sM.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 T(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 s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});s.length&&this._physicsPlugin.removeJoint(s[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 s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}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){U.Warn("It was not possible to create a physics body for this object.");return}const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o]);e.physicsBody=new this.BJSCANNON.Body(r),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 s=r=>{if(!r.rotationQuaternion)return;const n=r.getPhysicsImpostor();if(n&&n.parent!==e&&r.parent){const l=r.getAbsolutePosition().subtract(r.parent.getAbsolutePosition()),h=r.rotationQuaternion.multiply(this._tmpQuaternion);n.physicsBody&&(this.removePhysicsBody(n),n.physicsBody=null),n.parent=e,n.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(n),new this.BJSCANNON.Vec3(l.x,l.y,l.z),new this.BJSCANNON.Quaternion(h.x,h.y,h.z,h.w)),e.physicsBody.mass+=n.getParam("mass")}r.getChildMeshes(!0).filter(o=>!!o.physicsImpostor).forEach(s)};t.filter(r=>!!r.physicsImpostor).forEach(s)}}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 s;const r=e.joint.jointData,n={pivotA:r.mainPivot?new this.BJSCANNON.Vec3().set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?new this.BJSCANNON.Vec3().set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?new this.BJSCANNON.Vec3().set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?new this.BJSCANNON.Vec3().set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case Fi.HingeJoint:case Fi.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case Fi.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case Fi.SpringJoint:{const o=r;s=new this.BJSCANNON.Spring(t,i,{restLength:o.length,stiffness:o.stiffness,damping:o.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case Fi.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case Fi.PointToPointJoint:case Fi.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce);break}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==Fi.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==Fi.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;si*1e3));d++);this.time+=s;const h=this.time%i/i,c=e,u=this.bodies;for(let d=0;d!==u.length;d++){const f=u[d];f.type!==t.Body.STATIC&&f.sleepState!==t.Body.SLEEPING?(f.position.vsub(f.previousPosition,c),c.scale(h,c),f.position.vadd(c,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))}}iM.DefaultPluginFactory=()=>new eS;class q0{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=T.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Tx}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(s){s.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(s=>{s.afterStep(),this._tmpImpostorsArray[s.uniqueId]=s});let i=this.world.contacts;for(;i!==null;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const s=this._tmpImpostorsArray[+i.body1.name],r=this._tmpImpostorsArray[+i.body2.name];if(!s||!r){i=i.next;continue}s.onCollide({body:r.physicsBody,point:null,distance:0,impulse:0,normal:null}),r.onCollide({body:s.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){U.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 r=o=>Math.max(o,At),n=new ae;i.forEach(o=>{if(!o.object.rotationQuaternion)return;const l=o.object.rotationQuaternion;n.copyFrom(l),o.object.rotationQuaternion.set(0,0,0,1),o.object.computeWorldMatrix(!0);const h=n.toEulerAngles(),c=o.getObjectExtents(),u=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(h.x*u,h.y*u,h.z*u)}switch(o.object.rotationQuaternion.copyFrom(n),o.type){case ht.ParticleImpostor:U.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ht.SphereImpostor:{const d=c.x,f=c.y,m=c.z,_=Math.max(r(d),r(f),r(m))/2;t.type.push("sphere"),t.size.push(_),t.size.push(_),t.size.push(_);break}case ht.CylinderImpostor:{const d=r(c.x)/2,f=r(c.y);t.type.push("cylinder"),t.size.push(d),t.size.push(f),t.size.push(f);break}case ht.PlaneImpostor:case ht.BoxImpostor:default:{const d=r(c.x),f=r(c.y),m=r(c.z);t.type.push("box"),t.size.push(d),t.size.push(f),t.size.push(m);break}}o.object.rotationQuaternion=l}),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(n),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 s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case Fi.BallAndSocketJoint:n="jointBall";break;case Fi.SpringJoint:{U.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const l=s;o.min=l.length||o.min,o.max=Math.max(o.min,o.max)}case Fi.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case Fi.PrismaticJoint:n="jointPrisme";break;case Fi.SliderJoint:n="jointSlide";break;case Fi.WheelJoint:n="jointWheel";break;case Fi.HingeJoint:default:n="jointHinge";break}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){U.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 s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.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 T(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new T(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,s){i!==void 0?U.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.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 U.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){U.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Lo{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 ae,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new T,this._tmpContactNormal=new T,this._tmpVec3=new T,this._tmpMatrix=new L,typeof t=="function"){U.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}else this.bjsAMMO=t;if(!this.isSupported()){U.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=s=>{s=this.bjsAMMO.wrapPointer(s,this.bjsAMMO.btManifoldPoint);const r=s.getPositionWorldOnA(),n=s.m_normalWorldOnB;this._tmpContactPoint.x=r.x(),this._tmpContactPoint.y=r.y(),this._tmpContactPoint.z=r.z(),this._tmpContactNormal.x=n.x(),this._tmpContactNormal.y=n.y(),this._tmpContactNormal.z=n.z(),this._tmpContactImpulse=s.getAppliedImpulse(),this._tmpContactDistance=s.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new Tx,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 s of i._onPhysicsCollideCallbacks)for(const r of s.otherImpostors)(i.physicsBody.isActive()||r.physicsBody.isActive())&&this._isImpostorPairInContact(i,r)&&(i.onCollide({body:r.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),r.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===ht.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,l;const h=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)return;const s=e.joint.jointData;s.mainPivot||(s.mainPivot=new T(0,0,0)),s.connectedPivot||(s.connectedPivot=new T(0,0,0));let r;switch(e.joint.type){case Fi.DistanceJoint:{const n=s.maxDistance;n&&(s.mainPivot=new T(0,-n/2,0),s.connectedPivot=new T(0,n/2,0)),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case Fi.HingeJoint:{s.mainAxis||(s.mainAxis=new T(0,0,0)),s.connectedAxis||(s.connectedAxis=new T(0,0,0));const n=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),o=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);r=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),n,o);break}case Fi.BallAndSocketJoint:r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:U.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(P.PositionKind);n||(n=[]);let o;if(t&&t!==i){let h;t.rotationQuaternion?h=t.rotationQuaternion:t.rotation?h=ae.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):h=ae.Identity(),L.Compose(T.One(),h,t.position).invertToRef(this._tmpMatrix),o=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else L.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=this._tmpMatrix;const l=r.length/3;for(let h=0;h{s+=this._addMeshVerts(e,t,h)})}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){t.getIndices();let i=t.getVerticesData(P.PositionKind);i||(i=[]);let s=t.getVerticesData(P.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let l=0;ld*d),l=(d,f)=>d+f;if(o.reduce(l)===0)t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const d=e.getParam("path");if(e.getParam("shape")===null)return U.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 c=e.getParam("fixedPoints");c=c>3?3:c;const u=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,c);return u.get_m_cfg().set_collisions(17),u}_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 s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(P.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let l=0;l{s+=this._addHullVerts(e,t,l)})}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const n=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let o=0;if(n.forEach(l=>{const h=l.getPhysicsImpostor();if(h){if(h.type==ht.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const c=this._createShape(h),u=l.parent.getWorldMatrix().clone(),d=new T;u.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),s.addChildShape(this._tmpAmmoTransform,c),h.dispose(),o++}}),o>0){if(e.type!=ht.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),s.addChildShape(this._tmpAmmoTransform,l))}return s}else this.bjsAMMO.destroy(s),s=null}switch(e.type){case ht.SphereImpostor:if(Ne.WithinEpsilon(r.x,r.y,1e-4)&&Ne.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{const n=[new this.bjsAMMO.btVector3(0,0,0)],o=[1];s=new this.bjsAMMO.btMultiSphereShape(n,o,1),s.setLocalScaling(new this.bjsAMMO.btVector3(r.x/2,r.y/2,r.z/2))}break;case ht.CapsuleImpostor:{const n=r.x/2;s=new this.bjsAMMO.btCapsuleShape(n,r.y-n*2)}break;case ht.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ht.PlaneImpostor:case ht.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ht.MeshImpostor:if(e.getParam("mass")==0){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const n=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(n),this._addMeshVerts(n,i,i)==0?s=new this.bjsAMMO.btCompoundShape:s=new this.bjsAMMO.btBvhTriangleMeshShape(n)}break}case ht.ConvexHullImpostor:{if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const n=new this.bjsAMMO.btConvexHullShape;this._addHullVerts(n,i,i)==0?(e._pluginData.toDispose.push(n),s=new this.bjsAMMO.btCompoundShape):s=n}break}case ht.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case ht.CustomImpostor:s=this._createCustom(e);break;case ht.SoftbodyImpostor:s=this._createSoftbody(e);break;case ht.ClothImpostor:s=this._createCloth(e);break;case ht.RopeImpostor:s=this._createRope(e);break;default:U.Warn("The impostor type is not currently supported by the ammo plugin.");break}return s}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 s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>At||Math.abs(s.getOrigin().y()-t.y)>At||Math.abs(s.getOrigin().z()-t.z)>At||Math.abs(s.getRotation().x()-i.x)>At||Math.abs(s.getRotation().y()-i.y)>At||Math.abs(s.getRotation().z()-i.z)>At||Math.abs(s.getRotation().w()-i.w)>At)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),e.mass==0){const r=e.physicsBody.getMotionState();r&&r.setWorldTransform(s)}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 T(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 T(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:(U.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===ht.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):U.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(U.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):U.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(U.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):U.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(U.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):U.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,l=Math.round((o-1)*i),h=Math.round((o-1)*s),c=o-1-h,u=l+o*c;e.physicsBody.appendAnchor(u,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){U.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){U.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._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._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 s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Lo._DISABLE_COLLISION_FLAG=4;Lo._KINEMATIC_FLAG=2;Lo._DISABLE_DEACTIVATION_FLAG=4;xs.prototype.removeReflectionProbe=function(a){if(!this.reflectionProbes)return-1;const e=this.reflectionProbes.indexOf(a);return e!==-1&&this.reflectionProbes.splice(e,1),e};xs.prototype.addReflectionProbe=function(a){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(a)};class __{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=L.Identity(),this._target=T.Zero(),this._add=T.Zero(),this._invertYAxis=!1,this.position=T.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let c=0;c<6;++c)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${c}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const c=this._scene.getEngine().getCaps();c.textureHalfFloatRender?o=2:c.textureFloatRender&&(o=1)}this._renderTargetTexture=new Yi(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(c=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[c]),i.getSceneUniformBuffer().unbindEffect()),c){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 u=i.useRightHandedSystem?L.LookAtRHToRef:L.LookAtLHToRef,d=i.useRightHandedSystem?L.PerspectiveFovRH:L.PerspectiveFovLH;u(this.position,this._target,T.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 h;this._renderTargetTexture.onBeforeBindObservable.add(()=>{var c,u;this._currentSceneUBO=i.getSceneUniformBuffer(),(u=(c=i.getEngine())._debugPushGroup)==null||u.call(c,`reflection probe generation for ${e}`,1),h=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var c,u;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),(u=(c=i.getEngine())._debugPopGroup)==null||u.call(c,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=Pe.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let r=0;rs||new __(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}v([i_()],__.prototype,"_attachedMesh",void 0);v([Sr()],__.prototype,"position",void 0);class wY{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,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,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 cC extends wY{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 K,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Oe(1,1,1,1),this.position=T.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,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let r=0;r=s.distance)&&(s=o,t))break}return s||new zs};Ue.prototype._internalMultiPickSprites=function(a,e,t){if(!zs)return null;let i=[];if(!t){if(!this.activeCamera)return null;t=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;st.actionManager?t.isPickable&&t.actionManager.hasPointerTriggers:!1}register(){this.scene._pointerMoveStage.registerStep(ve.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ve.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ve.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,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null)),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0),i&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager)){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,ji.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,ji.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,ji.CreateNewFromSprite(i.pickedSprite,r,s));break}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,ji.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const o=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(7,ji.CreateNewFromSprite(o.pickedSprite,n,s)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(1,ji.CreateNewFromSprite(o.pickedSprite,n,s)),r&&o.pickedSprite.actionManager.processTrigger(6,ji.CreateNewFromSprite(o.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==o.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,ji.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}const LY="imageProcessingCompatibility",BY=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;j.IncludesShadersStore[LY]=BY;const UY="spritesPixelShader",VY=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#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 +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;j.ShadersStore[UY]=VY;const kY="spritesVertexShader",GY=`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 +#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 +#define CUSTOM_VERTEX_MAIN_END +}`;j.ShadersStore[kY]=GY;class zY{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},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=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Gs(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(P.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=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 Gs(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 h=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(P.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=l,this._vertexBuffers.inverts=h,this._vertexBuffers.cellInfo=c,this._vertexBuffers[P.ColorKind]=u,this._createEffects()}_createEffects(){var t,i,s,r;(t=this._drawWrapperBase)==null||t.dispose(),(i=this._drawWrapperFog)==null||i.dispose(),(s=this._drawWrapperDepth)==null||s.dispose(),(r=this._drawWrapperFogDepth)==null||r.dispose(),this._drawWrapperBase=new Ws(this._engine),this._drawWrapperFog=new Ws(this._engine),this._drawWrapperDepth=new Ws(this._engine,!1),this._drawWrapperFogDepth=new Ws(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const e=this._pixelPerfect?`#define PIXEL_PERFECT +`:"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[P.PositionKind,"options","offsets","inverts","cellInfo",P.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[P.PositionKind,"options","offsets","inverts","cellInfo",P.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],e+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,o=this._drawWrapperDepth,l=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&this._scene.fogMode!==0&&(n=this._drawWrapperFog,o=this._drawWrapperFogDepth,l=!0);const h=n.effect;if(!h.isReady())return;const c=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),f=Math.min(this._capacity,e.length);let m=0,_=!0;for(let C=0;C>0;t._xOffset=(t.cellIndex-c*h)*this.cellWidth/r.width,t._yOffset=c*this.cellHeight/r.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]=s),n?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/r.width,this._vertexData[l+13]=t._ySize/r.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{u.cellRef||(u.cellIndex=0);const f=u.cellIndex;typeof f=="number"&&isFinite(f)&&Math.floor(f)===f&&(u.cellRef=this._spriteMap[u.cellIndex]),u._xOffset=this._cellData[u.cellRef].frame.x/d.width,u._yOffset=this._cellData[u.cellRef].frame.y/d.height,u._xSize=this._cellData[u.cellRef].frame.w,u._ySize=this._cellData[u.cellRef].frame.h},r||(r=We.LastCreatedScene),r._getComponent(ve.NAME_SPRITE)||r._addComponent(new FY(r)),this._fromPacked=l,this._scene=r;const c=this._scene.getEngine();if(this._spriteRenderer=new zY(c,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else if(s!==void 0)this.cellWidth=s,this.cellHeight=s;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new X(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,h)}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 r={};for(let n=0;n0);const r=e.substring(0,s-1)+".json",n=()=>{U.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=l=>{try{const h=JSON.parse(l),c=Reflect.ownKeys(h.frames);this._spriteMap=c,this._packedAndReady=!0,this._cellData=h.frames}catch{throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Z.LoadFile(r,o,void 0,void 0,!1,n)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=W.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const l=(o.x-s.x)/(r.x-s.x),h=1-(o.y-s.y)/(r.y-s.y),c=e._xOffset*n.width+l*e._xSize|0,u=e._yOffset*n.height+h*e._ySize|0;return this._textureContent[(c+u*n.width)*4+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=T.Zero(),o=T.Zero();let l=Number.MAX_VALUE,h=null;const c=W.Vector3[0],u=W.Vector3[1],d=t.getViewMatrix();let f=e,m=e;for(let _=0;_E){if(!this._checkTextureAlpha(x,f,E,n,o))continue;if(m=f,l=E,h=x,s)break}}}}if(h){const _=new zs;d.invertToRef(W.Matrix[0]),_.hit=!0,_.pickedSprite=h,_.distance=l;const x=W.Vector3[2];return x.copyFrom(m.direction),x.normalize(),x.scaleInPlace(l),m.origin.addToRef(x,c),_.pickedPoint=T.TransformCoordinates(c,W.Matrix[0]),_}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=T.Zero(),n=T.Zero();let o;const l=[],h=W.Vector3[0].copyFromFloats(0,0,0),c=W.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let d=0;d{const o=new hs;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){const l=JSON.parse(o.responseText),h=fl.Parse(l,i||We.LastCreatedScene,s);e&&(h.name=e),r(h)}else n("Unable to load the sprite manager")}),o.open("GET",t),o.send()})}static ParseFromSnippetAsync(e,t,i=""){return e==="_BLANK"?Promise.resolve(new fl("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((s,r)=>{const n=new hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.spriteManager),h=fl.Parse(l,t||We.LastCreatedScene,i);h.snippetId=e,s(h)}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}fl.SnippetUrl="https://snippet.babylonjs.com";fl.CreateFromSnippetAsync=fl.ParseFromSnippetAsync;class eg{}eg.LoaderInjectedPhysicsEngine=void 0;let qc={},sh={};const Q0=(a,e,t,i)=>{if(!e.materials)return null;for(let s=0,r=e.materials.length;s{for(const i in e)if(a.name===e[i])return t.push(a.id),!0;return a.parentId!==void 0&&t.indexOf(a.parentId)!==-1?(t.push(a.id),!0):!1},su=(a,e)=>a+" of "+(e?e.file+" from "+e.name+" version: "+e.version+", exporter version: "+e.exporter_version:"unknown"),rM=(a,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,s=t.isEnabled(!1);if(e._waitingData.lods.distances){const r=e._waitingData.lods.distances;if(r.length>=i.length){const n=r.length>i.length?r[r.length-1]:0;t.setEnabled(!1);for(let o=0;o0&&t.addLODLevel(n,null),s===!0&&t.setEnabled(!0)}else Z.Warn("Invalid level of detail distances for "+e.name)}}e._waitingData.lods=null}},Um=(a,e,t)=>{if(typeof a!="number"){const s=t.getLastEntryById(a);return s&&e!==void 0&&e!==null?s.instances[parseInt(e)]:s}const i=qc[a];return i&&e!==void 0&&e!==null?i.instances[parseInt(e)]:i},bg=(a,e)=>typeof a!="number"?e.getLastMaterialById(a,!0):sh[a],Z0=(a,e,t,i,s=!1)=>{const r=new Kg(a);let n="importScene has failed JSON parse";try{var o=JSON.parse(e);n="";const l=ft.loggingLevel===ft.DETAILED_LOGGING;let h,c;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,m=new oc((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,f,!0,!d,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(m.rotationY=o.environmentTextureRotationY),a.environmentTexture=m}else if(typeof o.environmentTexture=="object"){const f=Ms.Parse(o.environmentTexture,a,t);a.environmentTexture=f}else if(o.environmentTexture.endsWith(".env")){const f=new Ms((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),a.environmentTexture=f}else{const f=Ms.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":t)+o.environmentTexture,a,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(f.rotationY=o.environmentTextureRotationY),a.environmentTexture=f}if(o.createDefaultSkybox===!0){const f=a.activeCamera!==void 0&&a.activeCamera!==null?(a.activeCamera.maxZ-a.activeCamera.minZ)/2:1e3,m=o.skyboxBlurLevel||0;a.createDefaultSkybox(a.environmentTexture,d,f,m)}r.environmentTexture=a.environmentTexture}if(o.environmentIntensity!==void 0&&o.environmentIntensity!==null&&(a.environmentIntensity=o.environmentIntensity),o.lights!==void 0&&o.lights!==null)for(h=0,c=o.lights.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)}))}if(o.multiMaterials!==void 0&&o.multiMaterials!==null)for(h=0,c=o.multiMaterials.length;h{r.textures.indexOf(_)==-1&&(r.textures.push(_),_._parentContainer=r)})}if(o.morphTargetManagers!==void 0&&o.morphTargetManagers!==null)for(const d of o.morphTargetManagers){const f=Fo.Parse(d,a);r.morphTargetManagers.push(f),f._parentContainer=r}if(o.skeletons!==void 0&&o.skeletons!==null)for(h=0,c=o.skeletons.length;h{m&&(r.geometries.push(m),m._parentContainer=r)})}if(o.transformNodes!==void 0&&o.transformNodes!==null)for(h=0,c=o.transformNodes.length;h{d._waitingSubMaterialsUniqueIds.forEach(f=>{d.subMaterials.push(bg(f,a))}),d._waitingSubMaterialsUniqueIds=[]}),a.meshes.forEach(d=>{d._waitingMaterialId!==null&&(d.material=bg(d._waitingMaterialId,a),d._waitingMaterialId=null)}),h=0,c=a.skeletons.length;h{if(f._waitingTransformNodeId){const m=a.getLastEntryById(f._waitingTransformNodeId);m&&f.linkTransformNode(m),f._waitingTransformNodeId=null}}),d._hasWaitingData=null)}for(h=0,c=a.meshes.length;h0){for(let f=0;f0){for(let f=0;f{d._loadedUniqueId=""}),xs.Parse(o,a,r,t),h=0,c=a.meshes.length;ha.indexOf("babylon")!==-1,importMesh:(a,e,t,i,s,r,n,o)=>{var c;let l="importMesh has failed JSON parse";try{var h=JSON.parse(t);l="";const u=ft.loggingLevel===ft.DETAILED_LOGGING;a?Array.isArray(a)||(a=[a]):a=null;const d=[],f=new Map,m=[];if(h.transformNodes!==void 0&&h.transformNodes!==null)for(let _=0,x=h.transformNodes.length;_{N===!0||!h.geometries[k]||!Array.isArray(h.geometries[k])||h.geometries[k].forEach(B=>{if(B.id===I.geometryId){switch(k){case"vertexData":Is.Parse(B,e,i);break}N=!0}})}),N===!1&&U.Warn("Geometry not found for mesh "+I.id)}if(I.materialUniqueId||I.materialId){const N=I.materialUniqueId?E:x;let k=N.indexOf(I.materialUniqueId||I.materialId)!==-1;if(k===!1&&h.multiMaterials!==void 0&&h.multiMaterials!==null){const B=(Q,ne)=>{N.push(Q);const de=Q0(ne,h,e,i);de&&de.material&&(sh[de.parsedMaterial.uniqueId||de.parsedMaterial.id]=de.material,l+=` + Material `+de.material.toString(u))};for(let Q=0,ne=h.multiMaterials.length;QB(fe,Ee=>Ee.uniqueId===fe)):de.materials.forEach(fe=>B(fe,Ee=>Ee.id===fe)),N.push(de.uniqueId||de.id);const ge=Sl.ParseMultiMaterial(de,e);sh[de.uniqueId||de.id]=ge,ge&&(k=!0,l+=` + Multi-Material `+ge.toString(u));break}}}if(k===!1){N.push(I.materialUniqueId||I.materialId);const B=Q0(Q=>I.materialUniqueId&&Q.uniqueId===I.materialUniqueId||Q.id===I.materialId,h,e,i);!B||!B.material?U.Warn("Material not found for mesh "+I.id):(sh[B.parsedMaterial.uniqueId||B.parsedMaterial.id]=B.material,l+=` + Material `+B.material.toString(u))}}if(I.skeletonId!==null&&I.skeletonId!==void 0&&h.skeletonId!==-1&&h.skeletons!==void 0&&h.skeletons!==null&&!(_.indexOf(I.skeletonId)>-1))for(let k=0,B=h.skeletons.length;k-1&&h.morphTargetManagers!==void 0&&h.morphTargetManagers!==null&&!(S.indexOf(I.morphTargetManagerId)>-1))for(let k=0,B=h.morphTargetManagers.length;k{y._waitingSubMaterialsUniqueIds.forEach(A=>{y.subMaterials.push(bg(A,e))}),y._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(y=>{y._waitingMaterialId!==null&&(y.material=bg(y._waitingMaterialId,e),y._waitingMaterialId=null)});for(let y=0,A=e.transformNodes.length;y-1&&m.splice(N,1)}C._waitingParentId=null}C._waitingData.lods&&rM(e,C)}for(const y of m)y.dispose();for(let y=0,A=e.skeletons.length;y{if(R._waitingTransformNodeId){const N=e.getLastEntryById(R._waitingTransformNodeId);N&&R.linkTransformNode(N),R._waitingTransformNodeId=null}}),I._hasWaitingData=null)}for(let y=0,A=e.meshes.length;y{_._loadedUniqueId=""}),!0}catch(u){const d=su("importMesh",h?h.producer:"Unknown")+l;if(o)o(d,u);else throw U.Log(d),u}finally{l!==null&&ft.loggingLevel!==ft.NO_LOGGING&&U.Log(su("importMesh",h?h.producer:"Unknown")+(ft.loggingLevel!==ft.MINIMAL_LOGGING?l:"")),sh={}}return!1},load:(a,e,t,i)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(e);switch(s="",r.useDelayedTextureLoading!==void 0&&r.useDelayedTextureLoading!==null&&(a.useDelayedTextureLoading=r.useDelayedTextureLoading&&!ft.ForceFullSceneLoadingForIncremental),r.autoClear!==void 0&&r.autoClear!==null&&(a.autoClear=r.autoClear),r.clearColor!==void 0&&r.clearColor!==null&&(a.clearColor=Oe.FromArray(r.clearColor)),r.ambientColor!==void 0&&r.ambientColor!==null&&(a.ambientColor=re.FromArray(r.ambientColor)),r.gravity!==void 0&&r.gravity!==null&&(a.gravity=T.FromArray(r.gravity)),r.useRightHandedSystem!==void 0&&(a.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode!==void 0&&r.fogMode!==null&&(a.fogMode=r.fogMode),r.fogColor!==void 0&&r.fogColor!==null&&(a.fogColor=re.FromArray(r.fogColor)),r.fogStart!==void 0&&r.fogStart!==null&&(a.fogStart=r.fogStart),r.fogEnd!==void 0&&r.fogEnd!==null&&(a.fogEnd=r.fogEnd),r.fogDensity!==void 0&&r.fogDensity!==null&&(a.fogDensity=r.fogDensity),s+=" Fog mode for scene: ",a.fogMode){case 0:s+=`none +`;break;case 1:s+=`exp +`;break;case 2:s+=`exp2 +`;break;case 3:s+=`linear +`;break}if(r.physicsEnabled){let o;r.physicsEngine==="cannon"||r.physicsEngine===eS.name?o=new eS(void 0,void 0,eg.LoaderInjectedPhysicsEngine):r.physicsEngine==="oimo"||r.physicsEngine===q0.name?o=new q0(void 0,eg.LoaderInjectedPhysicsEngine):(r.physicsEngine==="ammo"||r.physicsEngine===Lo.name)&&(o=new Lo(void 0,eg.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+` enabled +`;const l=r.physicsGravity?T.FromArray(r.physicsGravity):null;a.enablePhysics(l,o)}return r.metadata!==void 0&&r.metadata!==null&&(a.metadata=r.metadata),r.collisionsEnabled!==void 0&&r.collisionsEnabled!==null&&(a.collisionsEnabled=r.collisionsEnabled),Z0(a,e,t,i,!0)?(r.autoAnimate&&a.beginAnimation(a,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),r.activeCameraID!==void 0&&r.activeCameraID!==null&&a.setActiveCameraById(r.activeCameraID),!0):!1}catch(n){const o=su("importScene",r?r.producer:"Unknown")+s;if(i)i(o,n);else throw U.Log(o),n}finally{s!==null&&ft.loggingLevel!==ft.NO_LOGGING&&U.Log(su("importScene",r?r.producer:"Unknown")+(ft.loggingLevel!==ft.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(a,e,t,i)=>Z0(a,e,t,i)});class yg{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,ee.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=e.bias===void 0?0:e.bias,this.power=e.power===void 0?1:e.power,this.leftColor=e.leftColor||re.White(),this.rightColor=e.rightColor||re.Black(),e.isEnabled===!1&&(this.isEnabled=!1)}clone(){const e=new yg;return Tr.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 yg({isEnabled:e.isEnabled,leftColor:re.FromArray(e.leftColor),rightColor:re.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Pe._FresnelParametersParser=yg.Parse;class cn extends ei{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new re(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}v([O(),_e("_markAllSubMeshesAsLightsDirty")],cn.prototype,"maxSimultaneousLights",void 0);v([O(),_e("_markAllSubMeshesAsLightsDirty")],cn.prototype,"disableLighting",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],cn.prototype,"environmentTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],cn.prototype,"invertNormalMapX",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],cn.prototype,"invertNormalMapY",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],cn.prototype,"normalTexture",void 0);v([Vi("emissive"),_e("_markAllSubMeshesAsTexturesDirty")],cn.prototype,"emissiveColor",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty")],cn.prototype,"emissiveTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],cn.prototype,"occlusionStrength",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],cn.prototype,"occlusionTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],cn.prototype,"alphaCutOff",void 0);v([O()],cn.prototype,"doubleSided",null);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty",null)],cn.prototype,"lightmapTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],cn.prototype,"useLightmapAsShadowmap",void 0);class Cl extends cn{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=Pe.Clone(()=>new Cl(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=Pe.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 s=Pe.Parse(()=>new Cl(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}v([Vi(),_e("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Cl.prototype,"baseColor",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Cl.prototype,"baseTexture",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Cl.prototype,"metallic",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],Cl.prototype,"roughness",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Cl.prototype,"metallicRoughnessTexture",void 0);H("BABYLON.PBRMetallicRoughnessMaterial",Cl);class bl extends cn{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Pe.Clone(()=>new bl(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=Pe.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 s=Pe.Parse(()=>new bl(e.name,t),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}v([Vi("diffuse"),_e("_markAllSubMeshesAsTexturesDirty","_albedoColor")],bl.prototype,"diffuseColor",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],bl.prototype,"diffuseTexture",void 0);v([Vi("specular"),_e("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],bl.prototype,"specularColor",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty","_microSurface")],bl.prototype,"glossiness",void 0);v([Dt(),_e("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],bl.prototype,"specularGlossinessTexture",void 0);H("BABYLON.PBRSpecularGlossinessMaterial",bl);class du extends Kt{constructor(e,t,i=null){if(super(t),!!e)if(this._textureMatrix=L.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const s=this.getScene();s?s.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=r=>{if(typeof r!="string")return;let n=null,o=null,l;const h=r.split(` +`);let c=0,u=0,d=0,f=0,m=0;for(let _=0;_0&&(_+1)%4===0)n[_]=255;else{const x=o[_];n[_]=x/m*255}t.is3D?(t.updateSize(c,c,c),e.updateRawTexture3D(t,n,5,!1)):(t.updateSize(c*c,c),e.updateRawTexture(t,n,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._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 du(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 du(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}}du._NoneEmptyLineRegex=/\S+/;H("BABYLON.ColorGradingTexture",du);class Ag extends Kt{constructor(e,t,i,s=!1,r=!0,n=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=X.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=l,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,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?n&&(this._texture.isReady?Z.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");r_(this.url,n=>{this._width=n.width,this._height=n.height,r.width=this._width,r.height=this._height;const o=r.getContext("2d");o.drawImage(n,0,0);const l=o.getImageData(0,0,n.width,n.height);this._buffer=l.data.buffer,r.remove(),e()},(n,o)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,o)},i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene(),t=()=>{const r=this._getFloat32ArrayFromArrayBuffer(this._buffer),n=Ih.ConvertPanoramaToCubemap(r,this._width,this._height,this._size,this._supersample),o=[];for(let l=0;l<6;l++){const h=n[Ag._FacesMapping[l]];o.push(h)}return o};if(!e)return;const i=t(),s=this._texture;e.getEngine().updateRawCubeTexture(s,i,s.format,s.type,s.invertY),s.isReady=!0,e.removePendingData(s),s.onLoadedObservable.notifyObservers(s),s.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(e.byteLength*3/4);let s=0;for(let r=0;re.length){U.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let s=!1,r=!1,n=!1;switch(i.image_type){case $Y:s=!0;case HY:r=!0;break;case KY:s=!0;case XY:break;case jY:s=!0;case YY:n=!0;break}let o;const l=i.pixel_size>>3,h=i.width*i.height*l;let c;if(r&&(c=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),s){o=new Uint8Array(h);let y,A,I,R=0;const N=new Uint8Array(l);for(;t>QY){default:case e$:u=0,f=1,x=i.width,d=0,m=1,_=i.height;break;case ZY:u=0,f=1,x=i.width,d=i.height-1,m=-1,_=-1;break;case t$:u=i.width-1,f=-1,x=-1,d=0,m=1,_=i.height;break;case JY:u=i.width-1,f=-1,x=-1,d=i.height-1,m=-1,_=-1;break}const E="_getImageData"+(n?"Grey":"")+i.pixel_size+"bits",S=l$[E](i,c,o,d,m,_,u,f,x);a.getEngine()._uploadDataToTextureDirectly(a,S)}function i$(a,e,t,i,s,r,n,o,l){const h=t,c=e,u=a.width,d=a.height;let f,m=0,_,x;const E=new Uint8Array(u*d*4);for(x=i;x!==r;x+=s)for(_=n;_!==l;_+=o,m++)f=h[m],E[(_+u*x)*4+3]=255,E[(_+u*x)*4+2]=c[f*3+0],E[(_+u*x)*4+1]=c[f*3+1],E[(_+u*x)*4+0]=c[f*3+2];return E}function s$(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d,f=0,m,_;const x=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(m=n;m!==l;m+=o,f+=2){d=h[f+0]+(h[f+1]<<8);const E=((d&31744)>>10)*255/31|0,S=((d&992)>>5)*255/31|0,C=(d&31)*255/31|0;x[(m+c*_)*4+0]=E,x[(m+c*_)*4+1]=S,x[(m+c*_)*4+2]=C,x[(m+c*_)*4+3]=d&32768?0:255}return x}function r$(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,m;const _=new Uint8Array(c*u*4);for(m=i;m!==r;m+=s)for(f=n;f!==l;f+=o,d+=3)_[(f+c*m)*4+3]=255,_[(f+c*m)*4+2]=h[d+0],_[(f+c*m)*4+1]=h[d+1],_[(f+c*m)*4+0]=h[d+2];return _}function n$(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,m;const _=new Uint8Array(c*u*4);for(m=i;m!==r;m+=s)for(f=n;f!==l;f+=o,d+=4)_[(f+c*m)*4+2]=h[d+0],_[(f+c*m)*4+1]=h[d+1],_[(f+c*m)*4+0]=h[d+2],_[(f+c*m)*4+3]=h[d+3];return _}function a$(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d,f=0,m,_;const x=new Uint8Array(c*u*4);for(_=i;_!==r;_+=s)for(m=n;m!==l;m+=o,f++)d=h[f],x[(m+c*_)*4+0]=d,x[(m+c*_)*4+1]=d,x[(m+c*_)*4+2]=d,x[(m+c*_)*4+3]=255;return x}function o$(a,e,t,i,s,r,n,o,l){const h=t,c=a.width,u=a.height;let d=0,f,m;const _=new Uint8Array(c*u*4);for(m=i;m!==r;m+=s)for(f=n;f!==l;f+=o,d+=2)_[(f+c*m)*4+0]=h[d+0],_[(f+c*m)*4+1]=h[d+0],_[(f+c*m)*4+2]=h[d+0],_[(f+c*m)*4+3]=h[d+1];return _}const l$={GetTGAHeader:Ex,UploadContent:nM,_getImageData8bits:i$,_getImageData16bits:s$,_getImageData24bits:r$,_getImageData32bits:n$,_getImageDataGrey8bits:a$,_getImageDataGrey16bits:o$};class h${constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Ex(s);i(r.width,r.height,t.generateMipMaps,!1,()=>{nM(t,s)})}}ee._TextureLoaders.push(new h$);class c${constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=JE.RGBE_ReadHeader(s),n=JE.RGBE_ReadPixels(s,r),o=r.width*r.height,l=new Float32Array(o*4);for(let h=0;h{const h=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,h._uploadDataToTextureDirectly(t,l)})}}ee._TextureLoaders.push(new c$);function u$(){const a={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=n=>{if(n.data.action==="init"){if(n.data.url)try{importScripts(n.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:n.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(n.data.action==="transcode"){const o=n.data.config,l=n.data.imageData,h=new BASIS.BasisFile(l),c=i(h);let u=n.data.ignoreSupportedFormats?null:t(n.data.config,c),d=!1;u===null&&(d=!0,u=c.hasAlpha?a.cTFBC3:a.cTFBC1);let f=!0;h.startTranscoding()||(f=!1);const m=[];for(let _=0;_>2&3],u[C++]=c[S>>4&3],u[C++]=c[S>>6&3]}}return u}}function d$(a,e,t){return new Promise((i,s)=>{const r=n=>{n.data.action==="init"?(a.removeEventListener("message",r),i(a)):n.data.action==="error"&&s(n.data.error||"error initializing worker")};a.addEventListener("message",r),a.postMessage({action:"init",url:t?Z.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}var ll;(function(a){a[a.cTFETC1=0]="cTFETC1",a[a.cTFETC2=1]="cTFETC2",a[a.cTFBC1=2]="cTFBC1",a[a.cTFBC3=3]="cTFBC3",a[a.cTFBC4=4]="cTFBC4",a[a.cTFBC5=5]="cTFBC5",a[a.cTFBC7=6]="cTFBC7",a[a.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",a[a.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",a[a.cTFASTC_4x4=10]="cTFASTC_4x4",a[a.cTFATC_RGB=11]="cTFATC_RGB",a[a.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",a[a.cTFRGBA32=13]="cTFRGBA32",a[a.cTFRGB565=14]="cTFRGB565",a[a.cTFBGR565=15]="cTFBGR565",a[a.cTFRGBA4444=16]="cTFRGBA4444",a[a.cTFFXT1_RGB=17]="cTFFXT1_RGB",a[a.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",a[a.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",a[a.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",a[a.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(ll||(ll={}));const Sh={JSModuleURL:`${Z._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Z._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},f$=(a,e)=>{let t;switch(a){case ll.cTFETC1:t=36196;break;case ll.cTFBC1:t=33776;break;case ll.cTFBC4:t=33779;break;case ll.cTFASTC_4x4:t=37808;break;case ll.cTFETC2:t=37496;break;case ll.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t};let CE=null,ec=null,p$=0;const _$=!1,m$=()=>(CE||(CE=new Promise((a,e)=>{ec?a(ec):Z.LoadFileAsync(Z.GetBabylonScriptURL(Sh.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");const i=URL.createObjectURL(new Blob([`(${u$})()`],{type:"application/javascript"}));ec=new Worker(i),d$(ec,t,Sh.JSModuleURL).then(a,e)}).catch(e)})),CE),tS=(a,e)=>{const t=a instanceof ArrayBuffer?new Uint8Array(a):a;return new Promise((i,s)=>{m$().then(()=>{const r=p$++,n=l=>{l.data.action==="transcode"&&l.data.id===r&&(ec.removeEventListener("message",n),l.data.success?i(l.data):s("Transcode is not supported on this device"))};ec.addEventListener("message",n);const o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),ec.postMessage({action:"transcode",id:r,imageData:o,config:e,ignoreSupportedFormats:_$},[o.buffer])},r=>{s(r)})})},Vm=(a,e)=>{var i,s;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;a.isCube&&(t=(s=e._gl)==null?void 0:s.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,a,!0)},iS=(a,e)=>{const t=a.getEngine();for(let i=0;i{t._releaseTexture(r),Vm(a,t)})}else a._invertVScale=!a.invertY,a.width=s.width+3&-4,a.height=s.height+3&-4,a.samplingMode=2,Vm(a,t),t._uploadDataToTextureDirectly(a,new Uint16Array(s.transcodedPixels.buffer),i,0,4,!0);else{a.width=s.width,a.height=s.height,a.generateMipMaps=e.fileInfo.images[i].levels.length>1;const r=dC.GetInternalFormatFromBasisFormat(e.format,t);a.format=r,Vm(a,t),e.fileInfo.images[i].levels.forEach((n,o)=>{t._uploadCompressedDataToTextureDirectly(a,r,n.width,n.height,n.transcodedPixels,i,o)}),t._features.basisNeedsPOT&&(Ne.Log2(a.width)%1!==0||Ne.Log2(a.height)%1!==0)&&(Z.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."),a._cachedWrapU=X.CLAMP_ADDRESSMODE,a._cachedWrapV=X.CLAMP_ADDRESSMODE)}}},dC={JSModuleURL:Sh.JSModuleURL,WasmModuleURL:Sh.WasmModuleURL,GetInternalFormatFromBasisFormat:f$,TranscodeAsync:tS,LoadTextureFromTranscodeResult:iS};Object.defineProperty(dC,"JSModuleURL",{get:function(){return Sh.JSModuleURL},set:function(a){Sh.JSModuleURL=a}});Object.defineProperty(dC,"WasmModuleURL",{get:function(){return Sh.WasmModuleURL},set:function(a){Sh.WasmModuleURL=a}});class g${constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};tS(e,o).then(l=>{const h=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;iS(t,l),t.getEngine()._setCubeMapTextureParams(t,h),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}).catch(l=>{Z.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(l)})}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};tS(e,r).then(n=>{const o=n.fileInfo.images[0].levels[0],l=n.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,n.format!==-1,()=>{iS(t,n)})}).catch(n=>{Z.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Z.Warn(`Failed to transcode Basis file: ${n}`),i(0,0,!1,!1,()=>{},!0)})}}He._TextureLoaders.push(new g$);class jh extends Yi{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(n))}_initTypes(e,t,i,s,r,n,o,l,h,c){for(let u=0;u{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 s=e.length-1;s>=0;s--)this._textures[s]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}const x$="noisePixelShader",T$=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) +{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} +float interpolationNoise(vec2 p) +{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); +return ym;} +float perlinNoise2D(float x,float y) +{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i{})}clone(){return Pe.Clone(()=>{const e=this.getScene(),t=this._texture,i=new fC(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===xt.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i},this)}}class es extends Su{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof es&&e._blockName===this._blockName?ra.Compatible:ra.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class E$ extends Je{constructor(e){super(e,z.Vertex),this.registerInput("matricesIndices",M.Vector4),this.registerInput("matricesWeights",M.Vector4),this.registerInput("matricesIndicesExtra",M.Vector4,!0),this.registerInput("matricesWeightsExtra",M.Vector4,!0),this.registerInput("world",M.Matrix),this.registerOutput("output",M.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}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(s=>s.isAttribute&&s.name==="matricesIndices"&&t(s));i||(i=new bt("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="matricesWeights"&&t(s));i||(i=new bt("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.World&&t(s));i||(i=new bt("world"),i.setAsSystemValue(It.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){l_(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&oP(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 s=this._outputs[0],r=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}}H("BABYLON.BonesBlock",E$);class S$ extends Je{constructor(e){super(e,z.Vertex),this.registerInput("world0",M.Vector4),this.registerInput("world1",M.Vector4),this.registerInput("world2",M.Vector4),this.registerInput("world3",M.Vector4),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Matrix),this.registerOutput("instanceID",M.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(s=>s.isAttribute&&s.name==="world0"&&t(s));i||(i=new bt("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world1"&&t(s));i||(i=new bt("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world2"&&t(s));i||(i=new bt("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world3"&&t(s));i||(i=new bt("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="world"&&t(s));i||(i=new bt("world"),i.setAsSystemValue(It.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!(r!=null&&r.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(r!=null&&r.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,l=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=e._declareOutput(i)+` = mat4(${r.associatedVariableName}, ${n.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(s)+` = float(gl_InstanceID); +`:e.compilationString+=e._declareOutput(s)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=e._declareOutput(s)+` = 0.0; +`,e.compilationString+=`#endif +`,this}}H("BABYLON.InstancesBlock",S$);class aM extends Je{constructor(e){super(e,z.Vertex),this.registerInput("position",M.Vector3),this.registerInput("normal",M.Vector3),this.registerInput("tangent",M.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(M.Color4|M.Vector4|M.Vector3),this.registerInput("uv",M.Vector2),this.registerOutput("positionOutput",M.Vector3),this.registerOutput("normalOutput",M.Vector3),this.registerOutput("tangentOutput",M.Vector4),this.registerOutput("uvOutput",M.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")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new bt("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new bt("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&t(s));i||(i=new bt("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new bt("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const s=e.morphTargetManager;s!=null&&s.isUsingTextureForTargets&&(s.numMaxInfluencers||s.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&lP(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Al(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,l=this.uv,h=this.positionOutput,c=this.normalOutput,u=this.tangentOutput,d=this.uvOutput,f=e,m=s.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,x=_&&_.supportsNormals&&s.NORMAL,E=_&&_.supportsTangents&&s.TANGENT,S=_&&_.supportsUVs&&s.UV1;let C="";if(_!=null&&_.isUsingTextureForTargets&&m>0&&(C+=`float vertexID; +`),C+=`#ifdef MORPHTARGETS +`,_!=null&&_.isUsingTextureForTargets)C+=`for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) { +`,C+=`if (i >= morphTargetCount) break; +`,C+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; +`,C+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * morphTargetInfluences[i]; +`,C+=`vertexID += 1.0; +`,x&&(C+=`#ifdef MORPHTARGETS_NORMAL +`,C+=`${c.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[i]; +`,C+=`vertexID += 1.0; +`,C+=`#endif +`),S&&(C+=`#ifdef MORPHTARGETS_UV +`,C+=`${d.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${l.associatedVariableName}) * morphTargetInfluences[i]; +`,C+=`vertexID += 1.0; +`,C+=`#endif +`),E&&(C+=`#ifdef MORPHTARGETS_TANGENT +`,C+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * morphTargetInfluences[i]; +`,o.type===M.Vector4?C+=`${u.associatedVariableName}.w = ${o.associatedVariableName}.w; +`:C+=`${u.associatedVariableName}.w = 1.; +`,C+=`#endif +`),C+=`} +`;else for(let y=0;y0)for(let y=0;y!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.isSystemValue&&s.systemValue===It.World&&t(s));i||(i=new bt("world"),i.setAsSystemValue(It.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="normal"&&t(s));i||(i=new bt("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="tangent"&&s.type===M.Vector4&&t(s));i||(i=new bt("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var h,c,u,d;const s=this.normal,r=this.tangent;let n=s.isConnected;(h=s.connectInputBlock)!=null&&h.isAttribute&&!e.isVerticesDataPresent((c=s.connectInputBlock)==null?void 0:c.name)&&(n=!1);let o=r.isConnected;(u=r.connectInputBlock)!=null&&u.isAttribute&&!e.isVerticesDataPresent((d=r.connectInputBlock)==null?void 0:d.name)&&(o=!1);const l=n&&o;i.setValue("TBNBLOCK",l,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,l=this.row2;return e.target===z.Fragment&&(e.compilationString+=` + // ${this.name} + vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; + vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); + vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; + mat3 ${r.associatedVariableName} = mat3(${s.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]); +`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]); +`),l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = vec3(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}}H("BABYLON.TBNBlock",gf);class m_ extends Je{constructor(e){super(e,z.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",M.Vector4,!1),this.registerInput("worldNormal",M.Vector4,!1),this.registerInput("worldTangent",M.Vector4,!0),this.registerInput("uv",M.Vector2,!1),this.registerInput("normalMapColor",M.Color3,!1),this.registerInput("strength",M.Float,!1),this.registerInput("viewDirection",M.Vector3,!0),this.registerInput("parallaxScale",M.Float,!0),this.registerInput("parallaxHeight",M.Float,!0),this.registerInput("TBN",M.Object,!0,z.VertexAndFragment,new es("TBN",this,Ui.Input,gf,"TBNBlock")),this.registerInput("world",M.Matrix,!0),this.registerOutput("output",M.Vector4),this.registerOutput("uvOffset",M.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]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!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(s=>s.isAttribute&&s.name==="uv"&&t(s));i||(i=new bt("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const i=new bt("strength");i.value=1,i.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,M.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,M.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,M.Matrix);let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),h=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",c=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}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d={search:/varying mat3 vTBN;/g,replace:""},f={search:/uniform mat4 normalMatrix;/g,replace:""},m=this.TBN;m.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${m.associatedVariableName}; + #endif + `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${r.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,d,f]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:`#define inline +vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const _=!l||!o?this.normalMapColor.associatedVariableName:`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`;return e.compilationString+=e._declareOutput(this.output)+` = vec4(0.); +`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${_}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${_}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${l&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${l?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:c},{search:/vBumpInfos.z/g,replace:h},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:l?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),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([it("Invert X axis",Qe.Boolean,"PROPERTIES",{notifiers:{update:!1}})],m_.prototype,"invertX",void 0);v([it("Invert Y axis",Qe.Boolean,"PROPERTIES",{notifiers:{update:!1}})],m_.prototype,"invertY",void 0);v([it("Use parallax occlusion",Qe.Boolean)],m_.prototype,"useParallaxOcclusion",void 0);v([it("Object Space Mode",Qe.Boolean,"PROPERTIES",{notifiers:{update:!1}})],m_.prototype,"useObjectSpaceNormalMap",void 0);H("BABYLON.PerturbNormalBlock",m_);class C$ extends Je{constructor(e){super(e,z.Fragment,!0),this.registerInput("value",M.Float,!0),this.registerInput("cutoff",M.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}}H("BABYLON.DiscardBlock",C$);class b$ extends Je{constructor(e){super(e,z.Fragment),this.registerOutput("output",M.Float,z.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===z.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = gl_FrontFacing ? 1.0 : 0.0; +`,this}}H("BABYLON.FrontFacingBlock",b$);class y$ extends Je{constructor(e){super(e,z.Fragment),this.registerInput("input",M.AutoDetect,!1),this.registerOutput("dx",M.BasedOnInput),this.registerOutput("dy",M.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 s="dFdx",r="dFdy";return e.shaderLanguage===vt.WGSL&&(s="dpdx",r="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName}); +`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${r}(${this.input.associatedVariableName}); +`),this}}H("BABYLON.DerivativeBlock",y$);class A$ extends Je{constructor(e){super(e,z.Fragment),this.registerOutput("xy",M.Vector2,z.Fragment),this.registerOutput("xyz",M.Vector3,z.Fragment),this.registerOutput("xyzw",M.Vector4,z.Fragment),this.registerOutput("x",M.Float,z.Fragment),this.registerOutput("y",M.Float,z.Fragment),this.registerOutput("z",M.Float,z.Fragment),this.registerOutput("w",M.Float,z.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="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${e._declareOutput(i)} = gl_FragCoord.${i.name}; +`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===z.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}H("BABYLON.FragCoordBlock",A$);class R$ extends Je{constructor(e){super(e,z.Fragment),this.registerOutput("xy",M.Vector2,z.Fragment),this.registerOutput("x",M.Float,z.Fragment),this.registerOutput("y",M.Float,z.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 s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===z.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,M.Vector2),e.compilationString+=this.writeOutputs(e,this._varName),this}}H("BABYLON.ScreenSizeBlock",R$);class I$ extends Je{constructor(e){super(e,z.Fragment),this.registerInput("vector",M.AutoDetect),this.registerInput("worldViewProjection",M.Matrix),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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(s=>s.systemValue===It.WorldViewProjection&&t(s));i||(i=new bt("worldViewProjection"),i.setAsSystemValue(It.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case M.Vector3:e.compilationString+=`vec4 ${r} = ${s} * vec4(${t.associatedVariableName}, 1.0); +`;break;case M.Vector4:e.compilationString+=`vec4 ${r} = ${s} * ${t.associatedVariableName}; +`;break}return e.compilationString+=`${r}.xy /= ${r}.w;`,e.compilationString+=`${r}.xy = ${r}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${r}.xy; +`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${r}.x; +`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${r}.y; +`),this}}H("BABYLON.ScreenSpaceBlock",I$);class P$ extends Je{constructor(e){super(e,z.Fragment),this.registerInput("input",M.Vector2),this.registerInput("strength",M.Float),this.registerInput("center",M.Vector2),this.registerInput("offset",M.Vector2),this.registerOutput("output",M.Vector2),this.registerOutput("x",M.Float),this.registerOutput("y",M.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 bt("center");e.value=new ce(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new bt("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new bt("offset");e.value=new ce(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` + ${e._declareLocalVar(t,M.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + ${e._declareLocalVar(i,M.Float)} = ${this.strength.associatedVariableName} * length(${t}); + ${e._declareLocalVar(s,M.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + ${e._declareLocalVar(r,M.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + ${e._declareLocalVar(n,M.Vector2)} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n}; +`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x; +`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y; +`),this}}H("BABYLON.TwirlBlock",P$);class Sx extends Je{constructor(e){super(e,z.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",M.Float),this.registerInput("worldPosition",M.Vector3),this.registerInput("worldNormal",M.Vector3),this.registerInput("worldTangent",M.AutoDetect,!0),this.registerOutput("output",M.Vector4),this.registerOutput("xyz",M.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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];!this.generateInWorldSpace&&!this.worldTangent.isConnected&&U.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":` + vec3 biTangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, biTangent, normal); + `,s=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,r=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + ${i} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(normal, worlddX); + vec3 crossY = cross(normal, 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 * normal) - inToNormal); + ${s} + return vec4(result, 0.); + }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",r,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(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([it("Generate in world space instead of tangent space",Qe.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Sx.prototype,"generateInWorldSpace",void 0);v([it("Force normalization for the worldNormal input",Qe.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Sx.prototype,"automaticNormalizationNormal",void 0);v([it("Force normalization for the worldTangent input",Qe.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Sx.prototype,"automaticNormalizationTangent",void 0);H("BABYLON.HeightToNormalBlock",Sx);class M$ extends Je{constructor(e){super(e,z.Fragment,!0),this.registerInput("depth",M.Float,!0),this.registerInput("worldPos",M.Vector4,!0),this.registerInput("viewProjection",M.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){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; +`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` + vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + float v = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + gl_FragDepth = v; + + `:U.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}H("BABYLON.FragDepthBlock",M$);class O$ extends Je{constructor(e){super(e,z.Fragment),this.registerInput("worldPosition",M.Vector4,!1),this.registerInput("viewProjection",M.Matrix,!1),this.registerInput("worldNormal",M.AutoDetect,!0),this.registerOutput("depth",M.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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")}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}`;return e._emitUniformFromString("biasAndScaleSM",M.Vector3),e._emitUniformFromString("lightDataSM",M.Vector3),e._emitUniformFromString("depthValuesSM",M.Vector3),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; +`,e.compilationString+=`vec3 vPositionWSM; +`,e.compilationString+=`float vDepthMetricSM = 0.0; +`,e.compilationString+=`float zSM; +`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + gl_FragDepth = (clipPos.z / clipPos.w); + #else + gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `,e.compilationString+=`${e._declareOutput(this.depth)} = vec3(depthSM, 1., 1.); +`,this}}H("BABYLON.ShadowMapBlock",O$);class D$ extends Je{constructor(e){super(e,z.Fragment,!0),this.registerInput("viewDepth",M.Float,!0),this.registerInput("worldPosition",M.AutoDetect,!0),this.registerInput("viewNormal",M.AutoDetect,!0),this.registerInput("reflectivity",M.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(M.Vector3|M.Vector4|M.Color3|M.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]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r +`:e.compilationString+=` gl_FragData[PREPASS_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+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===M.Vector4?t.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_NORMAL\r +`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===M.Vector4?i.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r +`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===M.Vector4?r.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#endif\r +`,this}}H("BABYLON.PrePassOutputBlock",D$);class N$ extends Je{constructor(e){super(e,z.VertexAndFragment,!1),this.registerInput("worldPosition",M.Vector4,!1,z.Vertex),this.registerInput("view",M.Matrix,!1,z.Vertex),this.registerInput("input",M.AutoDetect,!1,z.Fragment),this.registerInput("fogColor",M.AutoDetect,!1,z.Fragment),this.registerOutput("output",M.Color3,z.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.View&&t(s));i||(i=new bt("view"),i.setAsSystemValue(It.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.FogColor&&t(s));i||(i=new bt("fogColor",void 0,M.Color3),i.setAsSystemValue(It.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&aP(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===z.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,s=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const r=this._outputs[0];e._emitUniformFromString(this._fogParameters,M.Vector4),e.compilationString+=`#ifdef FOG +`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); +`,e.compilationString+=e._declareOutput(r)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${s.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${e._declareOutput(r)} = ${i.associatedVariableName}.rgb; +`,e.compilationString+=`#endif +`}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,M.Vector3),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; +`}return this}}H("BABYLON.FogBlock",N$);class sS extends Je{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,U.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?z.Fragment:z.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?z.Fragment:z.Vertex}constructor(e){super(e,z.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",M.Vector4,!1,z.Vertex),this.registerInput("worldNormal",M.Vector4,!1,z.Fragment),this.registerInput("cameraPosition",M.Vector3,!1,z.Fragment),this.registerInput("glossiness",M.Float,!0,z.Fragment),this.registerInput("glossPower",M.Float,!0,z.Fragment),this.registerInput("diffuseColor",M.Color3,!0,z.Fragment),this.registerInput("specularColor",M.Color3,!0,z.Fragment),this.registerInput("view",M.Matrix,!0),this.registerOutput("diffuseOutput",M.Color3,z.Fragment),this.registerOutput("specularOutput",M.Color3,z.Fragment),this.registerOutput("shadow",M.Float,z.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]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.CameraPosition&&t(s));i||(i=new bt("cameraPosition"),i.setAsSystemValue(It.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(!this.light)c_(s,e,i,!0,t.maxSimultaneousLights);else{const r={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Tv(s,e,this.light,this._lightId,i,!0,r),r.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Sv(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?mv(this.light,this._lightId,s,e,!0):h_(s,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 s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,M.Vector4)&&(e.compilationString+=`${s} = ${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+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==z.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let s=i.associatedVariableName;this.generateOnlyFragmentCode?(s=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${s}; +`,t),e.compilationString+=`${s} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):s="v_"+s+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:s}]}),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}),this._lightId===0&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${s}); +`),e.compilationString+=`lightingInfo info; +`,e.compilationString+=`float shadow = 1.; +`,e.compilationString+=`float aggShadow = 0.; +`,e.compilationString+=`float numLights = 0.; +`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; +`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; +`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:s+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${s}.xyz`}),this._lightId===0&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);const r=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=e._declareOutput(r)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = 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([it("Generate only fragment code",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:sS._OnGenerateOnlyFragmentCodeChanged}})],sS.prototype,"generateOnlyFragmentCode",void 0);H("BABYLON.LightBlock",sS);class lo extends Je{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??We.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,z.VertexAndFragment),this.registerOutput("source",M.Object,z.VertexAndFragment,new es("source",this,Ui.Output,lo,"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===z.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),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){super._deserialize(e,t,i),e.texture&&!ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=X.Parse(e.texture,t,i))}}H("BABYLON.ImageSourceBlock",lo);class Ig extends Je{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())??We.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 Ig._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!Ig._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()??We.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()??We.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?z.Fragment:z.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",M.AutoDetect,!1,z.VertexAndFragment),this.registerInput("source",M.Object,!0,z.VertexAndFragment,new es("source",this,Ui.Input,lo,"ImageSourceBlock")),this.registerInput("layer",M.Float,!0),this.registerInput("lod",M.Float,!0),this.registerOutput("rgba",M.Color4,z.Neutral),this.registerOutput("rgb",M.Color3,z.Neutral),this.registerOutput("r",M.Float,z.Neutral),this.registerOutput("g",M.Float,z.Neutral),this.registerOutput("b",M.Float,z.Neutral),this.registerOutput("a",M.Float,z.Neutral),this.registerOutput("level",M.Float,z.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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 z.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return z.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===z.Fragment)return z.Fragment;if(e.target===z.Vertex)return z.VertexAndFragment;if(e.target===z.Neutral||e.target===z.VertexAndFragment){const t=e.ownerBlock;if(t.target===z.Fragment)return z.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return z.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected)if(e.mode===tn.PostProcess){const i=e.getBlockByPredicate(s=>s.name==="uv"&&t(s));i&&i.connectTo(this)}else{const i=e.mode===tn.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate(r=>r.isAttribute&&r.name===i&&t(r));s||(s=new bt("uv"),s.setAsAttribute(i)),s.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 s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!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||(this._textureName?(e.setTexture(this._textureName,this.texture),e.setTextureSampler(this._samplerName,this.texture._texture)):e.setTexture(this._samplerName,this.texture)))}get _isMixed(){return this.target!==z.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,M.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,M.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,M.Matrix,this._defineName);const i=e._getShaderType(M.Vector4),s=e._getShaderType(M.Vector2);if(e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${s}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0)); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${t.associatedVariableName}.xy; +`,e.compilationString+=`#endif +`,!!this._outputs.some(r=>r.isConnectedInVertexShader)){this._writeTextureRead(e,!0);for(const r of this._outputs)r.hasEndpoints&&r.name!=="level"&&this._writeOutput(e,r,r.name,!0)}}_getUVW(e){var r,n,o,l;let t=e;const i=((n=(r=this._texture)==null?void 0:r._texture)==null?void 0:n.is2DArray)??!1,s=((l=(o=this._texture)==null?void 0:o._texture)==null?void 0:l.is3D)??!1;if(i){const h=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${h})`}else if(s){const h=this.layer.isConnected?this.layer.associatedVariableName:"0";t=`vec3(${e}, ${h})`}return t}_samplerFunc(e){return e.shaderLanguage===vt.WGSL?e.target===z.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===vt.WGSL){const i=t.target===z.Vertex;return`${this._samplerFunc(t)}(${this._textureName},${this.samplerName}, ${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,M.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)}; +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,M.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===z.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===z.Fragment){e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,M.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} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===z.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===z.Fragment){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let r="";this.disableLevelMultiplication||(r=` * ${(e.shaderLanguage===vt.WGSL?"uniforms.":"")+this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var i,s,r,n;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===z.Vertex||this._fragmentOnly||e.target===z.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===z.Fragment||this._isMixed&&e.target===z.Vertex){if(!this._imageSource){const o=e._getFreeVariableName(this.name);this._samplerName=o+"Sampler",e.shaderLanguage===vt.WGSL&&(this._textureName=o+"Texture"),(s=(i=this._texture)==null?void 0:i._texture)!=null&&s.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName,this._textureName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==z.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(o=>o.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((n=(r=this._texture)==null?void 0:r._texture)!=null&&n.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName,this._textureName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,M.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){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=X.Parse(e.texture,t,i))}}H("BABYLON.TextureBlock",Ig);class Gp extends Je{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=(e==null?void 0:e.getScene())??We.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?z.Fragment:z.VertexAndFragment)}constructor(e){super(e,z.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(s=>s.isAttribute&&s.name==="position"&&t(s));i||(i=new bt("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.World&&t(s));i||(i=new bt("world"),i.setAsSystemValue(It.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.View&&t(s));i||(i=new bt("view"),i.setAsSystemValue(It.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();!s||!s.getTextureMatrix||(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,s.coordinatesMode===0,!0),i.setValue(this._defineSkyboxName,s.coordinatesMode===5,!0),i.setValue(this._defineCubicName,s.coordinatesMode===3||s.coordinatesMode===6,!0),i.setValue("INVERTCUBICMAP",s.coordinatesMode===6,!0),i.setValue(this._defineSphericalName,s.coordinatesMode===1,!0),i.setValue(this._definePlanarName,s.coordinatesMode===2,!0),i.setValue(this._defineProjectionName,s.coordinatesMode===4,!0),i.setValue(this._defineEquirectangularName,s.coordinatesMode===7,!0),i.setValue(this._defineEquirectangularFixedName,s.coordinatesMode===8,!0),i.setValue(this._defineMirroredEquirectangularFixedName,s.coordinatesMode===9,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(!(!i||!r)&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const n=r;e.setVector3(this._reflectionPositionName,n.boundingBoxPosition),e.setVector3(this._reflectionSizeName,n.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===z.Vertex)return"";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,M.Matrix);let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,M.Vector4))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; +`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,M.Vector3,this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} +`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; +`,t+=`#endif +`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,M.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) +`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); +`,t+=`#endif +`),t}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._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,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"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,M.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,M.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,l=`${this.cameraPosition.associatedVariableName}`,h=`${this.view.associatedVariableName}`;e+=".xyz";let c=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${h}, ${r}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${l}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${l}.xyz, ${r}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${h}, ${r}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return s||(c+=`#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif +`),i||(c+=` + #ifdef ${this._define3DName} + vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; + #else + vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif +`),c}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let s=`${"vec"+(t.length===0?"4":t.length-1)} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?s+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:s+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,s+=` + #else +`,e?s+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:s+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,s+=`#endif +`,s}writeOutputs(e,t){let i="";if(e.target===z.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name}; +`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); +`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); +`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!ss.IgnoreTexturesAtLoadTime&&(i=e.texture.url.indexOf("data:")===0?"":i,e.texture.isCube?this.texture=Ms.Parse(e.texture,t,i):this.texture=X.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}v([it("Generate only fragment code",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Gp._OnGenerateOnlyFragmentCodeChanged}})],Gp.prototype,"generateOnlyFragmentCode",void 0);H("BABYLON.ReflectionTextureBaseBlock",Gp);class w$ extends Gp{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,U.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,U.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?z.Fragment:z.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?z.Fragment:z.Vertex}constructor(e){super(e),this.registerInput("position",M.AutoDetect,!1,z.Vertex),this.registerInput("worldPosition",M.Vector4,!1,z.Vertex),this.registerInput("worldNormal",M.Vector4,!1,z.Fragment),this.registerInput("world",M.Matrix,!1,z.Vertex),this.registerInput("cameraPosition",M.Vector3,!1,z.Fragment),this.registerInput("view",M.Matrix,!1,z.Fragment),this.registerOutput("rgb",M.Color3,z.Fragment),this.registerOutput("rgba",M.Color4,z.Fragment),this.registerOutput("r",M.Float,z.Fragment),this.registerOutput("g",M.Float,z.Fragment),this.registerOutput("b",M.Float,z.Fragment),this.registerOutput("a",M.Float,z.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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(s=>s.systemValue===It.CameraPosition&&t(s));i||(i=new bt("cameraPosition"),i.setAsSystemValue(It.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==z.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+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); +`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}H("BABYLON.ReflectionTextureBlock",w$);class vx extends Je{constructor(e){super(e,z.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",M.AutoDetect,!1,z.VertexAndFragment),this.registerOutput("depth",M.Float,z.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.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?z.VertexAndFragment:z.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===M.Vector3?M.Vector3:t.type===M.Vector4?M.Vector4:M.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,M.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===z.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===z.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===z.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===z.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!==z.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([it("Use non linear depth",Qe.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],vx.prototype,"useNonLinearDepth",void 0);v([it("Store Camera space Z",Qe.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(a,e)=>{const t=e;let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),a&&a.disableDepthRenderer(),i}}})],vx.prototype,"storeCameraSpaceZ",void 0);v([it("Force 32 bits float",Qe.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:a=>a==null?void 0:a.disableDepthRenderer()}})],vx.prototype,"force32itsFloat",void 0);H("BABYLON.SceneDepthBlock",vx);class F$ extends Je{constructor(e){super(e,z.VertexAndFragment,!0),this.registerInput("worldPosition",M.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")}get worldPosition(){return this._inputs[0]}get target(){return z.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),l=!!(t.clipPlane4??s.clipPlane4),h=!!(t.clipPlane5??s.clipPlane5),c=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",l,!0),i.setValue("CLIPPLANE5",h,!0),i.setValue("CLIPPLANE6",c,!0)}bind(e,t,i){if(!i)return;const s=i.getScene();pa(e,t,s)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==z.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",M.Vector4),e._emitUniformFromString("vClipPlane2",M.Vector4),e._emitUniformFromString("vClipPlane3",M.Vector4),e._emitUniformFromString("vClipPlane4",M.Vector4),e._emitUniformFromString("vClipPlane5",M.Vector4),e._emitUniformFromString("vClipPlane6",M.Vector4);return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}H("BABYLON.ClipPlanesBlock",F$);class L$ extends Je{get texture(){return null}set texture(e){}constructor(e,t=z.VertexAndFragment){super(e,t,!1),this.registerOutput("position",M.Object,z.VertexAndFragment,new es("position",this,Ui.Output,lo,"ImageSourceBlock")),this.registerOutput("depth",M.Object,z.VertexAndFragment,new es("depth",this,Ui.Output,lo,"ImageSourceBlock")),this.registerOutput("normal",M.Object,z.VertexAndFragment,new es("normal",this,Ui.Output,lo,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==z.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const s=t.getScene().enablePrePassRenderer();if(!s)return;const r=s.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[s.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[s.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[s.getIndex(6)]))}}H("BABYLON.PrePassTextureBlock",L$);class B$ extends Je{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==z.VertexAndFragment)return t.target;if(e.connectedPoint.target!==z.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,z.Neutral),this._endpoints=[],this.registerInput("input",M.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 s of this.endpoints)t.indexOf(s)===-1&&(i+=s._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}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);t!==-1&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}H("BABYLON.NodeMaterialTeleportInBlock",B$);class U$ extends Je{constructor(e){super(e,z.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",M.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}}H("BABYLON.NodeMaterialTeleportOutBlock",U$);class V$ extends qg{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}}H("BABYLON.AddBlock",V$);class k$ extends Je{constructor(e){super(e,z.Neutral),this.registerInput("input",M.AutoDetect),this.registerInput("factor",M.Float),this.registerOutput("output",M.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}}H("BABYLON.ScaleBlock",k$);class pC extends Je{constructor(e){super(e,z.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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];return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${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([it("Minimum",Qe.Float)],pC.prototype,"minimum",void 0);v([it("Maximum",Qe.Float)],pC.prototype,"maximum",void 0);H("BABYLON.ClampBlock",pC);class G$ extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Vector2),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.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}}H("BABYLON.CrossBlock",G$);class z$ extends Je{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(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),this._outputs.forEach(r=>{const n=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),o=e._getGLType(r.type);t=t.replace(n,o),i=i.replace(n,o)}),e._emitFunction(i,t,""),this._outputs.forEach(r=>{e.compilationString+=e._declareOutput(r)+`; +`}),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach((r,n)=>{var o,l;n>0&&(e.compilationString+=", "),this._inputSamplers&&this._inputSamplers.indexOf(r.name)!==-1?e.compilationString+=((l=(o=r.connectedPoint)==null?void 0:o.ownerBlock)==null?void 0:l.samplerName)??r.associatedVariableName:e.compilationString+=r.associatedVariableName,s=!0}),this._outputs.forEach((r,n)=>{(n>0||s)&&(e.compilationString+=", "),e.compilationString+=r.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,s;this._options=e,this._code=e.code.join(` +`)+` +`,this.name=this.name||e.name,this.target=z[e.target],(t=e.inParameters)==null||t.forEach((r,n)=>{const o=M[r.type];r.type==="sampler2D"||r.type==="samplerCube"?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(r.name),this.registerInput(r.name,M.Object,!0,z.VertexAndFragment,new es(r.name,this,Ui.Input,lo,"ImageSourceBlock"))):this.registerInput(r.name,o),Object.defineProperty(this,r.name,{get:function(){return this._inputs[n]},enumerable:!0,configurable:!0})}),(i=e.outParameters)==null||i.forEach((r,n)=>{this.registerOutput(r.name,M[r.type]),Object.defineProperty(this,r.name,{get:function(){return this._outputs[n]},enumerable:!0,configurable:!0}),r.type==="BasedOnInput"&&(this._outputs[n]._typeConnectionSource=this._findInputByName(r.typeFromInput)[0])}),(s=e.inLinkedConnectionTypes)==null||s.forEach(r=>{this._linkConnectionTypes(this._findInputByName(r.input1)[1],this._findInputByName(r.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.CameraPosition&&t(s));i||(i=new bt("cameraPosition"),i.setAsSystemValue(It.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}}H("BABYLON.ViewDirectionBlock",hM);class Q$ extends Je{constructor(e){super(e,z.Neutral),this.registerInput("worldNormal",M.Vector4),this.registerInput("viewDirection",M.Vector3),this.registerInput("bias",M.Float),this.registerInput("power",M.Float),this.registerOutput("fresnel",M.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 hM("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const t=new bt("bias");t.value=0,t.output.connectTo(this.bias)}if(!this.power.isConnected){const t=new bt("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}}H("BABYLON.FresnelBlock",Q$);class Z$ extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.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}}H("BABYLON.MaxBlock",Z$);class J$ extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.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}}H("BABYLON.MinBlock",J$);class e6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.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}}H("BABYLON.DistanceBlock",e6);class t6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.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}}H("BABYLON.LengthBlock",t6);class i6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerOutput("output",M.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}}H("BABYLON.NegateBlock",i6);class s6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerInput("power",M.AutoDetect),this.registerOutput("output",M.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}}H("BABYLON.PowBlock",s6);class r6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("seed",M.AutoDetect),this.registerOutput("output",M.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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}}H("BABYLON.RandomNumberBlock",r6);class n6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("x",M.Float),this.registerInput("y",M.Float),this.registerOutput("output",M.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===vt.WGSL?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); +`,this}}H("BABYLON.ArcTan2Block",n6);class a6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerInput("edge0",M.Float),this.registerInput("edge1",M.Float),this.registerOutput("output",M.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}}H("BABYLON.SmoothStepBlock",a6);class o6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.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===M.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName}; +`,this}}H("BABYLON.ReciprocalBlock",o6);class l6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerInput("reference",M.AutoDetect),this.registerInput("distance",M.Float),this.registerInput("replacement",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(M.Float),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Float),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[3].excludedConnectionPointTypes.push(M.Float),this._inputs[3].excludedConnectionPointTypes.push(M.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}}H("BABYLON.ReplaceColorBlock",l6);class h6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("value",M.AutoDetect),this.registerInput("steps",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].excludedConnectionPointTypes.push(M.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(M.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}}H("BABYLON.PosterizeBlock",h6);var ru;(function(a){a[a.SawTooth=0]="SawTooth",a[a.Square=1]="Square",a[a.Triangle=2]="Triangle"})(ru||(ru={}));class c6 extends Je{constructor(e){super(e,z.Neutral),this.kind=ru.SawTooth,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.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 ru.SawTooth:{e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break}case ru.Square:{e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break}case ru.Triangle:{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}}H("BABYLON.WaveBlock",c6);class bE{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 u6 extends Je{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,z.Neutral),this.colorSteps=[new bE(0,re.Black()),new bE(1,re.White())],this.onValueChangedObservable=new K,this.registerInput("gradient",M.AutoDetect),this.registerOutput("output",M.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Float|M.Vector2|M.Vector3|M.Vector4|M.Color3|M.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(M.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.); +`;return}const s=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(s,M.Vector3)} = ${this._writeColorConstant(0,i)}; +`,e.compilationString+=`${e._declareLocalVar(r,M.Float)}; +`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==M.Float&&(n+=".x");for(let o=1;o!0){if(!this.intensity.isConnected){const i=new bt("Refraction intensity",z.Fragment,M.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.View&&t(s));i||(i=new bt("view"),i.setAsSystemValue(It.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.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,h;super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=((l=this.volumeIndexOfRefraction.connectInputBlock)==null?void 0:l.value)??((h=this.indexOfRefractionConnectionPoint.connectInputBlock)==null?void 0:h.value)??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,Ne.Log2(o)),s.boundingBoxSize){const c=s;e.setVector3("vRefractionPosition",c.boundingBoxPosition),e.setVector3("vRefractionSize",c.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"),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,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,M.Matrix),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,M.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,M.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,M.Vector2),e._emitUniformFromString("vRefractionPosition",M.Vector3),e._emitUniformFromString("vRefractionSize",M.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=Ms.Parse(e.texture,t,i):this.texture=X.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}v([it("Link refraction to transparency",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Sc.prototype,"linkRefractionWithTransparency",void 0);v([it("Invert refraction Y",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Sc.prototype,"invertRefractionY",void 0);v([it("Use thickness as depth",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Sc.prototype,"useThicknessAsDepth",void 0);H("BABYLON.RefractionBlock",Sc);class Wp extends Je{constructor(e){super(e,z.Fragment),this._isUnique=!0,this.registerInput("thickness",M.Float,!1,z.Fragment),this.registerInput("tintColor",M.Color3,!0,z.Fragment),this.registerInput("translucencyIntensity",M.Float,!0,z.Fragment),this.registerInput("translucencyDiffusionDist",M.Color3,!0,z.Fragment),this.registerInput("refraction",M.Object,!0,z.Fragment,new es("refraction",this,Ui.Input,Sc,"RefractionBlock")),this.registerInput("dispersion",M.Float,!0,z.Fragment),this.registerOutput("subsurface",M.Object,z.Fragment,new es("subsurface",this,Ui.Output,Wp,"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 bt("SubSurface thickness",z.Fragment,M.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!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,s){var _;let r="";const n=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.",h=t!=null&&t.translucencyDiffusionDist.isConnected?t==null?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",c=t!=null&&t.refraction.isConnected?(_=t==null?void 0:t.refraction.connectedPoint)==null?void 0:_.ownerBlock:null,u=c!=null&&c.tintAtDistance.isConnected?c.tintAtDistance.associatedVariableName:"1.",d=c!=null&&c.intensity.isConnected?c.intensity.associatedVariableName:"1.",f=c!=null&&c.view.isConnected?c.view.associatedVariableName:"",m=t!=null&&t.dispersion.isConnected?t==null?void 0:t.dispersion.associatedVariableName:"0.0";return r+=(c==null?void 0:c.getCode(e))??"",r+=`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${n}); + vec4 vTintColor = vec4(${o}, ${u}); + vec3 vSubSurfaceIntensity = vec3(${d}, ${l}, 0.); + float dispersion = ${m}; + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${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}, + ${i==null?void 0:i._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${s}.xyz, + viewDirectionW, + ${f}, + ${(c==null?void 0:c._vRefractionInfosName)??""}, + ${(c==null?void 0:c._refractionMatrixName)??""}, + ${(c==null?void 0:c._vRefractionMicrosurfaceInfosName)??""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${(c==null?void 0:c._defineLODRefractionAlpha)??"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${(c==null?void 0:c._defineLinearSpecularRefraction)??"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${(c==null?void 0:c._define3DName)??"IGNORE"} + ${(c==null?void 0:c._cubeSamplerName)??""}, + #else + ${(c==null?void 0:c._2DSamplerName)??""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${(c==null?void 0:c._define3DName)??"IGNORE"} + ${(c==null?void 0:c._cubeSamplerName)??""}, + ${(c==null?void 0:c._cubeSamplerName)??""}, + #else + ${(c==null?void 0:c._2DSamplerName)??""}, + ${(c==null?void 0:c._2DSamplerName)??""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${(c==null?void 0:c._vRefractionFilteringInfoName)??""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #ifdef SS_DISPERSION + dispersion, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${h}, + vTintColor, + #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE + vec4(0.), + #endif + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`,r}_buildBlock(e){return e.target===z.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}H("BABYLON.SubSurfaceBlock",Wp);const T6={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 Ys extends Je{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,U.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?z.Fragment:z.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?z.Fragment:z.Vertex}constructor(e){super(e,z.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=re.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",M.Vector4,!1,z.Vertex),this.registerInput("worldNormal",M.Vector4,!1,z.Fragment),this.registerInput("view",M.Matrix,!1),this.registerInput("cameraPosition",M.Vector3,!1,z.Fragment),this.registerInput("perturbedNormal",M.Vector4,!0,z.Fragment),this.registerInput("baseColor",M.Color3,!0,z.Fragment),this.registerInput("metallic",M.Float,!1,z.Fragment),this.registerInput("roughness",M.Float,!1,z.Fragment),this.registerInput("ambientOcc",M.Float,!0,z.Fragment),this.registerInput("opacity",M.Float,!0,z.Fragment),this.registerInput("indexOfRefraction",M.Float,!0,z.Fragment),this.registerInput("ambientColor",M.Color3,!0,z.Fragment),this.registerInput("reflection",M.Object,!0,z.Fragment,new es("reflection",this,Ui.Input,Tf,"ReflectionBlock")),this.registerInput("clearcoat",M.Object,!0,z.Fragment,new es("clearcoat",this,Ui.Input,Mu,"ClearCoatBlock")),this.registerInput("sheen",M.Object,!0,z.Fragment,new es("sheen",this,Ui.Input,xf,"SheenBlock")),this.registerInput("subsurface",M.Object,!0,z.Fragment,new es("subsurface",this,Ui.Input,Wp,"SubSurfaceBlock")),this.registerInput("anisotropy",M.Object,!0,z.Fragment,new es("anisotropy",this,Ui.Input,Cx,"AnisotropyBlock")),this.registerInput("iridescence",M.Object,!0,z.Fragment,new es("iridescence",this,Ui.Input,zp,"IridescenceBlock")),this.registerOutput("ambientClr",M.Color3,z.Fragment),this.registerOutput("diffuseDir",M.Color3,z.Fragment),this.registerOutput("specularDir",M.Color3,z.Fragment),this.registerOutput("clearcoatDir",M.Color3,z.Fragment),this.registerOutput("sheenDir",M.Color3,z.Fragment),this.registerOutput("diffuseInd",M.Color3,z.Fragment),this.registerOutput("specularInd",M.Color3,z.Fragment),this.registerOutput("clearcoatInd",M.Color3,z.Fragment),this.registerOutput("sheenInd",M.Color3,z.Fragment),this.registerOutput("refraction",M.Color3,z.Fragment),this.registerOutput("lighting",M.Color3,z.Fragment),this.registerOutput("shadow",M.Float,z.Fragment),this.registerOutput("alpha",M.Float,z.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")}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(s=>s.systemValue===It.CameraPosition&&t(s));i||(i=new bt("cameraPosition"),i.setAsSystemValue(It.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(s=>s.systemValue===It.View&&t(s));i||(i=new bt("view"),i.setAsSystemValue(It.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===ei.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===ei.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!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 r=e.getScene();if(r.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&&Ce.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)c_(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Yg(r,i);else{const o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Tv(r,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Sv(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,n)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var u;if(!i)return;const s=i.getScene();this.light?mv(this.light,this._lightId,s,e,!0):h_(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(s._mirroredCameraPosition!=null);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=1,l=((u=this.indexOfRefraction.connectInputBlock)==null?void 0:u.value)??1.5,h=Math.pow((l-o)/(l+o),2);this._metallicReflectanceColor.scaleToRef(h*this._metallicF0Factor,Yt.Color3[0]);const c=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,Yt.Color3[0],c),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var n;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 s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,M.Vector4)&&(e.compilationString+=`${s} = ${t.associatedVariableName}; +`);const r=this.reflection.isConnected?(n=this.reflection.connectedPoint)==null?void 0:n.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=(r==null?void 0:r.handleVertexSide(e))??"",e._emitVaryingFromString("vClipSpacePosition",M.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 +`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; +`,e._injectAtEnd+=`#endif +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; +`;const t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+=`albedoOpacityBlock( + vec4(${t}, 1.), + #ifdef ALBEDO + vec4(1.), + vec2(1., 1.), + #endif + #ifdef OPACITY + vec4(${i}), + vec2(1., 1.), + #endif + albedoOpacityOut + ); + + vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; + float alpha = albedoOpacityOut.alpha; +`,e}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; +`;const t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+=`ambientOcclusionBlock( + #ifdef AMBIENT + vec3(${t}), + vec4(0., 1.0, 1.0, 0.), + #endif + aoOut + ); +`,e}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; +`;const i="1.";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,M.Vector4),t+=`vec3 baseColor = surfaceAlbedo; + + reflectivityBlock( + vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), + #ifdef METALLICWORKFLOW + surfaceAlbedo, + ${this._vMetallicReflectanceFactorsName}, + #endif + #ifdef REFLECTIVITY + vec3(0., 0., ${i}), + vec4(1.), + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor, + #endif + #ifdef MICROSURFACEMAP + microSurfaceTexel, <== not handled! + #endif + reflectivityOut + ); + + 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 +`,t}_buildBlock(e){var S,C,y,A,I,R,N,k,B,Q,ne;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=sC(this._scene));const t=this.reflection.isConnected?(S=this.reflection.connectedPoint)==null?void 0:S.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==z.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 i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r}; +`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 +`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); +`,e.compilationString+=`#endif +`):r="v_"+r,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",M.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",M.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",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity",M.Vector4),t!=null&&t.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); +`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"}; +`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,M.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+=`#ifdef UNLIT + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?(C=this.anisotropy.connectedPoint)==null?void 0:C.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:(t==null?void 0:t._vReflectionFilteringInfoName)??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?(y=this.sheen.connectedPoint)==null?void 0:y.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"}]});const l=this.iridescence.isConnected?(A=this.iridescence.connectedPoint)==null?void 0:A.ownerBlock:null;e.compilationString+=zp.GetCode(l),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const h=this.clearcoat.isConnected?(I=this.clearcoat.connectedPoint)==null?void 0:I.ownerBlock:null,c=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,u=this.perturbedNormal.isConnected&&((N=((R=this.perturbedNormal.connectedPoint)==null?void 0:R.ownerBlock).worldTangent)==null?void 0:N.isConnected),d=this.anisotropy.isConnected&&((k=this.anisotropy.connectedPoint)==null?void 0:k.ownerBlock).worldTangent.isConnected;let f=u||!this.perturbedNormal.isConnected&&d;e.compilationString+=Mu.GetCode(e,h,t,r,c,f,this.worldNormal.associatedVariableName),c&&(f=(h==null?void 0:h.worldTangent.isConnected)??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._defineProjectionName)??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:(t==null?void 0:t._defineLODReflectionAlpha)??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:(t==null?void 0:t._defineLinearSpecularReflection)??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:f?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:(t==null?void 0:t._defineSkyboxName)??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"}]});const m=this.subsurface.isConnected?(B=this.subsurface.connectedPoint)==null?void 0:B.ownerBlock:null,_=this.subsurface.isConnected?(ne=((Q=this.subsurface.connectedPoint)==null?void 0:Q.ownerBlock).refraction.connectedPoint)==null?void 0:ne.ownerBlock:null;_&&(_.viewConnectionPoint=this.view,_.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Wp.GetCode(e,m,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:(t==null?void 0:t._define3DName)??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:(t==null?void 0:t._defineOppositeZ)??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:(t==null?void 0:t._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",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+=`#endif +`;const x=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let E=ei.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();E.indexOf(".")===-1&&(E+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:x+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:E}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:`vec3(1.); +gl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb); +`}]});for(const de of this._outputs)if(de.hasEndpoints){const ge=T6[de.name];if(ge){const[fe,Ee]=ge;Ee&&(e.compilationString+=`#if ${Ee} +`),e.compilationString+=`${e._declareOutput(de)} = ${fe}; +`,Ee&&(e.compilationString+=`#else +`,e.compilationString+=`${e._declareOutput(de)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else U.Error(`There's no remapping for the ${de.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([it("Direct lights",Qe.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Ys.prototype,"directIntensity",void 0);v([it("Environment lights",Qe.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Ys.prototype,"environmentIntensity",void 0);v([it("Specular highlights",Qe.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],Ys.prototype,"specularIntensity",void 0);v([it("Light falloff",Qe.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:ei.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:ei.LIGHTFALLOFF_GLTF},{label:"Standard",value:ei.LIGHTFALLOFF_STANDARD}]})],Ys.prototype,"lightFalloff",void 0);v([it("Alpha Testing",Qe.Boolean,"OPACITY")],Ys.prototype,"useAlphaTest",void 0);v([it("Alpha CutOff",Qe.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],Ys.prototype,"alphaTestCutoff",void 0);v([it("Alpha blending",Qe.Boolean,"OPACITY")],Ys.prototype,"useAlphaBlending",void 0);v([it("Radiance over alpha",Qe.Boolean,"RENDERING",{notifiers:{update:!0}})],Ys.prototype,"useRadianceOverAlpha",void 0);v([it("Specular over alpha",Qe.Boolean,"RENDERING",{notifiers:{update:!0}})],Ys.prototype,"useSpecularOverAlpha",void 0);v([it("Specular anti-aliasing",Qe.Boolean,"RENDERING",{notifiers:{update:!0}})],Ys.prototype,"enableSpecularAntiAliasing",void 0);v([it("Realtime filtering",Qe.Boolean,"RENDERING",{notifiers:{update:!0}})],Ys.prototype,"realTimeFiltering",void 0);v([it("Realtime filtering quality",Qe.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],Ys.prototype,"realTimeFilteringQuality",void 0);v([it("Energy Conservation",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Ys.prototype,"useEnergyConservation",void 0);v([it("Radiance occlusion",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Ys.prototype,"useRadianceOcclusion",void 0);v([it("Horizon occlusion",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Ys.prototype,"useHorizonOcclusion",void 0);v([it("Unlit",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Ys.prototype,"unlit",void 0);v([it("Force normal forward",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],Ys.prototype,"forceNormalForward",void 0);v([it("Generate only fragment code",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Ys._OnGenerateOnlyFragmentCodeChanged}})],Ys.prototype,"generateOnlyFragmentCode",void 0);v([it("Debug mode",Qe.List,"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}]})],Ys.prototype,"debugMode",void 0);v([it("Split position",Qe.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],Ys.prototype,"debugLimit",void 0);v([it("Output factor",Qe.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],Ys.prototype,"debugFactor",void 0);H("BABYLON.PBRMetallicRoughnessBlock",Ys);class E6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("left",M.AutoDetect),this.registerInput("right",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(M.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===vt.GLSL?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName}); +`,this}}H("BABYLON.ModBlock",E6);class S6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("row0",M.Vector4),this.registerInput("row1",M.Vector4),this.registerInput("row2",M.Vector4),this.registerInput("row3",M.Vector4),this.registerOutput("output",M.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 bt("row0");e.value=new tt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new bt("row1");e.value=new tt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new bt("row2");e.value=new tt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new bt("row3");e.value=new tt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3;return e.compilationString+=e._declareOutput(t)+` = mat4(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName}); +`,this}}H("BABYLON.MatrixBuilder",S6);var ia;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(ia||(ia={}));class v6 extends Je{constructor(e){super(e,z.Neutral),this.condition=ia.LessThan,this.registerInput("a",M.Float),this.registerInput("b",M.Float),this.registerInput("true",M.AutoDetect,!0),this.registerInput("false",M.AutoDetect,!0),this.registerOutput("output",M.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=M.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",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ia.Equal:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)}; +`;break}case ia.NotEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)}; +`;break}case ia.LessThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)}; +`;break}case ia.LessOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)}; +`;break}case ia.GreaterThan:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)}; +`;break}case ia.GreaterOrEqual:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)}; +`;break}case ia.Xor:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)}; +`;break}case ia.Or:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)}; +`;break}case ia.And:{e.compilationString+=e._declareOutput(t)+` = ${e._generateTertiary(i,s,`(${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.${ia[this.condition]}; +`}}H("BABYLON.ConditionalBlock",v6);class uM extends Je{constructor(e){super(e,z.Neutral),this.octaves=6,this.registerInput("seed",M.AutoDetect),this.registerInput("chaos",M.AutoDetect,!0),this.registerInput("offsetX",M.Float,!0),this.registerInput("offsetY",M.Float,!0),this.registerInput("offsetZ",M.Float,!0),this.registerOutput("output",M.Float),this._inputs[0].acceptedConnectionPointTypes.push(M.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(M.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,h;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;const t=` + + float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise(in vec2 x, in 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 cloudNoise(in vec3 x, in 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 fbm(in vec2 st, in vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise(st, chaos); + st *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm(in vec3 x, in vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + for (int i = 0; i < OCTAVES; ++i) { + value += amplitude * cloudNoise(x, chaos); + x = x * 2.0; + amplitude *= 0.5; + } + return value; + }`,s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(this.octaves|0).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=((l=this.seed.connectedPoint)==null?void 0:l.type)===M.Vector2?"vec2":"vec3";e.compilationString+=`${n} ${r} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&n==="vec3"&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let o="";return this.chaos.isConnected?o=this.chaos.associatedVariableName:o=((h=this.seed.connectedPoint)==null?void 0:h.type)===M.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=e._declareOutput(this._outputs[0])+` = ${s}(${r}, ${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([it("Octaves",Qe.Int)],uM.prototype,"octaves",void 0);H("BABYLON.CloudBlock",uM);class C6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("seed",M.Vector2),this.registerInput("offset",M.Float),this.registerInput("density",M.Float),this.registerOutput("output",M.Float),this.registerOutput("cells",M.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 seed, float offset){ + mat2 m = mat2(15.27, 47.63, 99.41, 89.98); + vec2 uv = fract(sin(m * seed) * 46839.32); + return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); + } + `;e.shaderLanguage===vt.WGSL&&(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 g = floor(seed * density); + vec2 f = fract(seed * density); + float t = 8.0; + vec3 res = vec3(8.0, 0.0, 0.0); + + for(int y=-1; y<=1; y++) + { + for(int x=-1; x<=1; x++) + { + vec2 lattice = vec2(float(x),float(y)); + vec2 randomOffset = voronoiRandom(lattice + g, offset); + float d = distance(lattice + randomOffset, f); + if(d < res.x) + { + res = vec3(d, randomOffset.x, randomOffset.y); + [*]outValue = res.x; + [*]cells = res.y; + } + } + } + } + `,e.shaderLanguage===vt.WGSL?t=e._babylonSLtoWGSL(t):t=e._babylonSLtoGLSL(t),e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),s=e._getFreeVariableName("tempCells"),r=e.shaderLanguage===vt.WGSL?"&":"";return e.compilationString+=`${e._declareLocalVar(i,M.Float)} = 0.0; +`,e.compilationString+=`${e._declareLocalVar(s,M.Float)} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${r}${i}, ${r}${s}); +`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=e._declareOutput(this.cells)+` = ${s}; +`),this}}H("BABYLON.VoronoiNoiseBlock",C6);class b6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==z.VertexAndFragment)return t.target;if(e.connectedPoint.target!==z.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=e._declareOutput(t)+` = ${i.associatedVariableName}; +`,this}}H("BABYLON.ElbowBlock",b6);class _C extends Je{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())??We.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,i=>i.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()??We.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()??We.LastCreatedScene;t==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,z.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",M.AutoDetect,!1),this.registerInput("normal",M.AutoDetect,!1),this.registerInput("sharpness",M.Float,!0),this.registerInput("source",M.Object,!0,z.VertexAndFragment,new es("source",this,Ui.Input,lo,"ImageSourceBlock")),this.registerInput("sourceY",M.Object,!0,z.VertexAndFragment,new es("sourceY",this,Ui.Input,lo,"ImageSourceBlock")),t||this.registerInput("sourceZ",M.Object,!0,z.VertexAndFragment,new es("sourceZ",this,Ui.Input,lo,"ImageSourceBlock")),this.registerOutput("rgba",M.Color4,z.Neutral),this.registerOutput("rgb",M.Color3,z.Neutral),this.registerOutput("r",M.Float,z.Neutral),this.registerOutput("g",M.Float,z.Neutral),this.registerOutput("b",M.Float,z.Neutral),this.registerOutput("a",M.Float,z.Neutral),this.registerOutput("level",M.Float,z.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(M.Color3|M.Vector3|M.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 s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!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))}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),l=e._getFreeVariableName("z"),h=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),u=e._getFreeVariableName("uvx"),d=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${c} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${u} = ${this.position.associatedVariableName}.yz; + vec2 ${d} = ${this.position.associatedVariableName}.zx; + vec2 ${f} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${u}.xy = ${u}.yx; + + if (${c}.x >= 0.0) { + ${u}.x = -${u}.x; + } + if (${c}.y < 0.0) { + ${d}.y = -${d}.y; + } + if (${c}.z < 0.0) { + ${f}.x = -${f}.x; + } + `),e.compilationString+=` + vec4 ${n} = texture2D(${t}, ${u}); + vec4 ${o} = texture2D(${i}, ${d}); + vec4 ${l} = texture2D(${s}, ${f}); + + // blend weights + vec3 ${h} = pow(abs(${c}), vec3(${r})); + + // blend and return + vec4 ${this._tempTextureRead} = (${n}*${h}.x + ${o}*${h}.y + ${l}*${h}.z) / (${h}.x + ${h}.y + ${h}.z); + `}_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} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s}; +`,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=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+"Sampler"),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,M.Float),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&i.name!=="level"&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; +`,this.texture&&(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`),e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,!this.hasImageSource&&this.texture&&!this.texture.isRenderTarget&&this.texture.getClassName()!=="VideoTexture"&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!ss.IgnoreTexturesAtLoadTime&&e.texture.url!==void 0&&(i=e.texture.url.indexOf("data:")===0?"":i,this.texture=X.Parse(e.texture,t,i))}}v([it("Project as cube",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],_C.prototype,"projectAsCube",void 0);H("BABYLON.TriPlanarBlock",_C);class y6 extends _C{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),f=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : + (${o}.y>${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : + (${o}.y<${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${c} = ivec3(3) - ${h} - ${l}; + + // project+fetch + vec4 ${u} = textureGrad( ${t}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), + vec2(${r}[${l}.y],${r}[${l}.z]), + vec2(${n}[${l}.y],${n}[${l}.z]) ); + vec4 ${d} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), + vec2(${r}[${c}.y],${r}[${c}.z]), + vec2(${n}[${c}.y],${n}[${c}.z]) ); + + // blend factors + vec2 ${f} = vec2(${o}[${l}.x],${o}[${c}.x]); + // make local support + ${f} = clamp( (${f}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${f} = pow( ${f}, vec2(${s}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${u}*${f}.x + ${d}*${f}.y) / (${f}.x + ${f}.y); + `}}H("BABYLON.BiPlanarBlock",y6);class A6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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}}H("BABYLON.MatrixDeterminantBlock",A6);class R6 extends Je{constructor(e){super(e,z.Neutral),this.registerInput("input",M.Matrix),this.registerOutput("output",M.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)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); +`,this}}H("BABYLON.MatrixTransposeBlock",R6);var yi;(function(a){a[a.None=0]="None",a[a.Normal=1]="Normal",a[a.Tangent=2]="Tangent",a[a.VertexColor=3]="VertexColor",a[a.UV1=4]="UV1",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6"})(yi||(yi={}));class dM extends Je{constructor(e){super(e,z.Neutral),this.attributeType=yi.None,this.registerInput("input",M.AutoDetect),this.registerInput("fallback",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(t=>{var s;if(this.attributeType)return;const i=t.ownerBlock;if(i instanceof bt&&i.isAttribute)switch(i.name){case"color":this.attributeType=yi.VertexColor;break;case"normal":this.attributeType=yi.Normal;break;case"tangent":this.attributeType=yi.Tangent;break;case"uv":this.attributeType=yi.UV1;break;case"uv2":this.attributeType=yi.UV2;break;case"uv3":this.attributeType=yi.UV3;break;case"uv4":this.attributeType=yi.UV4;break;case"uv5":this.attributeType=yi.UV5;break;case"uv6":this.attributeType=yi.UV6;break}else if(i instanceof aM)switch((s=this.input.connectedPoint)==null?void 0:s.name){case"normalOutput":this.attributeType=yi.Normal;break;case"tangentOutput":this.attributeType=yi.Tangent;break;case"uvOutput":this.attributeType=yi.UV1;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 yi.VertexColor:t="VERTEXCOLOR_NME";break;case yi.Normal:t="NORMAL";break;case yi.Tangent:t="TANGENT";break;case yi.UV1:t="UV1";break;case yi.UV2:t="UV2";break;case yi.UV3:t="UV3";break;case yi.UV4:t="UV4";break;case yi.UV5:t="UV5";break;case yi.UV6: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??yi.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType}; +`,e}}v([it("Attribute lookup",Qe.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:yi.None},{label:"Normal",value:yi.Normal},{label:"Tangent",value:yi.Tangent},{label:"Vertex Color",value:yi.VertexColor},{label:"UV1",value:yi.UV1},{label:"UV2",value:yi.UV2},{label:"UV3",value:yi.UV3},{label:"UV4",value:yi.UV4},{label:"UV5",value:yi.UV5},{label:"UV6",value:yi.UV6}]})],dM.prototype,"attributeType",void 0);H("BABYLON.MeshAttributeExistsBlock",dM);var Li;(function(a){a[a.EaseInSine=0]="EaseInSine",a[a.EaseOutSine=1]="EaseOutSine",a[a.EaseInOutSine=2]="EaseInOutSine",a[a.EaseInQuad=3]="EaseInQuad",a[a.EaseOutQuad=4]="EaseOutQuad",a[a.EaseInOutQuad=5]="EaseInOutQuad",a[a.EaseInCubic=6]="EaseInCubic",a[a.EaseOutCubic=7]="EaseOutCubic",a[a.EaseInOutCubic=8]="EaseInOutCubic",a[a.EaseInQuart=9]="EaseInQuart",a[a.EaseOutQuart=10]="EaseOutQuart",a[a.EaseInOutQuart=11]="EaseInOutQuart",a[a.EaseInQuint=12]="EaseInQuint",a[a.EaseOutQuint=13]="EaseOutQuint",a[a.EaseInOutQuint=14]="EaseInOutQuint",a[a.EaseInExpo=15]="EaseInExpo",a[a.EaseOutExpo=16]="EaseOutExpo",a[a.EaseInOutExpo=17]="EaseInOutExpo",a[a.EaseInCirc=18]="EaseInCirc",a[a.EaseOutCirc=19]="EaseOutCirc",a[a.EaseInOutCirc=20]="EaseInOutCirc",a[a.EaseInBack=21]="EaseInBack",a[a.EaseOutBack=22]="EaseOutBack",a[a.EaseInOutBack=23]="EaseInOutBack",a[a.EaseInElastic=24]="EaseInElastic",a[a.EaseOutElastic=25]="EaseOutElastic",a[a.EaseInOutElastic=26]="EaseInOutElastic"})(Li||(Li={}));class I6 extends Je{constructor(e){super(e,z.Neutral),this.type=Li.EaseInOutSine,this.registerInput("input",M.AutoDetect),this.registerOutput("output",M.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(M.Matrix),this._inputs[0].excludedConnectionPointTypes.push(M.Object),this._inputs[0].excludedConnectionPointTypes.push(M.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 s=parseInt(t.replace("vec",""));let r=i?` + var ret: vec${s}f = vec${s}f(0.0); + `:` + vec${s} ret = vec${s}(0.0); + `;for(let n=1;n<=s;n++)r+=this._duplicateEntry(e,n===1?"x":n===2?"y":n===3?"z":"w")+`; +`;return r+=`return ret; +`,r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="";const r=e._getShaderType(this.input.type),n=e.shaderLanguage===vt.WGSL;switch(s=Li[this.type]+"_"+r.replace("<","").replace(">",""),this.type){case Li.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case Li.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case Li.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case Li.EaseInQuad:i="return v * v";break;case Li.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case Li.EaseInOutQuad:{const o=e._generateTertiary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,r,n);break}case Li.EaseInCubic:i="return v * v * v";break;case Li.EaseOutCubic:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",r,n);break}case Li.EaseInOutCubic:{const o=e._generateTertiary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(o,r,n);break}case Li.EaseInQuart:i="return v * v * v * v";break;case Li.EaseOutQuart:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",r,n);break}case Li.EaseInOutQuart:{const o=e._generateTertiary("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,r,n);break}case Li.EaseInQuint:i="return v * v * v * v * v";break;case Li.EaseOutQuint:{i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",r,n);break}case Li.EaseInOutQuint:{const o=e._generateTertiary("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,r,n);break}case Li.EaseInExpo:{const o=e._generateTertiary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(o,r,n);break}case Li.EaseOutExpo:{const o=e._generateTertiary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(o,r,n);break}case Li.EaseInOutExpo:{const o=e._generateTertiary("0.0",e._generateTertiary("1.0",e._generateTertiary("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,r,n);break}case Li.EaseInCirc:{i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",r,n);break}case Li.EaseOutCirc:{i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",r,n);break}case Li.EaseInOutCirc:{const o=e._generateTertiary("(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,r,n);break}case Li.EaseInBack:{i="return 2.70158 * v * v * v - 1.70158 * v * v";break}case Li.EaseOutBack:{i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",r,n);break}case Li.EaseInOutBack:{const o=e._generateTertiary("(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,r,n);break}case Li.EaseInElastic:{const o=e._generateTertiary("0.0",e._generateTertiary("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,r,n);break}case Li.EaseOutElastic:{const o=e._generateTertiary("0.0",e._generateTertiary("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,r,n);break}case Li.EaseInOutElastic:{const o=e._generateTertiary("0.0",e._generateTertiary("1.0",e._generateTertiary("-(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,r,n);break}}return n?e._emitFunction(s,`fn ${s}(v: ${r}) -> ${r} {${i};} +`,""):e._emitFunction(s,`${r} ${s}(${r} v) {${i};} +`,""),e.compilationString+=e._declareOutput(t)+` = ${s}(${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.${Li[this.type]}; +`}}H("BABYLON.CurveBlock",I6);class P6 extends Gr{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class g_ extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new P6,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;return!this._isEnabled||!(r!=null&&r.texture)||!Ce.DecalMapEnabled||!t.texturesEnabled?!0:r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;!this._isEnabled||!(s!=null&&s.texture)||!Ce.DecalMapEnabled||!t.texturesEnabled?(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1):((!e.DECAL||e.GAMMADECAL!==s.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=s.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,Oi(s.texture,e,"DECAL"))}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!this._isEnabled||!(r!=null&&r.texture)||!Ce.DecalMapEnabled||!t.texturesEnabled)return;const n=this._material.isFrozen,o=r.texture;(!e.useUbo||!n||!e.isSync)&&(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),wi(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}v([O(),_e("_markAllSubMeshesAsTexturesDirty")],g_.prototype,"isEnabled",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],g_.prototype,"smoothAlpha",void 0);H("BABYLON.DecalMapConfiguration",g_);var J0;(function(a){a[a.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",a[a.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",a[a.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"})(J0||(J0={}));var la;(function(a){a[a.COLOR_MODE_SET=0]="COLOR_MODE_SET",a[a.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",a[a.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"})(la||(la={}));var pl;(function(a){a[a.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",a[a.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"})(pl||(pl={}));class Ur{}Ur.DEFAULT_COLOR=re.White();Ur.DEFAULT_WIDTH_ATTENUATED=1;Ur.DEFAULT_WIDTH=.1;class di{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&typeof e[0]=="number")return[e];if(e.length&&Array.isArray(e[0])&&typeof e[0][0]=="number")return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof T){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof T){const t=[];return e.forEach(s=>{t.push(s.flatMap(r=>[r.x,r.y,r.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 s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),s.length===0?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return di._SearchInPoints(e,t,s)||r.push([e,t]),di._SearchInPoints(t,i,s)||r.push([t,i]),di._SearchInPoints(i,e,s)||r.push([i,e]),r.length===0?null:r}static _SearchInPoints(e,t,i){var s,r,n;for(const o of i)for(let l=0;l{const n=s.getVerticesData(P.PositionKind),o=s.getIndices();if(n&&o)for(let l=0,h=0;l[t.x,t.y,t.z])}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(e.length===0)return 0;let t;typeof e[0]=="number"?t=di.ToVector3Array(e):t=e;const i=W.Vector3[0];let s=0;for(let r=0;r{r.length>t?di.SegmentizeSegmentByCount(r.point1,r.point2,Math.ceil(r.length/t)).forEach(o=>{s.push(o)}):(s.push(r.point1),s.push(r.point2))}),s}static SegmentizeLineBySegmentCount(e,t){const i=typeof e[0]=="number"?di.ToVector3Array(e):e,s=di.GetLineLength(i)/t;return di.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;is.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const l=e.length;for(let c=0;c[r.x,r.y,r.z])}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],l=Gz(e,t,i,s);for(const h of l){for(const c of h.paths){const u=[],d=c.getPoints();for(const f of d)u.push(f.x,f.y,r);o.push(u)}if(n)for(const c of h.holes){const u=[],d=c.getPoints();for(const f of d)u.push(f.x,f.y,r);o.push(u)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(e.length*4);for(let i=0,s=0;ir?r:t.length,o=Math.ceil(t.length/r);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const l=di.Color3toRGBAUint8(t),h=new gs(l,n,o,ee.TEXTUREFORMAT_RGBA,s,!1,!0,i);return h.name=e,h}static PrepareEmptyColorsTexture(e){if(!Ur.EmptyColorsTexture){const t=new Uint8Array(4);Ur.EmptyColorsTexture=new gs(t,1,1,ee.TEXTUREFORMAT_RGBA,e,!1,!1,gs.NEAREST_NEAREST),Ur.EmptyColorsTexture.name="grlEmptyColorsTexture"}return Ur.EmptyColorsTexture}static DisposeEmptyColorsTexture(){var e;(e=Ur.EmptyColorsTexture)==null||e.dispose(),Ur.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class M6 extends Gr{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 fc extends hn{constructor(e,t,i){i=i||{color:Ur.DEFAULT_COLOR};const s=new M6;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===pl.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,fc.GREASED_LINE_MATERIAL_NAME,200,s),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?Ur.DEFAULT_WIDTH_ATTENUATED:Ur.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??la.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??pl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??gs.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new ce(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=di.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??Ur.DEFAULT_COLOR,di.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{di.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 r=this._scene.activeCamera;if(r){const o=r.getProjectionMatrix();e.updateMatrix("grl_projection",o)}else throw Error("GreasedLinePluginMaterial requires an active camera.");const n=W.Vector4[0];n.x=this._aspect,n.y=this._resolution.x,n.z=this._resolution.y,n.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",n)}const t=W.Vector4[0];t.x=di.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=W.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=di.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const s=this.colorsTexture??Ur.EmptyColorsTexture;e.setTexture("grl_colors",s),e.updateFloat2("grl_textureSize",(s==null?void 0:s.getSize().width)??1,(s==null?void 0:s.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===pl.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return fc.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 == ${la.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${la.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${la.COLOR_MODE_MULTIPLY}.) { + 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 == ${la.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${la.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${la.COLOR_MODE_MULTIPLY}.) { + 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 r,n,o;const s=((r=this._colors)==null?void 0:r.length)??0;if(this._colors=e,e===null||e.length===0){(n=this.colorsTexture)==null||n.dispose();return}if(!(t&&!i))if(this.colorsTexture&&s===e.length&&!i){const l=di.Color3toRGBAUint8(e);this.colorsTexture.update(l)}else(o=this.colorsTexture)==null||o.dispose(),this.colorsTexture=di.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 r;super.parse(e,t,i);const s=e.greasedLineMaterialOptions;(r=this.colorsTexture)==null||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=di.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):di.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var i;const t=e;(i=t.colorsTexture)==null||i.dispose(),this._colors&&(t.colorsTexture=di.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()}}fc.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial";H(`BABYLON.${fc.GREASED_LINE_MATERIAL_NAME}`,fc);const O6="greasedLinePixelShader",D6=`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;}}} +`;j.ShadersStore[O6]=D6;const N6="greasedLineVertexShader",w6=`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 +} +`;j.ShadersStore[N6]=w6;class F6 extends vn{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${pl.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${pl.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${la.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${la.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${la.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=re.White(),this._colorsDistributionType=pl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:Ur.DEFAULT_COLOR};const n=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?Ur.DEFAULT_WIDTH_ATTENUATED:Ur.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??re.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??pl.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??gs.NEAREST_NEAREST,this.colorMode=i.colorMode??la.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new ce(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=di.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add(()=>{di.DisposeEmptyColorsTexture()})}dispose(){var e;(e=this._colorsTexture)==null||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new ce(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 r,n,o;const s=((r=this._colors)==null?void 0:r.length)??0;if(this._colors=e,e===null||e.length===0){(n=this._colorsTexture)==null||n.dispose();return}if(!(t&&!i))if(this._colorsTexture&&s===e.length&&!i){const l=di.Color3toRGBAUint8(e);this._colorsTexture.update(l)}else(o=this._colorsTexture)==null||o.dispose(),this.colorsTexture=di.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",di.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",di.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",di.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Ur.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 r;const s=e.greasedLineMaterialOptions;(r=this._colorsTexture)==null||r.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=di.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=di.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const L6=`#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`,B6=`#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`,U6=`#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`,V6=`#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`,k6=`#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`,fM=[new re(.98,.26,.38),new re(.47,.75,.3),new re(0,.26,.77),new re(.97,.6,.76),new re(.19,.63,.78),new re(.98,.8,.6),new re(.65,.43,.15),new re(.15,.47,.22),new re(.67,.71,.86),new re(.09,.46,.56),new re(.8,.98,.02),new re(.39,.29,.13),new re(.53,.63,.06),new re(.95,.96,.41),new re(1,.72,.94),new re(.63,.08,.31),new re(.66,.96,.95),new re(.22,.14,.19),new re(.14,.65,.59),new re(.93,1,.68),new re(.93,.14,.44),new re(.47,.86,.67),new re(.85,.07,.78),new re(.53,.64,.98),new re(.43,.37,.56),new re(.71,.65,.25),new re(.66,.19,.01),new re(.94,.53,.12),new re(.41,.44,.44),new re(.24,.71,.96),new re(.57,.28,.56),new re(.44,.98,.42)];var fu;(function(a){a[a.NONE=0]="NONE",a[a.TRIANGLES=1]="TRIANGLES",a[a.VERTICES=2]="VERTICES",a[a.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",a[a.UV0=4]="UV0",a[a.UV1=5]="UV1",a[a.VERTEXCOLORS=6]="VERTEXCOLORS",a[a.MATERIALIDS=7]="MATERIALIDS"})(fu||(fu={}));class G6 extends Gr{constructor(){super(...arguments),this.DBG_MODE=fu.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class sr extends hn{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new G6;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new re(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new re(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new re(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new re(.8,.8,.8),this.vertexColor=t.vertexColor??new re(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new re(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new re(.5,.5,.5),this._materialColor=sr.MaterialColors[sr._PluginCount++%sr.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){U.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){(this._mode==fu.VERTICES||this._mode==fu.TRIANGLES||this._mode==fu.TRIANGLES_VERTICES)&&!i.isVerticesDataPresent("dbg_initialPass")&&U.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(){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:U6}}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){return e==="vertex"?{CUSTOM_VERTEX_DEFINITIONS:L6,CUSTOM_VERTEX_MAIN_END:B6}:{CUSTOM_FRAGMENT_DEFINITIONS:V6,CUSTOM_FRAGMENT_MAIN_END:k6}}static Reset(){this._PluginCount=0,this.MaterialColors=fM}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(e.getTotalIndices()==0)return i;if(t){const c=e.getVerticesDataKinds(),u=e.getIndices(),d={};for(const f of c)d[f]=e.getVerticesData(f);i=function(){e.setIndices(u);for(const f of c){const m=e.getVertexBuffer(f).getStrideSize();e.setVerticesData(f,d[f],void 0,m)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let c=0;c +#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);} +`;j.ShadersStore[z6]=W6;const H6="gaussianSplattingVertexDeclaration",X6=`uniform mat4 world;uniform mat4 view;uniform mat4 projection; +`;j.IncludesShadersStore[H6]=X6;const Y6="gaussianSplattingUboDeclaration",$6=`#include +#include +`;j.IncludesShadersStore[Y6]=$6;const K6="gaussianSplattingVertexShader",j6=`#include<__decl__gaussianSplattingVertex> +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#include +#include +attribute vec2 position;attribute float splatIndex;uniform vec2 viewport;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*1./viewport ++ position.y*minorAxis*1./viewport)*pos2d.w,pos2d.zw); +#include +#include +#include +} +`;j.ShadersStore[K6]=j6;class q6 extends Gr{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 Hp extends cf{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===!0)return!0;t.materialDefines||(t.materialDefines=new q6);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(Wg(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,n),Hg(r,o,this,n,!0,null,!0),Xg(e,n,!1,!1),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const l=[P.PositionKind,"splatIndex"];zg(l,n);const h=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","viewport","dataTextureSize","focal"],c=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],u=["Scene","Mesh"];$g({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:n}),Va(h);const d=n.toString(),f=r.getEngine().createEffect("gaussianSplatting",{attributes:l,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:d,onCompiled:this.onCompiled,onError:this.onError},o);t.setEffect(f,n,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!0,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;if(this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._mustRebind(s,n,i,t.visibility)){this.bindView(n),this.bindViewProjection(n);const l=s.getEngine(),h=this.getScene().activeCamera,c=l.getRenderWidth(),u=l.getRenderHeight();this._activeEffect.setFloat2("viewport",c,u);let d=1e3;h&&(h.fovMode==Ve.FOVMODE_VERTICAL_FIXED?d=u/2/Math.tan(h.fov/2):d=c/2/Math.tan(h.fov/2)),this._activeEffect.setFloat2("focal",d,d);const f=t;if(f.covariancesATexture){const m=f.covariancesATexture.getSize();n.setFloat2("dataTextureSize",m.width,m.height),n.setTexture("covariancesATexture",f.covariancesATexture),n.setTexture("covariancesBTexture",f.covariancesBTexture),n.setTexture("centersTexture",f.centersTexture),n.setTexture("colorsTexture",f.colorsTexture)}pa(n,this,s)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);mc(s,t,n),this.useLogarithmicDepth&&Ch(r,n,s),this._afterBind(t,this._activeEffect,i)}clone(e){return Pe.Clone(()=>new Hp(e,this.getScene()),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return Pe.Parse(()=>new Hp(e.name,t),e,t,i)}}H("BABYLON.GaussianSplattingMaterial",Hp);Object.defineProperty(Ie.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new g_(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(ei.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new g_(this)}return this._decalMap},enumerable:!0,configurable:!0});Object.defineProperty(Ft.prototype,"decalMap",{get:function(){return this._decalMap},set:function(a){this._decalMap=a},enumerable:!0,configurable:!0});class Q6{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,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,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function Z6(a,e){return`{X: ${a.x.toFixed(e)} Y: ${a.y.toFixed(e)}}`}function J6(a,e){return`{X: ${a._x.toFixed(e)} Y: ${a._y.toFixed(e)} Z: ${a._z.toFixed(e)}}`}function e8(a,e){return`{X: ${a.x.toFixed(e)} Y: ${a.y.toFixed(e)} Z: ${a.z.toFixed(e)} W: ${a.w.toFixed(e)}}`}function rS(a,e,t,i,s){let r=null,n=null,o=null;try{r=new a.Decoder,n=new a.DecoderBuffer,n.Init(e,e.byteLength);let l;const h=r.GetEncodedGeometryType(n);switch(h){case a.TRIANGULAR_MESH:{const d=new a.Mesh;if(l=r.DecodeBufferToMesh(n,d),!l.ok()||d.ptr===0)throw new Error(l.error_msg());const m=d.num_faces()*3,_=m*4,x=a._malloc(_);try{r.GetTrianglesUInt32Array(d,_,x);const E=new Uint32Array(m);E.set(new Uint32Array(a.HEAPF32.buffer,x,m)),i(E)}finally{a._free(x)}o=d;break}case a.POINT_CLOUD:{const d=new a.PointCloud;if(l=r.DecodeBufferToPointCloud(n,d),!l.ok()||!d.ptr)throw new Error(l.error_msg());o=d;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=o.num_points(),u=(d,f,m,_)=>{const x=_.data_type(),E=_.num_components(),S=_.normalized(),C=_.byte_stride(),y=_.byte_offset(),I={[a.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:a.HEAPF32},[a.DT_INT8]:{typedArrayConstructor:Int8Array,heap:a.HEAP8},[a.DT_INT16]:{typedArrayConstructor:Int16Array,heap:a.HEAP16},[a.DT_INT32]:{typedArrayConstructor:Int32Array,heap:a.HEAP32},[a.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:a.HEAPU8},[a.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:a.HEAPU16},[a.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:a.HEAPU32}}[x];if(!I)throw new Error(`Invalid data type ${x}`);const R=c*E,N=R*I.typedArrayConstructor.BYTES_PER_ELEMENT,k=a._malloc(N);try{d.GetAttributeDataArrayForAllPoints(f,_,x,N,k);const B=new I.typedArrayConstructor(I.heap.buffer,k,R);s(m,B.slice(),E,y,C,S)}finally{a._free(k)}};if(t)for(const d in t){const f=t[d],m=r.GetAttributeByUniqueId(o,f);u(r,o,d,m)}else{const d={position:a.POSITION,normal:a.NORMAL,color:a.COLOR,uv:a.TEX_COORD};for(const f in d){const m=r.GetAttributeId(o,d[f]);if(m!==-1){const _=r.GetAttribute(o,m);u(r,o,f,_)}}}return c}finally{o&&a.destroy(o),n&&a.destroy(n),r&&a.destroy(r)}}function t8(){let a;onmessage=e=>{const t=e.data;switch(t.id){case"init":{const i=t.decoder;i.url&&importScripts(i.url);const s=i.wasmBinary?{wasmBinary:i.wasmBinary}:{};a=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":{if(!a)throw new Error("Draco decoder module is not available");a.then(i=>{const s=rS(i,t.dataView,t.attributes,r=>{postMessage({id:"indices",data:r},[r.buffer])},(r,n,o,l,h,c)=>{postMessage({id:"attribute",kind:r,data:n,size:o,byteOffset:l,byteStride:h,normalized:c},[n.buffer])});postMessage({id:"decodeMeshDone",totalVertices:s})});break}}}}function i8(a,e,t){return new Promise((i,s)=>{const r=o=>{a.removeEventListener("error",r),a.removeEventListener("message",n),s(o)},n=o=>{o.data.id==="initDone"&&(a.removeEventListener("error",r),a.removeEventListener("message",n),i(a))};if(a.addEventListener("error",r),a.addEventListener("message",n),!e)a.postMessage({id:"init",decoder:{url:t}});else{const o=e.slice(0);a.postMessage({id:"init",decoder:{url:t,wasmBinary:o}},[o])}})}function s8(a,e){return new Promise(t=>{(e||DracoDecoderModule)({wasmBinary:a}).then(i=>{t({module:i})})})}class zn{static get DecoderAvailable(){const e=zn.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 zn._Default||(zn._Default=new zn),zn._Default}constructor(e=zn.DefaultNumWorkers){const t=zn.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,s=typeof e=="number"?e:e.numWorkers,r=s&&typeof Worker=="function"&&typeof URL=="function",n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&typeof WebAssembly=="object"?{url:n?Z.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Z.LoadFileAsync(Z.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Z.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then(l=>{const h=`${rS}(${t8})()`,c=URL.createObjectURL(new Blob([h],{type:"application/javascript"}));return new p_(s,()=>{const u=new Worker(c);return i8(u,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 Z.LoadBabylonScriptAsync(o.url)}return await s8(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 s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),r=(n,o)=>i&&i[n]!==void 0?(o!==i[n]&&U.Warn(`Normalized flag from Draco data (${o}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):o;if(this._workerPoolPromise)return this._workerPoolPromise.then(n=>new Promise((o,l)=>{n.push((h,c)=>{let u=null;const d=[],f=x=>{h.removeEventListener("error",f),h.removeEventListener("message",m),l(x),c()},m=x=>{const E=x.data;switch(E.id){case"decodeMeshDone":{h.removeEventListener("error",f),h.removeEventListener("message",m),o({indices:u,attributes:d,totalVertices:E.totalVertices}),c();break}case"indices":{u=E.data;break}case"attribute":{d.push({kind:E.kind,data:E.data,size:E.size,byteOffset:E.byteOffset,byteStride:E.byteStride,normalized:r(E.kind,E.normalized)});break}}};h.addEventListener("error",f),h.addEventListener("message",m);const _=s.slice();h.postMessage({id:"decodeMesh",dataView:_,attributes:t},[_.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(n=>{let o=null;const l=[],h=rS(n.module,s,t,c=>{o=c},(c,u,d,f,m,_)=>{l.push({kind:c,data:u,size:d,byteOffset:f,byteStride:m,normalized:_})});return{indices:o,attributes:l,totalVertices:h}});throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this.decodeMeshToMeshDataAsync(i,s),n=new Is(e,t);r.indices&&n.setIndices(r.indices);for(const o of r.attributes)n.setVerticesBuffer(new P(t.getEngine(),o.data,o.kind,!1,void 0,o.byteStride,void 0,o.byteOffset,o.size,void 0,o.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this.decodeMeshToMeshDataAsync(i,s,r),o=new Is(e,t);n.indices&&o.setIndices(n.indices);for(const l of n.attributes)o.setVerticesBuffer(new P(t.getEngine(),l.data,l.kind,!1,void 0,l.byteStride,void 0,l.byteOffset,l.size,void 0,l.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new Se;i.indices&&(s.indices=i.indices);for(const r of i.attributes){const n=P.GetFloatData(r.data,r.size,P.GetDataType(r.data),r.byteOffset,r.byteStride,r.normalized,i.totalVertices);s.set(n,r.kind)}return s}}zn.Configuration={decoder:{wasmUrl:`${Z._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Z._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Z._DefaultCdnUrl}/draco_decoder_gltf.js`}};zn.DefaultNumWorkers=zn.GetDefaultNumWorkers();zn._Default=null;class cl{static get Default(){return cl._Default||(cl._Default=new cl),cl._Default}constructor(){const e=cl.Configuration.decoder;this._decoderModulePromise=Z.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then(async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,r);return MeshoptDecoder.useWorkers(0),n})}}cl.Configuration={decoder:{url:`${Z._DefaultCdnUrl}/meshopt_decoder.js`}};cl._Default=null;let km=0;class Xp{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){var e,t;return new Xp(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 Xp(T.Lerp(this.pos,e.pos,t),T.Lerp(this.normal,e.normal,t),this.uv&&e.uv?ce.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Oe.Lerp(this.vertColor,e.vertColor,t):void 0)}}class tc{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(s.lengthSquared()===0||r.lengthSquared()===0)return null;const n=T.Normalize(T.Cross(s,r));return new tc(n,T.Dot(n,e))}clone(){return new tc(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let c=0;const u=[];let d,f;for(d=0;dtc.EPSILON?1:0;c|=m,u.push(m)}switch(c){case 0:(T.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const m=[],_=[];for(d=0;d=3&&(x=new Ou(m,e.shared),x.plane&&s.push(x)),_.length>=3&&(x=new Ou(_,e.shared),x.plane&&r.push(x));break}}}}tc.EPSILON=1e-5;class Ou{constructor(e,t){this.vertices=e,this.shared=t,this.plane=tc.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map(t=>t.clone());return new Ou(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let Oa=class tg{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new tg;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 Oa(this.clone()._polygons),i=new Oa(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Io._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new Oa(this._polygons),i=new Oa(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 Oa(this.clone()._polygons),i=new Oa(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(),Io._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new Oa(this._polygons),i=new Oa(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 Oa(this.clone()._polygons),i=new Oa(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Io._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new Oa(this._polygons),i=new Oa(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 s=this._polygons,r=[],n=[],o=[];let l=null,h=null;const c=T.Zero(),u=T.Zero(),d=ce.Zero(),f=new Oe(0,0,0,0),m=[0,0,0],_={};let x;for(let S=0,C=s.length;Sc.shared.meshId===u.shared.meshId?c.shared.subMeshId-u.shared.subMeshId:c.shared.meshId-u.shared.meshId),this.toVertexData(c=>{o[c.shared.meshId]||(o[c.shared.meshId]={}),o[c.shared.meshId][c.shared.subMeshId]||(o[c.shared.meshId][c.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:c.shared.materialIndex}),l=o[c.shared.meshId][c.shared.subMeshId]},()=>{l.indexStart=Math.min(n,l.indexStart),l.indexEnd=Math.max(n,l.indexEnd),n++}).applyToMesh(s),i){let c=0,u;s.subMeshes=[];for(const d in o){u=-1;for(const f in o[d])l=o[d][f],xr.CreateFromIndices(l.materialIndex+c,l.indexStart,l.indexEnd-l.indexStart+1,s),u=Math.max(l.materialIndex,u);c+=++u}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}const r8="meshUVSpaceRendererVertexShader",n8=`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);}`;j.ShadersStore[r8]=n8;const a8="meshUVSpaceRendererPixelShader",o8=`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);} +`;j.ShadersStore[a8]=o8;const l8="meshUVSpaceRendererMaskerVertexShader",h8="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;}";j.ShadersStore[l8]=h8;const c8="meshUVSpaceRendererMaskerPixelShader",u8=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} +`;j.ShadersStore[c8]=u8;const d8="meshUVSpaceRendererFinaliserPixelShader",f8=`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;}}} +`;j.ShadersStore[d8]=f8;const p8="meshUVSpaceRendererFinaliserVertexShader",_8=`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;} +`;j.ShadersStore[p8]=_8;q._TrailMeshParser=(a,e)=>Pg.Parse(a,e);class Pg extends q{constructor(e,t,i,s=1,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=s,this._length=r,this._sectionVectors=[],this._sectionNormalVectors=[];for(let o=0;o<=this._sectionPolygonPointsCount;o++)this._sectionVectors[o]=T.Zero(),this._sectionNormalVectors[o]=T.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new Se,t=[],i=[],s=[],r=[];let n=T.Zero();this._generator instanceof Ft&&this._generator.hasBoundingInfo?n=this._generator.getBoundingInfo().boundingBox.centerWorld:n=this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let l=0;l<=this._sectionPolygonPointsCount;l++){const h=l!==this._sectionPolygonPointsCount?l*o:0;t.push(n.x+Math.cos(h)*this.diameter,n.y+Math.sin(h)*this.diameter,n.z),r.push(l/this._sectionPolygonPointsCount,0)}for(let l=1;l<=this._length;l++){for(let c=0;c<=this._sectionPolygonPointsCount;c++){const u=c!==this._sectionPolygonPointsCount?c*o:0;t.push(n.x+Math.cos(u)*this.diameter,n.y+Math.sin(u)*this.diameter,n.z),r.push(c/this._sectionPolygonPointsCount,l/this._length)}const h=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let c=0;c<=this._sectionPolygonPointsCount;c++)s.push(h+c,h+c+this._sectionPolygonPointsCount,h+c+this._sectionPolygonPointsCount+1),s.push(h+c,h+c+this._sectionPolygonPointsCount+1,h+c+1)}Se.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}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(P.PositionKind),t=this.getVerticesData(P.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let n=3*(this._sectionPolygonPointsCount+1);n{this._getSimplifier(e).simplify(t,s=>{t.distance!==void 0&&e.mesh.addLODLevel(t.distance,s),s.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{const t=this._getSimplifier(e),i=(s,r)=>{t.simplify(s,n=>{s.distance!==void 0&&e.mesh.addLODLevel(s.distance,n),n.isVisible=!0,r()})};Fa.Run(e.settings.length,s=>{i(e.settings[s.index],()=>{s.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){switch(e.simplificationType){case Mg.QUADRATIC:default:return new E8(e.mesh)}}}var Mg;(function(a){a[a.QUADRATIC=0]="QUADRATIC"})(Mg||(Mg={}));class g8{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class x8{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new pu,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class pu{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,s,r,n,o,l,h){return this.data[e]*this.data[r]*this.data[h]+this.data[i]*this.data[s]*this.data[l]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[l]-this.data[t]*this.data[s]*this.data[h]}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 pu;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new pu(pu.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class T8{constructor(e,t){this.vertexId=e,this.triangleId=t}}class E8{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=At}simplify(e,t){this._initDecimatedMesh(),Fa.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 s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(l,h)=>{setTimeout(()=>{l%5===0&&this._updateMesh(l===0);for(let d=0;d{const f=~~((this._triangles.length/2+d)%this._triangles.length),m=this._triangles[f];if(m&&!(m.error[3]>c||m.deleted||m.isDirty)){for(let _=0;_<3;++_)if(m.error[_]{I.indexOf(k)===-1&&(k.deletePending=!0,I.push(k))}),I.length%2!==0)continue;S.q=C.q.add(S.q),S.updatePosition(y);const R=this._references.length;r=this._updateTriangles(S,S,x,r),r=this._updateTriangles(S,C,E,r);const N=this._references.length-R;if(N<=S.triangleCount){if(N)for(let k=0;kn-r<=s)},0)};Fa.Run(this.decimationIterations,l=>{n-r<=s?l.breakLoop():o(l.index,()=>{l.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(P.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=u=>{if(i){for(let d=0;d{if(!s)return;const d=u+n.verticesStart,f=T.FromArray(s,d*3),m=o(f)||new x8(f,this._vertices.length);m.originalOffsets.push(d),m.id===this._vertices.length&&this._vertices.push(m),l.push(m.id)},c=n.verticesCount;Fa.SyncAsyncForLoop(c,this.syncIterations/4>>0,h,()=>{const u=d=>{if(!r)return;const m=(n.indexStart/3+d)*3,_=r[m+0],x=r[m+1],E=r[m+2],S=this._vertices[l[_-n.verticesStart]],C=this._vertices[l[x-n.verticesStart]],y=this._vertices[l[E-n.verticesStart]],A=new g8([S,C,y]);A.originalOffset=m,this._triangles.push(A)};Fa.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,u,()=>{this._init(t)})})}_init(e){const t=i=>{const s=this._triangles[i];s.normal=T.Cross(s._vertices[1].position.subtract(s._vertices[0].position),s._vertices[2].position.subtract(s._vertices[0].position)).normalize();for(let r=0;r<3;r++)s._vertices[r].q.addArrayInPlace(pu.DataFromNumbers(s.normal.x,s.normal.y,s.normal.z,-T.Dot(s.normal,s._vertices[0].position)))};Fa.SyncAsyncForLoop(this._triangles.length,this.syncIterations,t,()=>{const i=s=>{const r=this._triangles[s];for(let n=0;n<3;++n)r.error[n]=this._calculateError(r._vertices[n],r._vertices[(n+1)%3]);r.error[3]=Math.min(r.error[0],r.error[1],r.error[2])};Fa.SyncAsyncForLoop(this._triangles.length,this.syncIterations,i,()=>{e()})})}_reconstructMesh(e){const t=[];let i;for(i=0;i{n.push(y.position.x),n.push(y.position.y),n.push(y.position.z),c&&c.length&&(o.push(c[A*3]),o.push(c[A*3+1]),o.push(c[A*3+2])),u&&u.length&&(l.push(u[A*2]),l.push(u[A*2+1])),d&&d.length&&(h.push(d[A*4]),h.push(d[A*4+1]),h.push(d[A*4+2]),h.push(d[A*4+3])),++f})}const m=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),x=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const E=this._reconstructedMesh.getIndices(),S=this._mesh.getIndices();for(i=0;i{const A=S[s.originalOffset+y];let I=s._vertices[y].originalOffsets.indexOf(A);I<0&&(I=0),E.push(s._vertices[y].id+I+_)});this._reconstructedMesh.setIndices(E),this._reconstructedMesh.setVerticesData(P.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(P.NormalKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(P.UVKind,l),h.length>0&&this._reconstructedMesh.setVerticesData(P.ColorKind,h);const C=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],x.forEach(y=>{xr.AddToMesh(y.materialIndex,y.verticesStart,y.verticesCount,y.indexStart,y.indexCount,y.getMesh())}),xr.AddToMesh(C.materialIndex,_,f,m,t.length*3,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new q(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,s,r){for(let n=0;n.999)return!0;const f=T.Cross(u,d).normalize();if(s[n]=!1,T.Dot(f,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let n=0;n_r.Parse(a,e);class _r extends pM{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(di.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+=E.length*2,s+=(E.length-3)*2,r+=E.length*4/3,n+=E.length*8/3});const o=new Float32Array(i),l=i>65535?new Uint32Array(s):new Uint16Array(s),h=new Float32Array(r),c=new Float32Array(n),u=new Float32Array(n);let d=0,f=0,m=0,_=0,x=0;e.forEach(E=>{const S=di.GetLineLengthArray(E),C=S[S.length-1];for(let B=0,Q=0;Q>1]/C;if(this._options.uvs)for(let B=0;Bvs.Parse(a,e);class vs extends pM{constructor(e,t,i,s){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=s??[],i.points&&this.addPoints(di.ConvertPoints(i.points),i,!!s)}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 m=vs._ConvertToRibbonPath(d,h.ribbonOptions,this._scene.useRightHandedSystem,s&&s[f]);i=this._preprocess(m,i,h)})}}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 c,u;const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let d=0;d2)for(let d=0;d0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(f%2!==0?i:0),o[0],o[2]),l&&r.push(o[0],o[1]+(f%2!==0?i:0),o[2])}else for(let d=0;dm.y&&m.x>m.z?i?vs._RightHandedForwardReadOnlyQuaternion:vs._LeftHandedForwardReadOnlyQuaternion:vs._LeftReadOnlyQuaternion),h=m.normalize()}c=h.multiplyByFloats(o,o,o),r.push(d.add(c)),n.push(d.subtract(c))}s||(r.push(l[l.length-1].add(c)),n.push(l[l.length-1].subtract(c)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x===t.x&&(!i||(i==null?void 0:i.x)===1)?vs.DIRECTION_YZ:e.y===t.y?vs.DIRECTION_XZ:e.z===t.z?vs.DIRECTION_XY:vs.DIRECTION_XZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Tr.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Tr.DeepCopy(i,s,["instance"],void 0,!0);const n=new vs(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}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,s=e.name,r=e.pathOptions;return new vs(s,t,i,r)}_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 n=0;n=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return e.copyToArray(i,a*16),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[a]=e),t&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0};q.prototype.thinInstanceSetAttributeAt=function(a,e,t,i=!0){return a===P.ColorKind&&(a=P.ColorInstanceKind),!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[a]||e>=this._thinInstanceDataStorage.instancesCount?!1:(this._thinInstanceUpdateBufferSize(a,0),this._userThinInstanceBuffersStorage.data[a].set(t,e*this._userThinInstanceBuffersStorage.strides[a]),i&&this.thinInstanceBufferUpdated(a),!0)};Object.defineProperty(q.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(a){var i;const e=this._thinInstanceDataStorage.matrixData??((i=this.source)==null?void 0:i._thinInstanceDataStorage.matrixData),t=e?e.length/16:0;a<=t&&(this._thinInstanceDataStorage.instancesCount=a)},enumerable:!0,configurable:!0});q.prototype._thinInstanceCreateMatrixBuffer=function(a,e,t=!0){const i=new Gs(this.getEngine(),e,!t,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(i.createVertexBuffer(a+s,s*4,4));return i};q.prototype.thinInstanceSetBuffer=function(a,e,t=0,i=!0){var s,r,n;t=t||16,a==="matrix"?((s=this._thinInstanceDataStorage.matrixBuffer)==null||s.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())):a==="previousMatrix"?((r=this._thinInstanceDataStorage.previousMatrixBuffer)==null||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=e,e!==null&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",e,i))):(a===P.ColorKind&&(a=P.ColorInstanceKind),e===null?(n=this._userThinInstanceBuffersStorage)!=null&&n.data[a]&&(this.removeVerticesData(a),delete this._userThinInstanceBuffersStorage.data[a],delete this._userThinInstanceBuffersStorage.strides[a],delete this._userThinInstanceBuffersStorage.sizes[a],delete this._userThinInstanceBuffersStorage.vertexBuffers[a]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[a]=e,this._userThinInstanceBuffersStorage.strides[a]=t,this._userThinInstanceBuffersStorage.sizes[a]=e.length,this._userThinInstanceBuffersStorage.vertexBuffers[a]=new P(this.getEngine(),e,a,!i,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[a])))};q.prototype.thinInstanceBufferUpdated=function(a){var e,t,i;a==="matrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(e=this._thinInstanceDataStorage.matrixBuffer)==null||e.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):a==="previousMatrix"?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(a),(t=this._thinInstanceDataStorage.previousMatrixBuffer)==null||t.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(a===P.ColorKind&&(a=P.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[a].isUpdatable()&&this._thinInstanceRecreateBuffer(a),this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(this._userThinInstanceBuffersStorage.data[a],0)))};q.prototype.thinInstancePartialBufferUpdate=function(a,e,t){var i;a==="matrix"?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(e,t):(a===P.ColorKind&&(a=P.ColorInstanceKind),(i=this._userThinInstanceBuffersStorage)!=null&&i.vertexBuffers[a]&&this._userThinInstanceBuffersStorage.vertexBuffers[a].updateDirectly(e,t))};q.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const a=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=w.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,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)===Ql.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==w.AutoDetect)return e.acceptedConnectionPointTypes&&e.acceptedConnectionPointTypes.indexOf(this.type)!==-1?Ql.Compatible:Ql.TypeIncompatible;if(e.excludedConnectionPointTypes&&e.excludedConnectionPointTypes.indexOf(this.type)!==-1)return Ql.TypeIncompatible;let s=i,r=t;return this.direction===Yp.Input&&(s=t,r=i),s.isAnAncestorOf(r)?Ql.HierarchyIssue:Ql.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return t===-1?this:(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this),this)}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class _t{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 s=i.ownerBlock.getDescendantOfPredicate(e);if(s)return s}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 K,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=a_.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new iR(e,this,Yp.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return i=i??new iR(e,this,Yp.Output),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 s=i.connectedPoint.ownerBlock;s&&s!==this&&s.build(e)}this._customBuildStep(e),e.verbose&&U.Log(`Building ${this.name} [${this.getClassName()}]`);const t=ks.Now;this._buildBlock(e),this._buildExecutionTime=ks.Now-t;for(const i of this._outputs)for(const s of i.endpoints){const r=s.ownerBlock;r&&r.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(s=>{const r=this.inputs.find(n=>n.name===s.name);if(r&&(s.displayName&&(r.displayName=s.displayName),s.isExposedOnFrame&&(r.isExposedOnFrame=s.isExposedOnFrame,r.exposedPortPosition=s.exposedPortPosition),s.value!==void 0&&s.value!==null))if(s.valueType==="number")r.value=s.value;else{const n=rs(s.valueType);n&&(r.value=n.FromArray(s.value))}}),i&&i.forEach((s,r)=>{s.displayName&&(this.outputs[r].displayName=s.displayName),s.isExposedOnFrame&&(this.outputs[r].isExposedOnFrame=s.isExposedOnFrame,this.outputs[r].exposedPortPosition=s.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 s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.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 n=0;do n++,this._codeVariableName=i+n;while(e.indexOf(this._codeVariableName)!==-1)}e.push(this._codeVariableName);let s=` +// ${this.getClassName()} +`;this.comments&&(s+=`// ${this.comments} +`);const r=this.getClassName();if(r==="GeometryInputBlock"){const o=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${o}); +`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}"); +`;s+=this._dumpPropertiesCode();for(const n of this.inputs){if(!n.isConnected)continue;const l=n.connectedPoint.ownerBlock;t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}for(const n of this.outputs)if(n.hasEndpoints)for(const o of n.endpoints){const l=o.ownerBlock;l&&t.indexOf(l)===-1&&(s+=l._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=rs(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([O("comment")],_t.prototype,"comments",void 0);class _M extends _t{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",w.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}H("BABYLON.GeometryOutputBlock",_M);var Jt;(function(a){a[a.None=0]="None",a[a.Positions=1]="Positions",a[a.Normals=2]="Normals",a[a.Tangents=3]="Tangents",a[a.UV=4]="UV",a[a.UV2=5]="UV2",a[a.UV3=6]="UV3",a[a.UV4=7]="UV4",a[a.UV5=8]="UV5",a[a.UV6=9]="UV6",a[a.Colors=10]="Colors",a[a.VertexID=11]="VertexID",a[a.FaceID=12]="FaceID",a[a.GeometryID=13]="GeometryID",a[a.CollectionID=14]="CollectionID",a[a.LoopID=15]="LoopID",a[a.InstanceID=16]="InstanceID"})(Jt||(Jt={}));class v8{constructor(){this._rotationMatrix=new L,this._scalingMatrix=new L,this._positionMatrix=new L,this._scalingRotationMatrix=new L,this._transformMatrix=new L,this._tempVector3=new T,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 Jt.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():!this.geometryContext||!this.geometryContext.positions?T.Zero():T.FromArray(this.geometryContext.positions,i*3);case Jt.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():!this.geometryContext||!this.geometryContext.normals?T.Zero():T.FromArray(this.geometryContext.normals,i*3);case Jt.Colors:return!this.geometryContext||!this.geometryContext.colors?tt.Zero():tt.FromArray(this.geometryContext.colors,i*4);case Jt.Tangents:return!this.geometryContext||!this.geometryContext.tangents?tt.Zero():tt.FromArray(this.geometryContext.tangents,i*4);case Jt.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():!this.geometryContext||!this.geometryContext.uvs?ce.Zero():ce.FromArray(this.geometryContext.uvs,i*2);case Jt.UV2:return!this.geometryContext||!this.geometryContext.uvs2?ce.Zero():ce.FromArray(this.geometryContext.uvs2,i*2);case Jt.UV3:return!this.geometryContext||!this.geometryContext.uvs3?ce.Zero():ce.FromArray(this.geometryContext.uvs3,i*2);case Jt.UV4:return!this.geometryContext||!this.geometryContext.uvs4?ce.Zero():ce.FromArray(this.geometryContext.uvs4,i*2);case Jt.UV5:return!this.geometryContext||!this.geometryContext.uvs5?ce.Zero():ce.FromArray(this.geometryContext.uvs5,i*2);case Jt.UV6:return!this.geometryContext||!this.geometryContext.uvs6?ce.Zero():ce.FromArray(this.geometryContext.uvs6,i*2);case Jt.VertexID:return i;case Jt.FaceID:return this.executionContext.getExecutionFaceIndex();case Jt.LoopID:return this.executionContext.getExecutionLoopIndex();case Jt.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Jt.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Jt.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 w.Vector2:return new ce(i,i);case w.Vector3:return new T(i,i,i);case w.Vector4:return new tt(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(((r=e._connectedPoint)==null?void 0:r.type)===t)return s;switch(t){case w.Vector2:return new ce(s,s);case w.Vector3:return new T(s,s,s);case w.Vector4:return new tt(s,s,s,s)}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 ${Jt[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,s,r){L.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),L.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),L.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 n=0;nt.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.${Jt[this._contextualSource]}; +`;const t=[];let i="";switch(this.type){case w.Float:case w.Int:i=`${this.value}`;break;case w.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case w.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case w.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===w.Float||this.type===w.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=rs(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}H("BABYLON.GeometryInputBlock",bs);class mC extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",w.Float,!0,1),this.registerInput("width",w.Float,!0,0),this.registerInput("height",w.Float,!0,0),this.registerInput("depth",w.Float,!0,0),this.registerInput("subdivisions",w.Int,!0,1),this.registerInput("subdivisionsX",w.Int,!0,0),this.registerInput("subdivisionsY",w.Int,!0,0),this.registerInput("subdivisionsZ",w.Int,!0,0),this.registerOutput("geometry",w.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 bs("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new bs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new bs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new bs("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=s=>{t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.depth=this.depth.getConnectedValue(s);const r=this.subdivisions.getConnectedValue(s),n=this.subdivisionsX.getConnectedValue(s),o=this.subdivisionsY.getConnectedValue(s),l=this.subdivisionsZ.getConnectedValue(s);return r&&(t.segments=r),n&&(t.widthSegments=n),o&&(t.heightSegments=o),l&&(t.depthSegments=l),_z(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mC.prototype,"evaluateContext",void 0);H("BABYLON.BoxBlock",mC);class Gn{_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=Gn._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new K,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e)if(!t)t=i;else return Z.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:Gn.EditorURL;Z.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 s=ks.Now;this._initializeBlock(this.outputBlock,i);const r=new v8;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=Gn._BuildIdGenerator++),this._buildExecutionTime=ks.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new q(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 s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._initializeBlock(r,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 s of e.blocks){const r=rs(s.customType);if(r){const n=new r;n._deserialize(s),i[s.id]=n,this.attachedBlocks.push(n)}}for(const s of this.attachedBlocks)if(s.isTeleportOut){const r=s,n=r._tempEntryPointUniqueId;if(n){const o=i[n];o&&o.attachToEndpoint(r)}}for(let s=0;so.targetConnectionName)&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const n of s)i[n.blockId]&&(n.blockId=i[n.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const n in i)r[n]=i[n].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n){for(const o of r.inputs)if(i[o.targetBlockId]===e&&o.targetConnectionName===s.name){const l=n.getInputByName(o.inputName);if(!l||l.isConnected)continue;s.connectTo(l,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(const r of t)r.isInput&&e.indexOf(r)===-1&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+=`// Connections +`,s+=this.outputBlock._dumpCodeForOutputConnections(e),s+=`// Output nodes +`,s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`,s+=`nodeGeometry.build(); +`),s}_gatherBlocks(e,t){if(t.indexOf(e)===-1){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const r=s.ownerBlock;r!==e&&this._gatherBlocks(r,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new mC("Box");e.autoConfigure();const t=new _M("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Pe.Clone(()=>new Gn(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Pe.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 s of i)t.blocks.push(s.serialize());if(!e)for(const s of this.attachedBlocks)i.indexOf(s)===-1&&t.blocks.push(s.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 Gn(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Pe.Parse(()=>new Gn(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return e==="_BLANK"?Promise.resolve(Gn.CreateDefault("blank")):new Promise((s,r)=>{const n=new hs;n.addEventListener("readystatechange",()=>{if(n.readyState==4)if(n.status==200){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),l=JSON.parse(o.nodeGeometry);t||(t=Pe.Parse(()=>new Gn(e),l,null)),t.parseSerializedObject(l),t.snippetId=e;try{i||t.build(),s(t)}catch(h){r(h)}}else r("Unable to load the snippet "+e)}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}Gn._BuildIdGenerator=0;Gn.EditorURL=`${Z._DefaultCdnUrl}/v${ee.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;Gn.SnippetUrl="https://snippet.babylonjs.com";v([O()],Gn.prototype,"name",void 0);v([O("comment")],Gn.prototype,"comment",void 0);class gC extends _t{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=At,this.registerInput("geometry",w.Geometry),this.registerOutput("output",w.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 s=this.geometry.getConnectedValue(i),r=[],n={};for(let l=0;ln[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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gC.prototype,"evaluateContext",void 0);v([it("Epsilon",Qe.Float,"ADVANCED",{notifiers:{rebuild:!0}})],gC.prototype,"epsilon",void 0);H("BABYLON.GeometryOptimizeBlock",gC);class mM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",w.Float,!0,1),this.registerInput("width",w.Float,!0,0),this.registerInput("height",w.Float,!0,0),this.registerOutput("geometry",w.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 bs("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){const e=new bs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new bs("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=s=>(t.size=this.size.getConnectedValue(s),t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),Cv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mM.prototype,"evaluateContext",void 0);H("BABYLON.PlaneBlock",mM);class gM extends _t{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",w.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=Se.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=Se.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=Se.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}v([it("Serialize cached data",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gM.prototype,"serializedCachedData",void 0);H("BABYLON.MeshBlock",gM);class xM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",w.Float,!0,1),this.registerInput("radiusX",w.Float,!0,0),this.registerInput("radiusY",w.Float,!0,0),this.registerInput("radiusZ",w.Float,!0,0),this.registerInput("subdivisions",w.Int,!0,4),this.registerOutput("geometry",w.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 bs("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.radiusX=this.radiusX.getConnectedValue(s),t.radiusY=this.radiusY.getConnectedValue(s),t.radiusZ=this.radiusZ.getConnectedValue(s),Av(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xM.prototype,"evaluateContext",void 0);H("BABYLON.IcoSphereBlock",xM);class TM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",w.Int,!0,32),this.registerInput("diameter",w.Float,!0,1),this.registerInput("diameterX",w.Float,!0,0),this.registerInput("diameterY",w.Float,!0,0),this.registerInput("diameterZ",w.Float,!0,0),this.registerInput("arc",w.Float,!0,1),this.registerInput("slice",w.Float,!0,1),this.registerOutput("geometry",w.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 bs("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.segments=this.segments.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterX=this.diameterX.getConnectedValue(s),t.diameterY=this.diameterY.getConnectedValue(s),t.diameterZ=this.diameterZ.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),t.slice=this.slice.getConnectedValue(s),Wv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TM.prototype,"evaluateContext",void 0);H("BABYLON.SphereBlock",TM);class EM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",w.Float,!0,1),this.registerInput("height",w.Float,!0,1),this.registerInput("subdivisions",w.Int,!0,1),this.registerInput("subdivisionsX",w.Int,!0,0),this.registerInput("subdivisionsY",w.Int,!0,0),this.registerOutput("geometry",w.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 bs("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new bs("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.width=this.width.getConnectedValue(s),t.height=this.height.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.subdivisionsX=this.subdivisionsX.getConnectedValue(s),t.subdivisionsY=this.subdivisionsY.getConnectedValue(s),ol(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],EM.prototype,"evaluateContext",void 0);H("BABYLON.GridBlock",EM);class SM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",w.Float,!0,1),this.registerInput("thickness",w.Float,!0,.5),this.registerInput("tessellation",w.Int,!0,16),this.registerOutput("geometry",w.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 bs("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=s=>(t.thickness=this.thickness.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),Bv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SM.prototype,"evaluateContext",void 0);H("BABYLON.TorusBlock",SM);class vM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",w.Float,!0,25),this.registerInput("diameter",w.Float,!0,1),this.registerInput("diameterTop",w.Float,!0,-1),this.registerInput("diameterBottom",w.Float,!0,-1),this.registerInput("subdivisions",w.Int,!0,1),this.registerInput("tessellation",w.Int,!0,24),this.registerInput("arc",w.Float,!0,1),this.registerOutput("geometry",w.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 bs("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new bs("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.diameter=this.diameter.getConnectedValue(s),t.diameterTop=this.diameterTop.getConnectedValue(s),t.diameterBottom=this.diameterBottom.getConnectedValue(s),t.diameterTop===-1&&(t.diameterTop=t.diameter),t.diameterBottom===-1&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),Vv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vM.prototype,"evaluateContext",void 0);H("BABYLON.CylinderBlock",vM);class CM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",w.Float,!0,1),this.registerInput("radius",w.Float,!0,.25),this.registerInput("tessellation",w.Int,!0,16),this.registerInput("subdivisions",w.Int,!0,2),this.registerOutput("geometry",w.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 bs("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new bs("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.height=this.height.getConnectedValue(s),t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.subdivisions=this.subdivisions.getConnectedValue(s),Hv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CM.prototype,"evaluateContext",void 0);H("BABYLON.CapsuleBlock",CM);class bM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",w.Float,!0,.5),this.registerInput("tessellation",w.Int,!0,64),this.registerInput("arc",w.Float,!0,1),this.registerOutput("geometry",w.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 bs("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=s=>(t.radius=this.radius.getConnectedValue(s),t.tessellation=this.tessellation.getConnectedValue(s),t.arc=this.arc.getConnectedValue(s),Xv(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const s=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bM.prototype,"evaluateContext",void 0);H("BABYLON.DiscBlock",bM);class C8 extends _t{constructor(e){super(e),this.registerOutput("geometry",w.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}H("BABYLON.NullBlock",C8);class yM extends _t{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",w.Geometry),this.registerInput("positions",w.Vector3),this.registerOutput("output",w.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 s=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 s=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 s=[],r=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{var r;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 s=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 s=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 s=t.type===w.Float||t.type===w.Int,r=i.type===w.Float||i.type===w.Int,n=s&&r;switch(this.operation){case rn.Add:{n?e=o=>t.getConnectedValue(o)+i.getConnectedValue(o):s?e=o=>o.adapt(t,i.type).add(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).add(o.adapt(i,t.type));break}case rn.Subtract:{n?e=o=>t.getConnectedValue(o)-i.getConnectedValue(o):s?e=o=>o.adapt(t,i.type).subtract(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).subtract(o.adapt(i,t.type));break}case rn.Multiply:{n?e=o=>t.getConnectedValue(o)*i.getConnectedValue(o):s?e=o=>o.adapt(t,i.type).multiply(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).multiply(o.adapt(i,t.type));break}case rn.Divide:{n?e=o=>t.getConnectedValue(o)/i.getConnectedValue(o):s?e=o=>o.adapt(t,i.type).divide(i.getConnectedValue(o)):e=o=>t.getConnectedValue(o).divide(o.adapt(i,t.type));break}case rn.Min:{if(n)e=o=>Math.min(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=s?[i,t]:[t,i];switch(o.type){case w.Vector2:{e=h=>ce.Minimize(o.getConnectedValue(h),h.adapt(l,o.type));break}case w.Vector3:{e=h=>T.Minimize(o.getConnectedValue(h),h.adapt(l,o.type));break}case w.Vector4:{e=h=>tt.Minimize(o.getConnectedValue(h),h.adapt(l,o.type));break}}}break}case rn.Max:if(n)e=o=>Math.max(t.getConnectedValue(o),i.getConnectedValue(o));else{const[o,l]=s?[i,t]:[t,i];switch(o.type){case w.Vector2:{e=h=>ce.Maximize(o.getConnectedValue(h),h.adapt(l,o.type));break}case w.Vector3:{e=h=>T.Maximize(o.getConnectedValue(h),h.adapt(l,o.type));break}case w.Vector4:{e=h=>tt.Maximize(o.getConnectedValue(h),h.adapt(l,o.type));break}}break}}this.output._storedFunction=o=>t.type===w.Int?e(o)|0:e(o)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${rn[this.operation]}; +`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===w.Int||this.left.type===w.Float&&this.right.type!==w.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=[w.Int,w.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),(t.type===w.Int||t.type===w.Float)&&e.acceptedConnectionPointTypes.push(w.Vector2,w.Vector3,w.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([it("Operation",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:rn.Add},{label:"Subtract",value:rn.Subtract},{label:"Multiply",value:rn.Multiply},{label:"Divide",value:rn.Divide},{label:"Max",value:rn.Max},{label:"Min",value:rn.Min}]})],PM.prototype,"operation",void 0);H("BABYLON.MathBlock",PM);class b8 extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("fromMin",w.Float,!0,0),this.registerInput("fromMax",w.Float,!0,1),this.registerInput("toMin",w.Float,!0,0),this.registerInput("toMax",w.Float,!0,1),this.registerOutput("output",w.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(w.Vector2),this._inputs[0].excludedConnectionPointTypes.push(w.Vector3),this._inputs[0].excludedConnectionPointTypes.push(w.Vector4),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e),o=(t-i)/(s-i)*(n-r)+r;return this.output.type===w.Int?Math.floor(o):o}}}H("BABYLON.MapRangeBlock",b8);var Zs;(function(a){a[a.Equal=0]="Equal",a[a.NotEqual=1]="NotEqual",a[a.LessThan=2]="LessThan",a[a.GreaterThan=3]="GreaterThan",a[a.LessOrEqual=4]="LessOrEqual",a[a.GreaterOrEqual=5]="GreaterOrEqual",a[a.Xor=6]="Xor",a[a.Or=7]="Or",a[a.And=8]="And"})(Zs||(Zs={}));class MM extends _t{constructor(e){super(e),this.test=Zs.Equal,this.registerInput("left",w.Float),this.registerInput("right",w.Float,!0,0),this.registerInput("ifTrue",w.AutoDetect,!0,1),this.registerInput("ifFalse",w.AutoDetect,!0,0),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=w.Float,this._inputs[0].acceptedConnectionPointTypes.push(w.Int),this._inputs[1].acceptedConnectionPointTypes.push(w.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),s=this.right.getConnectedValue(t);let r=!1;switch(this.test){case Zs.Equal:r=Ne.WithinEpsilon(i,s,At);break;case Zs.NotEqual:r=i!==s;break;case Zs.LessThan:r=is;break;case Zs.LessOrEqual:r=i<=s;break;case Zs.GreaterOrEqual:r=i>=s;break;case Zs.Xor:r=!!i&&!s||!i&&!!s;break;case Zs.Or:r=!!i||!!s;break;case Zs.And:r=!!i&&!!s;break}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Zs[this.test]}; +`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}v([it("Test",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Zs.Equal},{label:"NotEqual",value:Zs.NotEqual},{label:"LessThan",value:Zs.LessThan},{label:"GreaterThan",value:Zs.GreaterThan},{label:"LessOrEqual",value:Zs.LessOrEqual},{label:"GreaterOrEqual",value:Zs.GreaterOrEqual},{label:"Xor",value:Zs.Xor},{label:"Or",value:Zs.Or},{label:"And",value:Zs.And}]})],MM.prototype,"test",void 0);H("BABYLON.ConditionBlock",MM);var Ja;(function(a){a[a.None=0]="None",a[a.LoopID=1]="LoopID",a[a.InstanceID=2]="InstanceID"})(Ja||(Ja={}));class OM extends _t{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Ja.None,this.registerInput("min",w.AutoDetect),this.registerInput("max",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.Texture),this._inputs[1].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].excludedConnectionPointTypes.push(w.Geometry),this._inputs[1].excludedConnectionPointTypes.push(w.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 bs("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new bs("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case w.Int:case w.Float:{e=t=>{const i=this.min.getConnectedValue(t)||0,s=this.max.getConnectedValue(t)||0;return i+Math.random()*(s-i)};break}case w.Vector2:{e=t=>{const i=this.min.getConnectedValue(t)||ce.Zero(),s=this.max.getConnectedValue(t)||ce.Zero();return new ce(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y))};break}case w.Vector3:{e=t=>{const i=this.min.getConnectedValue(t)||T.Zero(),s=this.max.getConnectedValue(t)||T.Zero();return new T(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z))};break}case w.Vector4:{e=t=>{const i=this.min.getConnectedValue(t)||tt.Zero(),s=this.max.getConnectedValue(t)||tt.Zero();return new tt(i.x+Math.random()*(s.x-i.x),i.y+Math.random()*(s.y-i.y),i.z+Math.random()*(s.z-i.z),i.w+Math.random()*(s.w-i.w))};break}}this.lockMode===Ja.None||!e?this.output._storedFunction=e:this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Ja.InstanceID:i=t.getContextualValue(Jt.InstanceID,!0)||0;break;case Ja.LoopID:i=t.getContextualValue(Jt.LoopID,!0)||0;break}return(this._currentLockId!==i||this.lockMode===Ja.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Ja[this.lockMode]}; +`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}v([it("LockMode",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Ja.None},{label:"LoopID",value:Ja.LoopID},{label:"InstanceID",value:Ja.InstanceID}]})],OM.prototype,"lockMode",void 0);H("BABYLON.RandomBlock",OM);class y8 extends _t{constructor(e){super(e),this.registerInput("offset",w.Vector3,!0,T.Zero()),this.registerInput("scale",w.Float,!0,1),this.registerInput("octaves",w.Float,!0,2,0,16),this.registerInput("roughness",w.Float,!0,.5,0,1),this.registerOutput("output",w.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,s){const r=e&15,n=r<8?t:i,o=r===12||r==14?t:s,l=r<4?i:o;return this._negateIf(n,r&n)+this._negateIf(l,r&2)}_fade(e){return e*e*e*(e*(e*6-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,l,h,c,u){const d=1-h,f=1-c;return(1-u)*(f*(e*d+t*h)+c*(i*d+s*h))+u*(f*(r*d+n*h)+c*(o*d+l*h))}_perlinNoise(e){const t=(e.x|0)-(e.x<0?1:0),i=(e.y|0)-(e.y<0?1:0),s=(e.z|0)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,l=this._fade(r),h=this._fade(n),c=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),l,h,c)}_perlinSigned(e){return this._perlinNoise(e)*.982}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new T(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,l=1,h=0,c=0;e=Ne.Clamp(e,0,15);const u=e|0;for(let _=0;_<=u;_++){const x=this._perlin(n.scale(o));c+=x*l,h+=l,l*=Ne.Clamp(t,0,1),o*=2}const d=e-Math.floor(e);if(d==0)return c/h;const f=this._perlin(n.scale(o));let m=c+f*l;return c/=h,m/=h+l,(1-d)*c+d*m}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Jt.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}H("BABYLON.NoiseBlock",y8);class DM extends _t{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",w.Geometry),this.registerInput("geometry1",w.Geometry,!0),this.registerInput("geometry2",w.Geometry,!0),this.registerInput("geometry3",w.Geometry,!0),this.registerInput("geometry4",w.Geometry,!0),this.registerOutput("output",w.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=>{let s=this.geometry0.getConnectedValue(i);const r=[];if(s)s=s.clone();else return null;if(this.geometry1.isConnected){const n=this.geometry1.getConnectedValue(i);n&&r.push(n)}if(this.geometry2.isConnected){const n=this.geometry2.getConnectedValue(i);n&&r.push(n)}if(this.geometry3.isConnected){const n=this.geometry3.getConnectedValue(i);n&&r.push(n)}if(this.geometry4.isConnected){const n=this.geometry4.getConnectedValue(i);n&&r.push(n)}return r.length&&s&&(s=s.merge(r,!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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DM.prototype,"evaluateContext",void 0);H("BABYLON.MergeGeometryBlock",DM);class NM extends _t{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",w.Geometry,!0),this.registerInput("geometry1",w.Geometry,!0),this.registerInput("geometry2",w.Geometry,!0),this.registerInput("geometry3",w.Geometry,!0),this.registerInput("geometry4",w.Geometry,!0),this.registerInput("geometry5",w.Geometry,!0),this.registerInput("geometry6",w.Geometry,!0),this.registerInput("geometry7",w.Geometry,!0),this.registerInput("geometry8",w.Geometry,!0),this.registerInput("geometry9",w.Geometry,!0),this.registerOutput("output",w.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,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=i=>{const s=[];return this._storeGeometry(this.geometry0,i,0,s),this._storeGeometry(this.geometry1,i,1,s),this._storeGeometry(this.geometry2,i,2,s),this._storeGeometry(this.geometry3,i,3,s),this._storeGeometry(this.geometry4,i,4,s),this._storeGeometry(this.geometry5,i,5,s),this._storeGeometry(this.geometry6,i,6,s),this._storeGeometry(this.geometry7,i,7,s),this._storeGeometry(this.geometry8,i,8,s),this._storeGeometry(this.geometry9,i,9,s),s.length?s[Math.round(Math.random()*(s.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],NM.prototype,"evaluateContext",void 0);H("BABYLON.GeometryCollectionBlock",NM);class A8 extends _t{constructor(e){super(e),this.registerInput("input",w.AutoDetect),this.registerOutput("output",w.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=s=>i.getConnectedValue(s)}}H("BABYLON.GeometryElbowBlock",A8);class R8 extends _t{constructor(e){super(e),this.registerInput("geometry",w.Geometry),this.registerOutput("output",w.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=[]),Se.ComputeNormals(t.positions,t.indices,t.normals),t}}}H("BABYLON.ComputeNormalsBlock",R8);class I8 extends _t{constructor(e){super(e),this.registerInput("xyzw ",w.Vector4,!0),this.registerInput("xyz ",w.Vector3,!0),this.registerInput("xy ",w.Vector2,!0),this.registerInput("zw ",w.Vector2,!0),this.registerInput("x ",w.Float,!0),this.registerInput("y ",w.Float,!0),this.registerInput("z ",w.Float,!0),this.registerInput("w ",w.Float,!0),this.registerOutput("xyzw",w.Vector4),this.registerOutput("xyz",w.Vector3),this.registerOutput("xy",w.Vector2),this.registerOutput("zw",w.Vector2),this.registerOutput("x",w.Float),this.registerOutput("y",w.Float),this.registerOutput("z",w.Float),this.registerOutput("w",w.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,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,l=this.xyzIn,h=this.xyzwIn,c=this.xyzwOut,u=this.xyzOut,d=this.xyOut,f=this.zwOut,m=this.xOut,_=this.yOut,x=this.zOut,E=this.wOut,S=C=>{if(h.isConnected)return h.getConnectedValue(C);let y=0,A=0,I=0,R=0;if(t.isConnected&&(y=t.getConnectedValue(C)),i.isConnected&&(A=i.getConnectedValue(C)),s.isConnected&&(I=s.getConnectedValue(C)),r.isConnected&&(R=r.getConnectedValue(C)),n.isConnected){const N=n.getConnectedValue(C);N&&(y=N.x,A=N.y)}if(o.isConnected){const N=o.getConnectedValue(C);N&&(I=N.x,R=N.y)}if(l.isConnected){const N=l.getConnectedValue(C);N&&(y=N.x,A=N.y,I=N.z)}return new tt(y,A,I,R)};c._storedFunction=C=>S(C),u._storedFunction=C=>{const y=S(C);return new T(y.x,y.y,y.z)},d._storedFunction=C=>{const y=S(C);return new ce(y.x,y.y)},f._storedFunction=C=>{const y=S(C);return new ce(y.z,y.w)},m._storedFunction=C=>S(C).x,_._storedFunction=C=>S(C).y,x._storedFunction=C=>S(C).z,E._storedFunction=C=>S(C).w}}H("BABYLON.VectorConverterBlock",I8);class P8 extends _t{constructor(e){super(e),this.registerInput("input",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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()}}H("BABYLON.NormalizeVectorBlock",P8);class wM extends _t{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",w.Geometry),this.registerInput("id",w.Int,!0,0),this.registerOutput("output",w.Geometry),this.id.acceptedConnectionPointTypes.push(w.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 s=this.geometry.getConnectedValue(i);if(!s||!s.indices||!s.positions)return s;const r=new jm;return r.materialIndex=this.id.getConnectedValue(i)|0,r.indexStart=0,r.indexCount=s.indices.length,r.verticesStart=0,r.verticesCount=s.positions.length/3,s.materialInfos=[r],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),e.evaluateContext!==void 0&&(this.evaluateContext=e.evaluateContext)}}v([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],wM.prototype,"evaluateContext",void 0);H("BABYLON.SetMaterialIDBlock",wM);var zt;(function(a){a[a.Cos=0]="Cos",a[a.Sin=1]="Sin",a[a.Abs=2]="Abs",a[a.Exp=3]="Exp",a[a.Round=4]="Round",a[a.Floor=5]="Floor",a[a.Ceiling=6]="Ceiling",a[a.Sqrt=7]="Sqrt",a[a.Log=8]="Log",a[a.Tan=9]="Tan",a[a.ArcTan=10]="ArcTan",a[a.ArcCos=11]="ArcCos",a[a.ArcSin=12]="ArcSin",a[a.Sign=13]="Sign",a[a.Negate=14]="Negate",a[a.OneMinus=15]="OneMinus",a[a.Reciprocal=16]="Reciprocal",a[a.ToDegrees=17]="ToDegrees",a[a.ToRadians=18]="ToRadians",a[a.Fract=19]="Fract",a[a.Exp2=20]="Exp2"})(zt||(zt={}));class FM extends _t{constructor(e){super(e),this.operation=zt.Cos,this.registerInput("input",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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 zt.Cos:{t=i=>Math.cos(i);break}case zt.Sin:{t=i=>Math.sin(i);break}case zt.Abs:{t=i=>Math.abs(i);break}case zt.Exp:{t=i=>Math.exp(i);break}case zt.Exp2:{t=i=>Math.pow(2,i);break}case zt.Round:{t=i=>Math.round(i);break}case zt.Floor:{t=i=>Math.floor(i);break}case zt.Ceiling:{t=i=>Math.ceil(i);break}case zt.Sqrt:{t=i=>Math.sqrt(i);break}case zt.Log:{t=i=>Math.log(i);break}case zt.Tan:{t=i=>Math.tan(i);break}case zt.ArcTan:{t=i=>Math.atan(i);break}case zt.ArcCos:{t=i=>Math.acos(i);break}case zt.ArcSin:{t=i=>Math.asin(i);break}case zt.Sign:{t=i=>Math.sign(i);break}case zt.Negate:{t=i=>-i;break}case zt.OneMinus:{t=i=>1-i;break}case zt.Reciprocal:{t=i=>1/i;break}case zt.ToRadians:{t=i=>i*Math.PI/180;break}case zt.ToDegrees:{t=i=>i*180/Math.PI;break}case zt.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 w.Int:case w.Float:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return t(s)};break}case w.Vector2:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new ce(t(s.x),t(s.y))};break}case w.Vector3:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new T(t(s.x),t(s.y),t(s.z))};break}case w.Vector4:{this.output._storedFunction=i=>{const s=this.input.getConnectedValue(i);return new tt(t(s.x),t(s.y),t(s.z),t(s.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.${zt[this.operation]}; +`}}v([it("Operation",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:zt.Cos},{label:"Sin",value:zt.Sin},{label:"Abs",value:zt.Abs},{label:"Exp",value:zt.Exp},{label:"Exp2",value:zt.Exp2},{label:"Round",value:zt.Round},{label:"Floor",value:zt.Floor},{label:"Ceiling",value:zt.Ceiling},{label:"Sqrt",value:zt.Sqrt},{label:"Log",value:zt.Log},{label:"Tan",value:zt.Tan},{label:"ArcTan",value:zt.ArcTan},{label:"ArcCos",value:zt.ArcCos},{label:"ArcSin",value:zt.ArcSin},{label:"Sign",value:zt.Sign},{label:"Negate",value:zt.Negate},{label:"OneMinus",value:zt.OneMinus},{label:"Reciprocal",value:zt.Reciprocal},{label:"ToDegrees",value:zt.ToDegrees},{label:"ToRadians",value:zt.ToRadians},{label:"Fract",value:zt.Fract}]})],FM.prototype,"operation",void 0);H("BABYLON.GeometryTrigonometryBlock",FM);class LM extends _t{constructor(e){super(e),this._rotationMatrix=new L,this._scalingMatrix=new L,this._translationMatrix=new L,this._scalingRotationMatrix=new L,this._transformMatrix=new L,this.evaluateContext=!0,this.registerInput("value",w.AutoDetect),this.registerInput("matrix",w.Matrix,!0),this.registerInput("translation",w.Vector3,!0,T.Zero()),this.registerInput("rotation",w.Vector3,!0,T.Zero()),this.registerInput("scaling",w.Vector3,!0,T.One()),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.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 s=this.value.getConnectedValue(i);if(!s)return null;let r;if(this.matrix.isConnected)r=this.matrix.getConnectedValue(i);else{const n=this.scaling.getConnectedValue(i),o=this.rotation.getConnectedValue(i),l=this.translation.getConnectedValue(i);L.ScalingToRef(n.x,n.y,n.z,this._scalingMatrix),L.RotationYawPitchRollToRef(o.y,o.x,o.z,this._rotationMatrix),L.TranslationToRef(l.x,l.y,l.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),r=this._transformMatrix}switch(this.value.type){case w.Geometry:{const n=s.clone();return n.transform(r),n}case w.Vector2:return ce.Transform(s,r);case w.Vector3:return T.TransformCoordinates(s,r);case w.Vector4:return tt.TransformCoordinates(s,r)}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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],LM.prototype,"evaluateContext",void 0);H("BABYLON.GeometryTransformBlock",LM);class M8 extends _t{constructor(e){super(e),this.registerInput("angle",w.Float,!1,0),this.registerOutput("matrix",w.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new bs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>L.RotationX(this.angle.getConnectedValue(t))}}H("BABYLON.RotationXBlock",M8);class O8 extends _t{constructor(e){super(e),this.registerInput("angle",w.Float,!1,0),this.registerOutput("matrix",w.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new bs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>L.RotationY(this.angle.getConnectedValue(t))}}H("BABYLON.RotationYBlock",O8);class D8 extends _t{constructor(e){super(e),this.registerInput("angle",w.Float,!1,0),this.registerOutput("matrix",w.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new bs("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>L.RotationZ(this.angle.getConnectedValue(t))}}H("BABYLON.RotationZBlock",D8);class N8 extends _t{constructor(e){super(e),this.registerInput("scale",w.Vector3,!1,T.One()),this.registerOutput("matrix",w.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new bs("Scale");e.value=new T(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.scale.getConnectedValue(t);return L.Scaling(i.x,i.y,i.z)}}}H("BABYLON.ScalingBlock",N8);class w8 extends _t{constructor(e){super(e),this.registerInput("source",w.Vector3,!0,T.Up()),this.registerInput("target",w.Vector3,!0,T.Left()),this.registerOutput("matrix",w.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(),s=this.target.getConnectedValue(t).clone(),r=new L;return i.normalize(),s.normalize(),L.RotationAlignToRef(i,s,r,!0),r}}}H("BABYLON.AlignBlock",w8);class F8 extends _t{constructor(e){super(e),this.registerInput("translation",w.Vector3,!1,T.Zero()),this.registerOutput("matrix",w.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new bs("Translation");e.value=new T(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=t=>{const i=this.translation.getConnectedValue(t);return L.Translation(i.x,i.y,i.z)}}}H("BABYLON.TranslationBlock",F8);class TC extends _t{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",w.Geometry),this.registerInput("instance",w.Geometry,!0),this.registerInput("density",w.Float,!0,1,0,1),this.registerInput("matrix",w.Matrix,!0),this.registerInput("rotation",w.Vector3,!0,T.Zero()),this.registerInput("scaling",w.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push(w.Float),this.registerOutput("output",w.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 s=this._vertexData.positions.length/3;const r=[],n=new T,o=[];let l=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexc)continue;n.fromArray(l,this._currentIndex*3);const u=h.clone();if(this.matrix.isConnected){const d=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(u,n,d,r)}else{const d=i.adaptInput(this.scaling,w.Vector3,T.OneReadOnly),f=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(u,n,f,d,r)}this._currentLoopIndex++}if(i.restoreGeometryContext(),i.restoreExecutionContext(),i.restoreInstancingContext(),r.length)if(r.length===1)this._vertexData=r[0];else{const h=r.splice(0,1)[0];this._vertexData=h.merge(r,!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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TC.prototype,"evaluateContext",void 0);v([it("Remove duplicated positions",Qe.Boolean,"ADVANCED",{notifiers:{update:!0}})],TC.prototype,"removeDuplicatedPositions",void 0);H("BABYLON.InstantiateOnVerticesBlock",TC);class BM extends _t{constructor(e){super(e),this._currentPosition=new T,this._currentUV=new ce,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this._tempVector0=new T,this._tempVector1=new T,this._uv0=new ce,this._uv1=new ce,this._uv2=new ce,this.evaluateContext=!0,this.registerInput("geometry",w.Geometry),this.registerInput("instance",w.Geometry,!0),this.registerInput("count",w.Int,!0,256),this.registerInput("matrix",w.Matrix,!0),this.registerInput("rotation",w.Vector3,!0,T.Zero()),this.registerInput("scaling",w.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push(w.Float),this.registerOutput("output",w.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(),T.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 s=null;const r=this.count.getConnectedValue(i),n=this._vertexData.indices.length/3,o=r/n;let l=0;const h=[];let c=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=r);_++){let x=Math.random(),E=Math.random();if(x>E){const I=x;x=E,E=I}const S=x,C=E-x,y=1-S-C;if(this._currentPosition.set(S*this._vertex0.x+C*this._vertex1.x+y*this._vertex2.x,S*this._vertex0.y+C*this._vertex1.y+y*this._vertex2.y,S*this._vertex0.z+C*this._vertex1.z+y*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(S*this._uv0.x+C*this._uv1.x+y*this._uv2.x,S*this._uv0.y+C*this._uv1.y+y*this._uv2.y),s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0){l-=o;continue}const A=s.clone();if(this.matrix.isConnected){const I=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(A,this._currentPosition,I,h)}else{const I=i.adaptInput(this.scaling,w.Vector3,T.OneReadOnly),R=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(A,this._currentPosition,R,I,h)}c++,this._currentLoopIndex++}}if(h.length)if(h.length===1)this._vertexData=h[0];else{const u=h.splice(0,1)[0];this._vertexData=u.merge(h,!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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BM.prototype,"evaluateContext",void 0);H("BABYLON.InstantiateOnFacesBlock",BM);class UM extends _t{constructor(e){super(e),this._currentPosition=new T,this._vertex0=new T,this._vertex1=new T,this._vertex2=new T,this.evaluateContext=!0,this.registerInput("geometry",w.Geometry),this.registerInput("instance",w.Geometry,!0),this.registerInput("count",w.Int,!0,256),this.registerInput("matrix",w.Matrix,!0),this.registerInput("rotation",w.Vector3,!0,T.Zero()),this.registerInput("scaling",w.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push(w.Float),this.registerOutput("output",w.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 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 s=null;const r=this.count.getConnectedValue(i),n=[],o=Lp(this._vertexData.positions,0,this._vertexData.positions.length/3),l=o.minimum,h=o.maximum,c=new T(1,0,0),u=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let d=0;d0&&m++}if(m%2===0){d--;continue}if(s=this.instance.getConnectedValue(i),!s||!s.positions||s.positions.length===0)continue;const _=s.clone();if(this.matrix.isConnected){const x=this.matrix.getConnectedValue(i);i._instantiateWithPositionAndMatrix(_,this._currentPosition,x,n)}else{const x=i.adaptInput(this.scaling,w.Vector3,T.OneReadOnly),E=this.rotation.getConnectedValue(i)||T.ZeroReadOnly;i._instantiate(_,this._currentPosition,E,x,n)}this._currentLoopIndex++}if(n.length)if(n.length===1)this._vertexData=n[0];else{const d=n.splice(0,1)[0];this._vertexData=d.merge(n,!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(){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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],UM.prototype,"evaluateContext",void 0);H("BABYLON.InstantiateOnVolumeBlock",UM);class bx extends _t{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",w.Geometry,!0),this.registerInput("count",w.Int,!0,1),this.registerOutput("output",w.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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bx.prototype,"evaluateContext",void 0);class L8 extends bx{constructor(e){super(e),this.registerInput("matrix",w.Matrix,!0),this.registerInput("position",w.Vector3,!0,T.Zero()),this.registerInput("rotation",w.Vector3,!0,T.Zero()),this.registerInput("scaling",w.Vector3,!0,T.One()),this.scaling.acceptedConnectionPointTypes.push(w.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 s=this.count.getConnectedValue(i),r=[];for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=L.Identity(),o=T.Zero(),l=T.Zero(),h=T.Zero();for(this._currentIndex=0;this._currentIndex{i.pushExecutionContext(this),i.pushInstancingContext(this);const s=this.count.getConnectedValue(i),r=[],n=L.Identity(),o=L.Identity(),l=L.Identity(),h=T.Zero(),c=T.Zero(),u=T.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}}H("BABYLON.IntFloatConverterBlock",V8);class k8 extends _t{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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 s=this.input.getConnectedValue(i);if(s==null)return this.log.push(["null",""]),s;switch(this.input.type){case w.Vector2:this.log.push([Z6(s,4),s.toString()]);break;case w.Vector3:this.log.push([J6(s,4),s.toString()]);break;case w.Vector4:this.log.push([e8(s,4),s.toString()]);break;default:this.log.push([s.toString(),s.toString()]);break}return s};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}H("BABYLON.DebugBlock",k8);class G8 extends _t{constructor(e){super(e),this.registerInput("geometry",w.Geometry),this.registerOutput("output",w.Geometry),this.registerOutput("id",w.Int),this.registerOutput("collectionId",w.Int),this.registerOutput("verticesCount",w.Int),this.registerOutput("facesCount",w.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)}}H("BABYLON.GeometryInfoBlock",G8);var Do;(function(a){a[a.Spherical=0]="Spherical",a[a.Cylindrical=1]="Cylindrical",a[a.Cubic=2]="Cubic"})(Do||(Do={}));class VM extends _t{constructor(e){super(e),this.mapping=Do.Spherical,this.registerInput("position",w.Vector3),this.registerInput("normal",w.Vector3),this.registerInput("center",w.Vector3,!0,T.Zero()),this.registerOutput("uv",w.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=T.Zero(),t=i=>{const s=this.position.getConnectedValue(i)||T.Zero(),r=this.normal.getConnectedValue(i)||T.Zero(),n=this.center.getConnectedValue(i),o=ce.Zero();switch(this.mapping){case Do.Spherical:{s.subtractToRef(n,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 Do.Cylindrical:{s.subtractToRef(n,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 Do.Cubic:{const l=Math.abs(r.x),h=Math.abs(r.y),c=Math.abs(r.z),u=Math.max(Math.abs(s.x),Math.abs(s.y),Math.abs(s.z));let d=0,f=0;l>=h&&l>=c?(d=s.y/u-n.y,f=s.z/u-n.z):h>=l&&h>=c?(d=s.x/u-n.x,f=s.z/u-n.z):(d=s.x/u-n.x,f=s.y/u-n.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.${Do[this.mapping]}; +`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}v([it("Mapping",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:Do.Spherical},{label:"Cylindrical",value:Do.Cylindrical},{label:"Cubic",value:Do.Cubic}]})],VM.prototype,"mapping",void 0);H("BABYLON.MappingBlock",VM);class z8 extends _t{constructor(e){super(e),this.registerInput("matrix0",w.Matrix),this.registerInput("matrix1",w.Matrix),this.registerOutput("output",w.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)}}}H("BABYLON.MatrixComposeBlock",z8);class W8 extends _t{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",w.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)t.indexOf(s)===-1&&(i+=s._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)}}H("BABYLON.TeleportInBlock",W8);class H8 extends _t{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",w.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}}H("BABYLON.TeleportOutBlock",H8);class kM extends _t{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",w.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const l=n.getImageData(0,0,s.width,s.height).data,h=new Float32Array(l.length);for(let c=0;c{this._data=null,i()},s.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 s=e.getSize();t4.GetTextureDataAsync(e,s.width,s.height).then(async r=>{const n=new Float32Array(r.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 s=this.coordinates.getConnectedValue(t);if(!s)return null;const r=this.clampCoordinates?Math.max(0,Math.min(s.x,1)):this._repeatClamp(s.x),n=this.clampCoordinates?Math.max(0,Math.min(s.y,1)):this._repeatClamp(s.y),o=Math.floor(r*(i.width-1)),l=Math.floor(n*(i.height-1)),h=o+i.width*l;return tt.FromArray(i.data,h*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([it("Clamp Coordinates",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GM.prototype,"clampCoordinates",void 0);H("BABYLON.GeometryTextureFetchBlock",GM);class X8 extends _t{constructor(e){super(e),this.registerInput("geometry",w.Geometry),this.registerOutput("min",w.Vector3),this.registerOutput("max",w.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?Lp(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Lp(t.positions,0,t.positions.length/3).maximum:null}}}H("BABYLON.BoundingBlock",X8);var No;(function(a){a[a.Intersect=0]="Intersect",a[a.Subtract=1]="Subtract",a[a.Union=2]="Union"})(No||(No={}));class EC extends _t{constructor(e){super(e),this.evaluateContext=!1,this.operation=No.Intersect,this.registerInput("geometry0",w.Geometry),this.registerInput("geometry1",w.Geometry),this.registerOutput("output",w.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 s=this.geometry0.getConnectedValue(i),r=this.geometry1.getConnectedValue(i);if(!s||!r)return null;const n=s.positions.length/3;!s.normals&&r.normals&&(s.normals=new Array(s.positions.length)),!r.normals&&s.normals&&(r.normals=new Array(r.positions.length)),!s.uvs&&r.uvs&&(s.uvs=new Array(n*2)),!r.uvs&&s.uvs&&(r.uvs=new Array(n*2)),!s.colors&&r.colors&&(s.colors=new Array(n*4)),!r.colors&&s.colors&&(r.colors=new Array(n*4));const o=Io.FromVertexData(s),l=Io.FromVertexData(r);let h;switch(this.operation){case No.Intersect:h=o.intersect(l);break;case No.Subtract:h=o.subtract(l);break;case No.Union:h=o.union(l);break}return h.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.${No[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([it("Evaluate context",Qe.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],EC.prototype,"evaluateContext",void 0);v([it("Operation",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:No.Intersect},{label:"Subtract",value:No.Subtract},{label:"Union",value:No.Union}]})],EC.prototype,"operation",void 0);H("BABYLON.BooleanGeometryBlock",EC);class Y8 extends _t{constructor(e){super(e),this.registerInput("x",w.AutoDetect),this.registerInput("y",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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),s=this.y.getConnectedValue(t);switch(this.x.type){case w.Int:case w.Float:return e(i,s);case w.Vector2:return new ce(e(i.x,s.x),e(i.y,s.y));case w.Vector3:return new T(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case w.Vector4:return new tt(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}H("BABYLON.GeometryArcTan2Block",Y8);class $8 extends _t{constructor(e){super(e),this.registerInput("left",w.AutoDetect),this.registerInput("right",w.AutoDetect),this.registerInput("gradient",w.Float),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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,s)=>(1-t)*i+t*s;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case w.Int:case w.Float:return e(r,i,s);case w.Vector2:return new ce(e(r,i.x,s.x),e(r,i.y,s.y));case w.Vector3:return new T(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case w.Vector4:return new tt(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}H("BABYLON.GeometryLerpBlock",$8);class K8 extends _t{constructor(e){super(e),this.registerInput("left",w.AutoDetect),this.registerInput("right",w.AutoDetect),this.registerInput("gradient",w.Float),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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,s)=>(1-t)*i+t*s;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case w.Int:case w.Float:return e(r,i,s);case w.Vector2:{const n=new ce(e(r,i.x,s.x),e(r,i.y,s.y));return n.normalize(),n}case w.Vector3:{const n=new T(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return n.normalize(),n}case w.Vector4:{const n=new tt(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return n.normalize(),n}}return 0},this}}H("BABYLON.GeometryNLerpBlock",K8);class j8 extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("edge",w.Float),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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),s=this.edge.getConnectedValue(t);switch(this.value.type){case w.Int:case w.Float:return e(i,s);case w.Vector2:return new ce(e(i.x,s),e(i.y,s));case w.Vector3:return new T(e(i.x,s),e(i.y,s),e(i.z,s));case w.Vector4:return new tt(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}H("BABYLON.GeometryStepBlock",j8);class q8 extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("edge0",w.Float),this.registerInput("edge1",w.Float),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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,s)=>{const r=Math.max(0,Math.min((t-i)/(s-i),1));return r*r*(3-2*r)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case w.Int:case w.Float:return e(i,s,r);case w.Vector2:return new ce(e(i.x,s,r),e(i.y,s,r));case w.Vector3:return new T(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case w.Vector4:return new tt(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}H("BABYLON.GeometrySmoothStepBlock",q8);class Q8 extends _t{constructor(e){super(e),this.registerInput("left",w.AutoDetect),this.registerInput("right",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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),s=this.right.getConnectedValue(t);switch(this.left.type){case w.Int:case w.Float:return e(i,s);case w.Vector2:return new ce(e(i.x,s.x),e(i.y,s.y));case w.Vector3:return new T(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case w.Vector4:return new tt(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}H("BABYLON.GeometryModBlock",Q8);class Z8 extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("power",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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),s=this.power.getConnectedValue(t);switch(this.value.type){case w.Int:case w.Float:return e(i,s);case w.Vector2:return new ce(e(i.x,s),e(i.y,s));case w.Vector3:return new T(e(i.x,s),e(i.y,s),e(i.z,s));case w.Vector4:return new tt(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}H("BABYLON.GeometryPowBlock",Z8);class SC extends _t{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Geometry),this._inputs[0].excludedConnectionPointTypes.push(w.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 w.Int:case w.Float:return e(i);case w.Vector2:return new ce(e(i.x),e(i.y));case w.Vector3:return new T(e(i.x),e(i.y),e(i.z));case w.Vector4:return new tt(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([it("Minimum",Qe.Float)],SC.prototype,"minimum",void 0);v([it("Maximum",Qe.Float)],SC.prototype,"maximum",void 0);H("BABYLON.GeometryClampBlock",SC);class J8 extends _t{constructor(e){super(e),this.registerInput("left",w.AutoDetect),this.registerInput("right",w.AutoDetect),this.registerOutput("output",w.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Int),this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.Vector2),this._inputs[1].excludedConnectionPointTypes.push(w.Int),this._inputs[1].excludedConnectionPointTypes.push(w.Float),this._inputs[1].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].excludedConnectionPointTypes.push(w.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 w.Vector3:return T.Cross(t,i);case w.Vector4:return T.Cross(t.toVector3(),i.toVector3())}return 0},this}}H("BABYLON.GeometryCrossBlock",J8);var Pt;(function(a){a[a.EaseInSine=0]="EaseInSine",a[a.EaseOutSine=1]="EaseOutSine",a[a.EaseInOutSine=2]="EaseInOutSine",a[a.EaseInQuad=3]="EaseInQuad",a[a.EaseOutQuad=4]="EaseOutQuad",a[a.EaseInOutQuad=5]="EaseInOutQuad",a[a.EaseInCubic=6]="EaseInCubic",a[a.EaseOutCubic=7]="EaseOutCubic",a[a.EaseInOutCubic=8]="EaseInOutCubic",a[a.EaseInQuart=9]="EaseInQuart",a[a.EaseOutQuart=10]="EaseOutQuart",a[a.EaseInOutQuart=11]="EaseInOutQuart",a[a.EaseInQuint=12]="EaseInQuint",a[a.EaseOutQuint=13]="EaseOutQuint",a[a.EaseInOutQuint=14]="EaseInOutQuint",a[a.EaseInExpo=15]="EaseInExpo",a[a.EaseOutExpo=16]="EaseOutExpo",a[a.EaseInOutExpo=17]="EaseInOutExpo",a[a.EaseInCirc=18]="EaseInCirc",a[a.EaseOutCirc=19]="EaseOutCirc",a[a.EaseInOutCirc=20]="EaseInOutCirc",a[a.EaseInBack=21]="EaseInBack",a[a.EaseOutBack=22]="EaseOutBack",a[a.EaseInOutBack=23]="EaseInOutBack",a[a.EaseInElastic=24]="EaseInElastic",a[a.EaseOutElastic=25]="EaseOutElastic",a[a.EaseInOutElastic=26]="EaseInOutElastic"})(Pt||(Pt={}));class zM extends _t{constructor(e){super(e),this.type=Pt.EaseInOutSine,this.registerInput("input",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[0].excludedConnectionPointTypes.push(w.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 Pt.EaseInSine:e=t=>1-Math.cos(t*3.1415/2);break;case Pt.EaseOutSine:e=t=>Math.sin(t*3.1415/2);break;case Pt.EaseInOutSine:e=t=>-(Math.cos(t*3.1415)-1)/2;break;case Pt.EaseInQuad:e=t=>t*t;break;case Pt.EaseOutQuad:e=t=>(1-t)*(1-t);break;case Pt.EaseInOutQuad:{e=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;break}case Pt.EaseInCubic:e=t=>t*t*t;break;case Pt.EaseOutCubic:{e=t=>1-Math.pow(1-t,3);break}case Pt.EaseInOutCubic:{e=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;break}case Pt.EaseInQuart:e=t=>t*t*t*t;break;case Pt.EaseOutQuart:{e=t=>1-Math.pow(1-t,4);break}case Pt.EaseInOutQuart:{e=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;break}case Pt.EaseInQuint:e=t=>t*t*t*t*t;break;case Pt.EaseOutQuint:{e=t=>1-Math.pow(1-t,5);break}case Pt.EaseInOutQuint:{e=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;break}case Pt.EaseInExpo:{e=t=>t===0?0:Math.pow(2,10*t-10);break}case Pt.EaseOutExpo:{e=t=>t===1?1:1-Math.pow(2,-10*t);break}case Pt.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 Pt.EaseInCirc:{e=t=>1-Math.sqrt(1-Math.pow(t,2));break}case Pt.EaseOutCirc:{e=t=>Math.sqrt(1-Math.pow(t-1,2));break}case Pt.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 Pt.EaseInBack:{e=t=>2.70158*t*t*t-1.70158*t*t;break}case Pt.EaseOutBack:{e=t=>2.70158*Math.pow(t-1,3)+1.70158*Math.pow(t-1,2);break}case Pt.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 Pt.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 Pt.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 Pt.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 w.Float:return e(i);case w.Vector2:return new ce(e(i.x),e(i.y));case w.Vector3:return new T(e(i.x),e(i.y),e(i.z));case w.Vector4:return new tt(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.${Pt[this.type]}; +`}}v([it("Type",Qe.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:Pt.EaseInSine},{label:"EaseOutSine",value:Pt.EaseOutSine},{label:"EaseInOutSine",value:Pt.EaseInOutSine},{label:"EaseInQuad",value:Pt.EaseInQuad},{label:"EaseOutQuad",value:Pt.EaseOutQuad},{label:"EaseInOutQuad",value:Pt.EaseInOutQuad},{label:"EaseInCubic",value:Pt.EaseInCubic},{label:"EaseOutCubic",value:Pt.EaseOutCubic},{label:"EaseInOutCubic",value:Pt.EaseInOutCubic},{label:"EaseInQuart",value:Pt.EaseInQuart},{label:"EaseOutQuart",value:Pt.EaseOutQuart},{label:"EaseInOutQuart",value:Pt.EaseInOutQuart},{label:"EaseInQuint",value:Pt.EaseInQuint},{label:"EaseOutQuint",value:Pt.EaseOutQuint},{label:"EaseInOutQuint",value:Pt.EaseInOutQuint},{label:"EaseInExpo",value:Pt.EaseInExpo},{label:"EaseOutExpo",value:Pt.EaseOutExpo},{label:"EaseInOutExpo",value:Pt.EaseInOutExpo},{label:"EaseInCirc",value:Pt.EaseInCirc},{label:"EaseOutCirc",value:Pt.EaseOutCirc},{label:"EaseInOutCirc",value:Pt.EaseInOutCirc},{label:"EaseInBack",value:Pt.EaseInBack},{label:"EaseOutBack",value:Pt.EaseOutBack},{label:"EaseInOutBack",value:Pt.EaseInOutBack},{label:"EaseInElastic",value:Pt.EaseInElastic},{label:"EaseOutElastic",value:Pt.EaseOutElastic},{label:"EaseInOutElastic",value:Pt.EaseInOutElastic}]})],zM.prototype,"type",void 0);H("BABYLON.GeometryCurveBlock",zM);class eK extends _t{constructor(e){super(e),this.registerInput("color",w.Vector3),this.registerInput("level",w.Float,!0,0),this.registerOutput("output",w.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),s=Math.min(t.x,t.y,t.z),r=Math.max(t.x,t.y,t.z),n=.5*(s+r);return new T(t.x*(1-i)+n*i,t.y*(1-i)+n*i,t.z*(1-i)+n*i)},this}}H("BABYLON.GeometryDesaturateBlock",eK);class tK extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("steps",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(w.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 s=i;if(this.steps.type===w.Float)switch(this.value.type){case w.Vector2:s=new ce(i,i);break;case w.Vector3:s=new T(i,i,i);break;case w.Vector4:s=new tt(i,i,i,i);break}switch(this.value.type){case w.Vector2:return new ce(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case w.Vector3:return new T(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case w.Vector4:return new tt(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this}}H("BABYLON.GeometryPosterizeBlock",tK);class iK extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerInput("reference",w.AutoDetect),this.registerInput("distance",w.Float),this.registerInput("replacement",w.AutoDetect),this.registerOutput("output",w.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].excludedConnectionPointTypes.push(w.Float),this._inputs[1].excludedConnectionPointTypes.push(w.Matrix),this._inputs[3].excludedConnectionPointTypes.push(w.Float),this._inputs[3].excludedConnectionPointTypes.push(w.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),s=this.distance.getConnectedValue(e),r=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}}H("BABYLON.GeometryDistanceBlock",sK);class rK extends _t{constructor(e){super(e),this.registerInput("left",w.AutoDetect),this.registerInput("right",w.AutoDetect),this.registerOutput("output",w.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(w.Int),this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Matrix),this._inputs[1].excludedConnectionPointTypes.push(w.Float),this._inputs[1].excludedConnectionPointTypes.push(w.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}}H("BABYLON.GeometryDotBlock",rK);class nK extends _t{constructor(e){super(e),this.registerInput("value",w.AutoDetect),this.registerOutput("output",w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.Int),this._inputs[0].excludedConnectionPointTypes.push(w.Float),this._inputs[0].excludedConnectionPointTypes.push(w.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}}H("BABYLON.GeometryLengthBlock",nK);class aK extends _t{constructor(e){super(e),this.registerInput("input",w.Vector2),this.registerInput("angle",w.Float),this.registerOutput("output",w.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 ce(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this}}H("BABYLON.GeometryRotate2dBlock",aK);class hc extends q{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=L.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new Se;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new xr(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[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 Hp(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const r=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(r-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[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)),s=`end_header +`,r=i.indexOf(s);if(r<0||!i)return e;const n=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},h=[],c=i.slice(0,r).split(` +`).filter(x=>x.startsWith("property "));for(const x of c){const[,E,S]=x.split(" ");if(h.push({name:S,type:E,offset:o}),l[E])o+=l[E];else return U.Error(`Unsupported property type: ${E}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0)}const u=3*4+3*4+4+4,d=.28209479177387814,f=new DataView(e,r+s.length),m=new ArrayBuffer(u*n),_=new ae;for(let x=0;x{this._loadData(hc.ConvertPLYToSplat(t))})}dispose(e){var t,i,s,r,n,o;(t=this._covariancesATexture)==null||t.dispose(),(i=this._covariancesBTexture)==null||i.dispose(),(s=this._centersTexture)==null||s.dispose(),(r=this._colorsTexture)==null||r.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,(n=this._material)==null||n.dispose(!1,!0),this._material=null,(o=this._worker)==null||o.terminate(),this._worker=null,super.dispose(e)}_loadData(e){var A;if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=3*4+3*4+4+4,r=t.length/s;this._vertexCount=r;const n=this._getTextureSize(r),o=n.x*n.y,l=new Float32Array(3*o),h=new Float32Array(3*o),c=new Float32Array(3*o),u=W.Matrix[0],d=W.Matrix[1],f=W.Quaternion[0],m=new T(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new T(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let I=0;Inew gs(I,R,N,k,this._scene,!1,!1,2,1),C=I=>{const R=I.length/3,N=new Float32Array(R*4);for(let k=0;k{this._depthMix=I.data.depthMix;const R=new Uint32Array(I.data.depthMix.buffer);for(let N=0;Ni&&(U.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new ce(i,s)}}hc._CreateWorker=function(a){let e=0,t,i,s,r;a.onmessage=n=>{if(n.data.positions)t=n.data.positions,e=n.data.vertexCount;else{const o=n.data.view;if(!t||!o)throw new Error("positions or view is not defined!");i=n.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let l=0;lnew sn(a,e,t);class sn{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=sn._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,sn.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Z.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 s=!1,r=i();const n=new hs;navigator.onLine&&(s=!0,r=r+(r.match(/\?/)==null?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",()=>{if(n.status===200||sn._ValidateXHRData(n,1))try{const o=JSON.parse(n.response);this._enableSceneOffline=o.enableSceneOffline,this._enableTexturesOffline=o.enableTexturesOffline&&sn._IsUASupportingBlobStorage,o.version&&!isNaN(parseInt(o.version))&&(this._manifestVersionFound=o.version),e(!0)}catch{t()}else t()},!1),n.addEventListener("error",()=>{if(s){s=!1;const o=i();n.open("GET",o),n.send()}else t()},!1);try{n.send()}catch{U.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 s=this._idbFactory.open("babylonjs",1);s.onerror=()=>{i()},s.onblocked=()=>{U.Error("IDB request blocked. Please reload the page."),i()},s.onsuccess=()=>{this._db=s.result,e()},s.onupgradeneeded=r=>{if(this._db=r.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(n){U.Error("Error while creating object stores. Exception: "+n.message),i()}}}}loadImage(e,t){const i=sn._ReturnFullUrlLocation(e),s=()=>{!this._hasReachedQuota&&this._db!==null?this._saveImageIntoDBAsync(i,t):t.src=e};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&this._db!==null){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let o;s&&typeof URL=="function"?(o=URL.createObjectURL(s.data),t.onerror=()=>{U.Error("Error loading image from blob URL: "+o+" switching back to web url: "+e),t.src=e},t.src=o):i()};const n=r.objectStore("textures").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{U.Error("Error loading texture "+e+" from DB."),t.src=e}}else U.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 s=()=>{let r;if(i&&typeof URL=="function")try{r=URL.createObjectURL(i)}catch{r=URL.createObjectURL(i)}r&&(t.src=r)};if(sn._IsUASupportingBlobStorage){const r=new hs;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(r.status===200&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=l=>{try{const c=l.target.error;c&&c.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const l=n.objectStore("textures").put(o);l.onsuccess=()=>{},l.onerror=()=>{s()}}catch(l){l.code===25&&(sn._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{U.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else U.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 s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=o=>{s=o.target.result},n.onerror=()=>{U.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(r){U.Error("Error while accessing 'versions' object store (READ OP). Exception: "+r.message),t(-1)}}else U.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=n=>{try{const o=n.target.error;o&&o.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{U.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){U.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=sn._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,l=>{l!==-1?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s;e.indexOf(".babylon")!==-1?s="scenes":s="textures";let r;const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=l=>{r=l.target.result},o.onerror=()=>{U.Error("Error loading file "+e+" from DB."),i()}}else U.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;e.indexOf(".babylon")!==-1?n="scenes":n="textures";const o=new hs;let l;o.open("GET",e+(e.match(/\?/)==null?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(o.status===200||o.status<400&&sn._ValidateXHRData(o,s?6:1))if(l=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const h=this._db.transaction([n],"readwrite");h.onabort=u=>{try{const d=u.target.error;d&&d.name==="QuotaExceededError"&&(this._hasReachedQuota=!0)}catch{}t(l)},h.oncomplete=()=>{t(l)};let c;n==="scenes"?c={sceneUrl:e,data:l,version:this._manifestVersionFound}:c={textureUrl:e,data:l};try{const u=h.objectStore(n).put(c);u.onsuccess=()=>{},u.onerror=()=>{U.Error("Error in DB add file request in BABYLON.Database.")}}catch{t(l)}}else t(l);else o.status>=400&&r?r(o):t()},!1),o.addEventListener("error",()=>{U.Error("error on XHR request."),r&&r()},!1),o.send()}else U.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}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=Ex(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}}sn._IsUASupportingBlobStorage=!0;sn.IDBStorageEnabled=!1;sn._ParseURL=a=>{const e=document.createElement("a");e.href=a;const t=a.substring(0,a.lastIndexOf("#")),i=a.substring(t.lastIndexOf("/")+1,a.length);return a.substring(0,a.indexOf(i,0))};sn._ReturnFullUrlLocation=a=>a.indexOf("http:/")===-1&&a.indexOf("https:/")===-1&&typeof window<"u"?sn._ParseURL(window.location.href)+a:a;class oh{constructor(){this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.minEmitBox=new T(-.5,-.5,-.5),this.maxEmitBox=new T(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=ni(this.direction1.x,this.direction2.x),n=ni(this.direction1.y,this.direction2.y),o=ni(this.direction1.z,this.direction2.z);if(s){t.x=r,t.y=n,t.z=o;return}T.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=ni(this.minEmitBox.x,this.maxEmitBox.x),n=ni(this.minEmitBox.y,this.maxEmitBox.y),o=ni(this.minEmitBox.z,this.maxEmitBox.z);if(s){t.x=r,t.y=n,t.z=o;return}T.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new oh;return Tr.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),T.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),T.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class yx{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,s){s?W.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),W.Vector3[0]).normalize();const r=Ne.RandomRange(0,this.directionRandomizer),n=Ne.RandomRange(0,this.directionRandomizer),o=Ne.RandomRange(0,this.directionRandomizer);t.x=W.Vector3[0].x+r,t.y=W.Vector3[0].y+n,t.z=W.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=Ne.RandomRange(0,Math.PI*2);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=Ne.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-Ne.RandomRange(0,this._radius*this.radiusRange);o=o*n;const l=o*Math.sin(r),h=o*Math.cos(r),c=n*this._height;if(s){t.x=l,t.y=c,t.z=h;return}T.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new yx(this._radius,this._angle,this.directionRandomizer);return Tr.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 x_{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=T.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),T.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=Ne.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);if(o+=Ne.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s){t.copyFrom(this._tempVector);return}T.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=Ne.RandomRange(-this.height/2,this.height/2),n=Ne.RandomRange(0,2*Math.PI),o=Ne.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(o)*this.radius,h=l*Math.cos(n),c=l*Math.sin(n);if(s){t.copyFromFloats(h,r,c);return}T.TransformCoordinatesFromFloatsToRef(h,r,c,e,t)}clone(){const e=new x_(this.radius,this.directionRandomizer);return Tr.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 Ax extends x_{constructor(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=Ne.RandomRange(this.direction1.x,this.direction2.x),n=Ne.RandomRange(this.direction1.y,this.direction2.y),o=Ne.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}T.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new Ax(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Tr.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),T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2)}}class Rx{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=Ne.RandomRange(0,this.directionRandomizer),o=Ne.RandomRange(0,this.directionRandomizer),l=Ne.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}T.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-Ne.RandomRange(0,this.radius*this.radiusRange),n=Ne.RandomRange(0,1),o=Ne.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(o)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(h,Math.abs(c),u);return}T.TransformCoordinatesFromFloatsToRef(h,Math.abs(c),u,e,t)}clone(){const e=new Rx(this.radius,this.directionRandomizer);return Tr.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 Ix{constructor(){this.direction1=new T(0,1,0),this.direction2=new T(0,1,0)}startDirectionFunction(e,t,i,s){const r=Ne.RandomRange(this.direction1.x,this.direction2.x),n=Ne.RandomRange(this.direction1.y,this.direction2.y),o=Ne.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}T.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(s){t.copyFromFloats(0,0,0);return}T.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new Ix;return Tr.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2)}}class T_{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=Ne.RandomRange(0,this.directionRandomizer),o=Ne.RandomRange(0,this.directionRandomizer),l=Ne.RandomRange(0,this.directionRandomizer);if(r.x+=n,r.y+=o,r.z+=l,r.normalize(),s){t.copyFrom(r);return}T.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-Ne.RandomRange(0,this.radius*this.radiusRange),n=Ne.RandomRange(0,1),o=Ne.RandomRange(0,2*Math.PI),l=Math.acos(2*n-1),h=r*Math.cos(o)*Math.sin(l),c=r*Math.cos(l),u=r*Math.sin(o)*Math.sin(l);if(s){t.copyFromFloats(h,c,u);return}T.TransformCoordinatesFromFloatsToRef(h,c,u,e,t)}clone(){const e=new T_(this.radius,this.directionRandomizer);return Tr.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 Px extends T_{constructor(e=1,t=new T(0,1,0),i=new T(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=Ne.RandomRange(this.direction1.x,this.direction2.x),s=Ne.RandomRange(this.direction1.y,this.direction2.y),r=Ne.RandomRange(this.direction1.z,this.direction2.z);T.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new Px(this.radius,this.direction1,this.direction2);return Tr.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 lh{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=W.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const n=W.Vector3[1];r.subtractToRef(i.position,n),n.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);if(s){t.copyFrom(r);return}T.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=W.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s){t.copyFrom(r);return}T.TransformCoordinatesToRef(r,e,t)}clone(){const e=new lh;return Tr.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 vC{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(P.PositionKind),this._normals=e.getVerticesData(P.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=T.Zero(),this._mesh=null,this.direction1=new T(0,1,0),this.direction2=new T(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals){T.TransformNormalToRef(this._storedNormal,e,t);return}const r=Ne.RandomRange(this.direction1.x,this.direction2.x),n=Ne.RandomRange(this.direction1.y,this.direction2.y),o=Ne.RandomRange(this.direction1.z,this.direction2.z);if(s){t.copyFromFloats(r,n,o);return}T.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),l=1-n-o,h=this._indices[r],c=this._indices[r+1],u=this._indices[r+2],d=W.Vector3[0],f=W.Vector3[1],m=W.Vector3[2],_=W.Vector3[3];T.FromArrayToRef(this._positions,h*3,d),T.FromArrayToRef(this._positions,c*3,f),T.FromArrayToRef(this._positions,u*3,m),_.x=n*d.x+o*f.x+l*m.x,_.y=n*d.y+o*f.y+l*m.y,_.z=n*d.z+o*f.z+l*m.z,s?t.copyFromFloats(_.x,_.y,_.z):T.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(T.FromArrayToRef(this._normals,h*3,d),T.FromArrayToRef(this._normals,c*3,f),T.FromArrayToRef(this._normals,u*3,m),this._storedNormal.x=n*d.x+o*f.x+l*m.x,this._storedNormal.y=n*d.y+o*f.y+l*m.y,this._storedNormal.z=n*d.z+o*f.z+l*m.z)}clone(){const e=new vC(this.mesh);return Tr.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){T.FromArrayToRef(e.direction1,0,this.direction1),T.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class WM{_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 oK="gpuUpdateParticlesPixelShader",lK=`#version 300 es +void main() {discard;} +`;j.ShadersStore[oK]=lK;const hK="gpuUpdateParticlesVertexShader",cK=`#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;uniform float directionRandomizer; +#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); +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#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 +}}`;j.ShadersStore[hK]=cK;class uK{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 lh&&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 ri("gpuUpdateParticles",this._updateEffectOptions,this._engine),new WM(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 s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.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, +directionRandomizer : f32, +#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); +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#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 +}} +`;j.ShadersStoreWGSL[dK]=fK;class pK{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 dl("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:t,defines:e.split(` +`)}),(i=this._simParamsComputeShader)==null||i.dispose(),this._simParamsComputeShader=new ze(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 WM(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){const t=new s3(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 r=0;r=n.gradient&&e<=o.gradient){const l=(e-n.gradient)/(o.gradient-n.gradient);i(n,o,l);return}}const s=t.length-1;i(t[s],t[s],1)}}class $p{constructor(e){this.particleSystem=e,this.position=T.Zero(),this.direction=T.Zero(),this.color=new Oe(0,0,0,0),this.colorStep=new Oe(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new ce(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Oe(0,0,0,0),this._currentColor2=new Oe(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=$p._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 s;this._initialSpriteCellLoop?s=ts(e*t%this.lifeTime/this.lifeTime):s=ts(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const i=W.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,W.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(W.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=$p._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 tt(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()))}}$p._Count=0;const mK="particlesPixelShader",gK=`#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 +}`;j.ShadersStore[mK]=gK;const xK="particlesVertexShader",TK=`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 +}`;j.ShadersStore[xK]=TK;class Og extends Qs{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}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 Ws(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 K),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=L.Identity(),this._inheritedVelocityOffset=new T,this.onDisposeObservable=new K,this.onStoppedObservable=new K,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Oe(0,0,0,0),this._colorDiff=new Oe(0,0,0,0),this._scaledDirection=T.Zero(),this._scaledGravity=T.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._onBeforeDrawParticlesObservable=null,this._emitFromParticle=l=>{},this.recycleParticle=l=>{const h=this._particles.pop();h!==l&&h.copyTo(l),this._stockParticles.push(h)},this._createParticle=()=>{let l;return this._stockParticles.length!==0?(l=this._stockParticles.pop(),l._reset()):l=new $p(this),this._prepareParticle(l),l},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,!i||i.getClassName()==="Scene"?(this._scene=i||We.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=L.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Ws(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new oh;let o=null;this.updateFunction=l=>{var u;let h=null;this.noiseTexture&&(h=this.noiseTexture.getSize(),(u=this.noiseTexture.getContent())==null||u.then(d=>{o=d}));const c=l===this._particles;for(let d=0;df.lifeTime){const S=f.age-_;m=(f.lifeTime-_)*m/S,f.age=f.lifeTime}const x=f.age/f.lifeTime;this._colorGradients&&this._colorGradients.length>0?Ln.GetCurrentGradient(x,this._colorGradients,(S,C,y)=>{S!==f._currentColorGradient&&(f._currentColor1.copyFrom(f._currentColor2),C.getColorToRef(f._currentColor2),f._currentColorGradient=S),Oe.LerpToRef(f._currentColor1,f._currentColor2,y,f.color)}):(f.colorStep.scaleToRef(m,this._scaledColorStep),f.color.addInPlace(this._scaledColorStep),f.color.a<0&&(f.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&Ln.GetCurrentGradient(x,this._angularSpeedGradients,(S,C,y)=>{S!==f._currentAngularSpeedGradient&&(f._currentAngularSpeed1=f._currentAngularSpeed2,f._currentAngularSpeed2=C.getFactor(),f._currentAngularSpeedGradient=S),f.angularSpeed=wn(f._currentAngularSpeed1,f._currentAngularSpeed2,y)}),f.angle+=f.angularSpeed*m;let E=m;if(this._velocityGradients&&this._velocityGradients.length>0&&Ln.GetCurrentGradient(x,this._velocityGradients,(S,C,y)=>{S!==f._currentVelocityGradient&&(f._currentVelocity1=f._currentVelocity2,f._currentVelocity2=C.getFactor(),f._currentVelocityGradient=S),E*=wn(f._currentVelocity1,f._currentVelocity2,y)}),f.direction.scaleToRef(E,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&Ln.GetCurrentGradient(x,this._limitVelocityGradients,(S,C,y)=>{S!==f._currentLimitVelocityGradient&&(f._currentLimitVelocity1=f._currentLimitVelocity2,f._currentLimitVelocity2=C.getFactor(),f._currentLimitVelocityGradient=S);const A=wn(f._currentLimitVelocity1,f._currentLimitVelocity2,y);f.direction.length()>A&&f.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&Ln.GetCurrentGradient(x,this._dragGradients,(S,C,y)=>{S!==f._currentDragGradient&&(f._currentDrag1=f._currentDrag2,f._currentDrag2=C.getFactor(),f._currentDragGradient=S);const A=wn(f._currentDrag1,f._currentDrag2,y);this._scaledDirection.scaleInPlace(1-A)}),this.isLocal&&f._localPosition?(f._localPosition.addInPlace(this._scaledDirection),T.TransformCoordinatesToRef(f._localPosition,this._emitterWorldMatrix,f.position)):f.position.addInPlace(this._scaledDirection),o&&h&&f._randomNoiseCoordinates1){const S=this._fetchR(f._randomNoiseCoordinates1.x,f._randomNoiseCoordinates1.y,h.width,h.height,o),C=this._fetchR(f._randomNoiseCoordinates1.z,f._randomNoiseCoordinates2.x,h.width,h.height,o),y=this._fetchR(f._randomNoiseCoordinates2.y,f._randomNoiseCoordinates2.z,h.width,h.height,o),A=W.Vector3[0],I=W.Vector3[1];A.copyFromFloats((2*S-1)*this.noiseStrength.x,(2*C-1)*this.noiseStrength.y,(2*y-1)*this.noiseStrength.z),A.scaleToRef(m,I),f.direction.addInPlace(I)}if(this.gravity.scaleToRef(m,this._scaledGravity),f.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&Ln.GetCurrentGradient(x,this._sizeGradients,(S,C,y)=>{S!==f._currentSizeGradient&&(f._currentSize1=f._currentSize2,f._currentSize2=C.getFactor(),f._currentSizeGradient=S),f.size=wn(f._currentSize1,f._currentSize2,y)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&Ln.GetCurrentGradient(x,this._colorRemapGradients,(S,C,y)=>{const A=wn(S.factor1,C.factor1,y),I=wn(S.factor2,C.factor2,y);f.remapData.x=A,f.remapData.y=I-A}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&Ln.GetCurrentGradient(x,this._alphaRemapGradients,(S,C,y)=>{const A=wn(S.factor1,C.factor1,y),I=wn(S.factor2,C.factor2,y);f.remapData.z=A,f.remapData.w=I-A})),this._isAnimationSheetEnabled&&f.updateCellIndex(),f._inheritParticleInfoToSubEmitters(),f.age>=f.lifeTime){this._emitFromParticle(f),f._attachedSubEmitters&&(f._attachedSubEmitters.forEach(S=>{S.particleSystem.disposeOnStop=!0,S.particleSystem.stop()}),f._attachedSubEmitters=null),this.recycleParticle(f),c&&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,s){const r=new XM(t,i,s);e.push(r),e.sort((n,o)=>n.gradiento.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.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=Yt.Color3[0];for(let i=0;i{re.LerpToRef(r.color,n.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=gs.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 _K(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 s=new HM(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort((r,n)=>r.gradientn.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,s,r){e=Math.abs(e)*.5+.5,t=Math.abs(t)*.5+.5;const n=e*i%i|0,o=t*s%s|0,l=(n+o*i)*4;return r[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 Gs(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(P.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(P.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[P.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const h=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=h,i+=1}if(!this._isBillboardBased||this.billboardMode===8||this.billboardMode===9){const h=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=h,i+=3}if(this._useRampGradients){const h=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=h,i+=4}let l;if(this._useInstancing){const h=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Gs(e,h,!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 s=0;s{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 s=0;s0&&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,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===8||this.billboardMode===9)&&(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let n=t._initialDirection;this.isLocal&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,W.Vector3[0]),n=W.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}else{let n=t.direction;this.isLocal&&(T.TransformNormalToRef(n,this._emitterWorldMatrix,W.Vector3[0]),n=W.Vector3[0]),n.x===0&&n.z===0&&(n.x=.001),this._vertexData[r++]=n.x,this._vertexData[r++]=n.y,this._vertexData[r++]=n.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(i===0?i=this._epsilon:i===1&&(i=1-this._epsilon),s===0?s=this._epsilon:s===1&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_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=L.Translation(i.x,i.y,i.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);let t;for(let i=0;i0){const r=ts(this._actualFrame/this.targetStopDuration);Ln.GetCurrentGradient(r,this._lifeTimeGradients,(n,o)=>{const l=n,h=o,c=l.getFactor(),u=h.getFactor(),d=(r-l.gradient)/(h.gradient-l.gradient);t.lifeTime=wn(c,u,d)})}else t.lifeTime=ni(this.minLifeTime,this.maxLifeTime);const s=ni(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(),T.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),s===0?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(s),!this._sizeGradients||this._sizeGradients.length===0?t.size=ni(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(ni(this.minScaleX,this.maxScaleX),ni(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;Ln.GetCurrentGradient(r,this._startSizeGradients,(n,o,l)=>{n!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=o.getFactor(),this._currentStartSizeGradient=n);const h=wn(this._currentStartSize1,this._currentStartSize2,l);t.scale.scaleInPlace(h)})}if(!this._angularSpeedGradients||this._angularSpeedGradients.length===0?t.angularSpeed=ni(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=ni(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 r=ni(0,1);Oe.LerpToRef(this.color1,this.color2,r,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 tt(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 T(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new T(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[P.PositionKind,P.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Va(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t){if(this._scene&&(vh(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===Qs.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}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Og._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==8&&this.billboardMode!==9,this._useRampGradients)),e.push(...Og._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(zI(e,this._imageProcessingConfigurationDefines),WI(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t!=null&&t.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Ws(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join(` +`);if(n.defines!==o){const l=[],h=[],c=[];this.fillUniformsAttributesAndSamplerNames(h,l,c),n.setEffect(this._engine.createEffect("particles",l,h,c,o),o)}return n}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 s=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const r=this._actualFrame/this.targetStopDuration;Ln.GetCurrentGradient(r,this._emitRateGradients,(n,o,l)=>{n!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=o.getFactor(),this._currentEmitRateGradient=n),s=wn(this._currentEmitRate1,this._currentEmitRate2,l)})}t=s*this._scaledUpdateSpeed>>0,this._newPartsExcess+=s*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 s=0;for(let r=0;r=0&&(r.invertToRef(W.Matrix[0]),i.setMatrix("invView",W.Matrix[0])),this._vertexArrayObject!==void 0?(o=this._scene)!=null&&o.forceWireframe?s.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?s.bindBuffers(this._vertexBuffers,(c=this._scene)!=null&&c.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,(h=this._scene)!=null&&h.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&Ch(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case Qs.BLENDMODE_ADD:s.setAlphaMode(1);break;case Qs.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case Qs.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case Qs.BLENDMODE_MULTIPLY:s.setAlphaMode(4);break}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?(u=this._scene)!=null&&u.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):(d=this._scene)!=null&&d.forceWireframe?s.drawElementsType(1,0,this._particles.length*10):s.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===Qs.BLENDMODE_MULTIPLYADD?t=this._render(Qs.BLENDMODE_MULTIPLY)+this._render(Qs.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 s=this._scene.particleSystems.indexOf(this);s>-1&&this._scene.particleSystems.splice(s,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var Kp;(function(a){a[a.ATTACHED=0]="ATTACHED",a[a.END=1]="END"})(Kp||(Kp={}));class hh{constructor(e){if(this.particleSystem=e,this.type=Kp.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=rs("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(!e)e=new T;else if(e instanceof T)e=e.clone();else if(e.getClassName().indexOf("Mesh")!==-1){const i=rs("BABYLON.Mesh");e=new i("",e.getScene()),e.isVisible=!1}const t=new hh(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,s=!1){throw ot("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new hh(hh._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function YM(a,e){const t=new Ix;return t.direction1=a,t.direction2=e,t}function $M(a=1,e=1){return new Rx(a,e)}function KM(a=1,e=1){return new T_(a,e)}function jM(a=1,e=new T(0,1,0),t=new T(0,1,0)){return new Px(a,e,t)}function qM(a=1,e=1,t=1,i=0){return new x_(a,e,t,i)}function QM(a=1,e=1,t=1,i=new T(0,1,0),s=new T(0,1,0)){return new Ax(a,e,t,i,s)}function ZM(a=1,e=Math.PI/4){return new yx(a,e)}class Bi extends Og{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===Kp.END){const s=i.clone();e._inheritParticleInfoToSubEmitter(s),s.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(s.particleSystem),s.particleSystem.start()}})}}createPointEmitter(e,t){const i=YM(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=$M(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=KM(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new T(0,1,0),i=new T(0,1,0)){const s=jM(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=qM(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){const n=QM(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=ZM(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new oh;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof Bi?this._subEmitters.push([new hh(e)]):e instanceof hh?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===Kp.ATTACHED){const s=i.clone();e._attachedSubEmitters.push(s),s.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(s=>{if(s._attachedSubEmitters)for(let r=s._attachedSubEmitters.length-1;r>=0;r-=1)s._attachedSubEmitters[r].dispose()})),t&&this.activeSubSystems)for(let s=this.activeSubSystems.length-1;s>=0;s-=1)this.activeSubSystems[s].dispose();if(this._subEmitters&&this._subEmitters.length){for(let s=0;s0?l.shaderOptions.defines.join(` +`):"";o=h.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,d)}const u=new Bi(n,r||e.capacity,t,o,e.isAnimationSheetEnabled);if(u.customShader=l,u._rootUrl=i,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(const d of e.subEmitters){const f=[];for(const m of d)f.push(hh.Parse(m,t,i));u.subEmitters.push(f)}}return Bi._Parse(e,u,t,i),e.textureMask&&(u.textureMask=Oe.FromArray(e.textureMask)),e.worldOffset&&(u.worldOffset=T.FromArray(e.worldOffset)),e.preventAutoStart&&(u.preventAutoStart=e.preventAutoStart),!s&&!u.preventAutoStart&&u.start(),u}serialize(e=!1){const t={};if(Bi._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 s=[];for(const r of i)s.push(r.serialize(e));t.subEmitters.push(s)}}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 x=t.emitter;e.emitterId=x.id}else{const x=t.emitter;e.emitter=x.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,Pe.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 s=t.getColorGradients();if(s){e.colorGradients=[];for(const x of s){const E={gradient:x.gradient,color1:x.color1.asArray()};x.color2?E.color2=x.color2.asArray():E.color2=x.color1.asArray(),e.colorGradients.push(E)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const x of r){const E={gradient:x.gradient,color:x.color.asArray()};e.rampGradients.push(E)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const x of n){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.colorRemapGradients.push(E)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const x of o){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.alphaRemapGradients.push(E)}}const l=t.getSizeGradients();if(l){e.sizeGradients=[];for(const x of l){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.sizeGradients.push(E)}}const h=t.getAngularSpeedGradients();if(h){e.angularSpeedGradients=[];for(const x of h){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.angularSpeedGradients.push(E)}}const c=t.getVelocityGradients();if(c){e.velocityGradients=[];for(const x of c){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.velocityGradients.push(E)}}const u=t.getDragGradients();if(u){e.dragGradients=[];for(const x of u){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.dragGradients.push(E)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const x of d){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.emitRateGradients.push(E)}}const f=t.getStartSizeGradients();if(f){e.startSizeGradients=[];for(const x of f){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.startSizeGradients.push(E)}}const m=t.getLifeTimeGradients();if(m){e.lifeTimeGradients=[];for(const x of m){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.lifeTimeGradients.push(E)}}const _=t.getLimitVelocityGradients();if(_){e.limitVelocityGradients=[];for(const x of _){const E={gradient:x.gradient,factor1:x.factor1};x.factor2!==void 0?E.factor2=x.factor2:E.factor2=x.factor1,e.limitVelocityGradients.push(E)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&this.customShader!=null){r=this.customShader;const h=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join(` +`):"",c=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,h);s[0]?s[0].effect=c:this.setCustomEffect(c,0)}const o=this.serialize(i),l=Bi.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,this.preventAutoStart||l.start(),l}}Bi.BILLBOARDMODE_Y=2;Bi.BILLBOARDMODE_ALL=7;Bi.BILLBOARDMODE_STRETCHED=8;Bi.BILLBOARDMODE_STRETCHED_LOCAL=9;hh._ParseParticleSystem=Bi.Parse;const EK="clipPlaneFragmentDeclaration2",SK=`#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 +`;j.IncludesShadersStore[EK]=SK;const vK="gpuRenderParticlesPixelShader",CK=`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 +} +`;j.ShadersStore[vK]=CK;const bK="clipPlaneVertexDeclaration2",yK=`#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 +`;j.IncludesShadersStore[bK]=yK;const AK="gpuRenderParticlesVertexShader",RK=`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=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 +}`;j.ShadersStore[AK]=RK;class nu extends Qs{static get IsSupported(){if(!We.LastCreatedEngine)return!1;const e=We.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=YM(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=$M(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=KM(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new T(0,1,0),i=new T(0,1,0)){const s=jM(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=qM(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new T(0,1,0),r=new T(0,1,0)){const n=QM(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=ZM(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new oh;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==Bi.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(Bi.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(Bi.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._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 Ws(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new K),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 HM(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 s=new XM(t,i);e.push(s),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((r,n)=>r.gradientn.gradient?1:0);const s=this;s[t]&&(s[t].dispose(),s[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,s=null,r=!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 K,this.onStoppedObservable=new K,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,!i||i.getClassName()==="Scene"?(this._scene=i||We.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)):(this._engine=i,this.defaultProjectionMatrix=L.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)),this._engine.getCaps().supportComputeShaders){if(!rs("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(rs("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!rs("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(rs("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Ws(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Ws(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 n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new oh;const l=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let h=[];for(let c=0;c0;)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),h=this._platform.createParticleBuffer(i);this._buffer0=new Gs(t,l,!1,this._attributesStrideSize),this._buffer1=new Gs(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new Gs(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 s=this._drawWrappers[e];s||(s=new Ws(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join(` +`);if(s.defines!==r){const n=[],o=[],l=[];this.fillUniformsAttributesAndSamplerNames(o,n,l),s.setEffect(this._engine.createEffect("gpuRenderParticles",n,o,l,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[P.PositionKind,"age","life","size","angle"];return e||r.push(P.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",P.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Va(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0){if(this._scene&&(vh(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==Ue.FOGMODE_NONE&&e.push("#define FOG")),t===Bi.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 Bi.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Bi.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Bi.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL");break}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...nu._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Bi.BILLBOARDMODE_STRETCHED)),e.push(...nu._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Mt.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Mt.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 s=new Float32Array(this._rawTextureWidth);for(let r=0;r{s[r]=Ne.Lerp(o.factor1,l.factor1,h)})}this[t]=gs.CreateRTexture(s,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=Yt.Color4[0];for(let i=0;i{Oe.LerpToRef(r.color1,n.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=gs.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var o,l,h,c;const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=((o=this._scene)==null?void 0:o.getViewMatrix())||L.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const u=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/u.width,this.spriteCellHeight/u.height,u.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const u=this._scene.activeCamera;s.setVector3("eyePosition",u.globalPosition)}const n=s.defines;if(this._scene&&(pa(s,this,this._scene),this.applyFog&&mc(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const u=r.clone();u.invert(),s.setMatrix("invView",u)}switch(this.useLogarithmicDepth&&this._scene&&Ch(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case Bi.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Bi.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Bi.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Bi.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4);break}return this._platform.bindDrawBuffers(this._targetIndex,s,(l=this._scene)!=null&&l.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),(h=this._scene)!=null&&h.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(c=this._scene)!=null&&c.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=W.Matrix[0],L.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 n=0;n1){const n=this._accumulatedCount|0;this._accumulatedCount-=n,this._currentActiveCount+=n}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 n=this.emitter;i=W.Matrix[0],L.TranslationToRef(n.x,n.y,n.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return!e&&!t&&(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),this.blendMode===Bi.BLENDMODE_MULTIPLYADD?r=this._render(Bi.BLENDMODE_MULTIPLY,i)+this._render(Bi.BLENDMODE_ADD,i):r=this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}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?r.shaderOptions.defines.join(` +`):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,h,void 0,void 0,void 0,this)}const o=this.serialize(i),l=nu.Parse(o,this._scene||this._engine,this._rootUrl);return l.name=e,l.customShader=r,l._customWrappers=s,t===void 0&&(t=this.emitter),this.noiseTexture&&(l.noiseTexture=this.noiseTexture.clone()),l.emitter=t,l}serialize(e=!1){const t={};return Bi._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,l;t instanceof He?o=t:(l=t,o=l.getEngine());const h=new nu(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(h._rootUrl=i,e.customShader&&o.createEffectForParticles){const c=e.customShader,u=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join(` +`):"",d=o.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,u,void 0,void 0,void 0,h);h.setCustomEffect(d,0),h.customShader=c}return e.id&&(h.id=e.id),e.activeParticleCount&&(h.activeParticleCount=e.activeParticleCount),Bi._Parse(e,h,t,i),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),!s&&!h.preventAutoStart&&h.start(),h}}xs.AddParser(ve.NAME_PARTICLESYSTEM,(a,e,t,i)=>{const s=xs.GetIndividualParser(ve.NAME_PARTICLESYSTEM);if(s&&a.particleSystems!==void 0&&a.particleSystems!==null)for(let r=0,n=a.particleSystems.length;ra.activeParticleCount?nu.Parse(a,e,t):Bi.Parse(a,e,t));He.prototype.createEffectForParticles=function(a,e=[],t=[],i="",s,r,n,o){let l=[],h=[];const c=[];return o?o.fillUniformsAttributesAndSamplerNames(h,l,c):(l=Bi._GetAttributeNamesOrOptions(),h=Bi._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:a},l,h.concat(e),c.concat(t),i,s,r,n)};q.prototype.getEmittedParticleSystems=function(){const a=[];for(let e=0;e(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 Se;t.set(this._positions32,P.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,P.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,P.ColorKind));const s=new q(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new Ie("point cloud material",this._scene),r.emissiveColor=new re(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise(n=>n(s))}_addParticle(e,t,i,s){const r=new IK(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new T(Math.random(),Math.random(),Math.random()),e.color=new Oe(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(s*4)+t*4,o=[n,n+1,n+2,n+3],l=o[0],h=o[1],c=o[2],u=o[3],d=r[l],f=r[h],m=r[c],_=r[u];return new Oe(d/255,f/255,m/255,_)}_setPointsColorOrUV(e,t,i,s,r,n,o,l){l=l??0,i&&e.updateFacetData();const c=2*e.getBoundingInfo().boundingSphere.radius;let u=e.getVerticesData(P.PositionKind);const d=e.getIndices(),f=e.getVerticesData(P.UVKind+(l?l+1:"")),m=e.getVerticesData(P.ColorKind),_=T.Zero();e.computeWorldMatrix();const x=e.getWorldMatrix();if(!x.isIdentity()){u=u.slice(0);for(let pr=0;pr1&&(Pl=1),Ml<0&&(Ml=0),Ml>1&&(Ml=1),re.HSVtoRGBToRef(Pf,Pl,Ml,Ic),xi.set(Ic.r,Ic.g,Ic.b,1)):xi=qr.set(Math.random(),Math.random(),Math.random(),1),Pn.color=new Oe(xi.x,xi.y,xi.z,xi.w),this._colors.push(xi.x,xi.y,xi.z,xi.w))}}_colorFromTexture(e,t,i){if(e.material===null){U.Warn(e.name+"has no material."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const r=e.material.getActiveTextures();if(r.length===0){U.Warn(e.name+"has no usable texture."),t._groupImageData=null,this._setPointsColorOrUV(e,t,i,!0,!1);return}const n=e.clone();n.setEnabled(!1),this._promises.push(new Promise(o=>{Kt.WhenAllReady(r,()=>{let l=t._textureNb;l<0&&(l=0),l>r.length-1&&(l=r.length-1);const h=()=>{t._groupImgWidth=r[l].getSize().width,t._groupImgHeight=r[l].getSize().height,this._setPointsColorOrUV(n,t,i,!0,!0,void 0,void 0,r[l].coordinatesIndex),n.dispose(),o()};t._groupImageData=null;const c=r[l].readPixels();c?c.then(u=>{t._groupImageData=u,h()}):h()})}))}_calculateDensity(e,t,i){let s,r,n,o,l,h,c,u,d,f,m,_;const x=T.Zero(),E=T.Zero(),S=T.Zero(),C=T.Zero(),y=T.Zero(),A=T.Zero();let I;const R=[];let N=0;const k=i.length/3;for(let ne=0;ne0;ne--){const de=R[ne];if(de===0)B[ne]=0;else{const fe=(de-R[ne-1])/de*Q,Ee=Math.floor(fe),De=fe-Ee,Te=+(Math.random()3)&&(n=en.Random);const o=e.getVerticesData(P.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const h=new yE(this._groupCounter,null);switch(h._groupDensity=this._calculateDensity(t,o,l),n===en.Color?h._textureNb=s||0:s=s||new Oe(1,1,1,1),n){case en.Color:this._colorFromTexture(e,h,!1);break;case en.UV:this._setPointsColorOrUV(e,h,!1,!1,!1);break;case en.Random:this._setPointsColorOrUV(e,h,!1);break;case en.Stated:this._setPointsColorOrUV(e,h,!1,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||en.Random;(isNaN(n)||n<0||n>3)&&(n=en.Random);const o=e.getVerticesData(P.PositionKind),l=e.getIndices();this._groups.push(this._groupCounter);const h=new yE(this._groupCounter,null);switch(h._groupDensity=this._calculateDensity(t,o,l),n===en.Color?h._textureNb=s||0:s=s||new Oe(1,1,1,1),n){case en.Color:this._colorFromTexture(e,h,!0);break;case en.UV:this._setPointsColorOrUV(e,h,!0,!1,!1);break;case en.Random:this._setPointsColorOrUV(e,h,!0);break;case en.Stated:this._setPointsColorOrUV(e,h,!0,void 0,void 0,s,r);break}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){var C,y;if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=W.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,l=this._uvs32,h=W.Vector3,c=h[5].copyFromFloats(1,0,0),u=h[6].copyFromFloats(0,1,0),d=h[7].copyFromFloats(0,0,1),f=h[8].setAll(Number.MAX_VALUE),m=h[9].setAll(-Number.MAX_VALUE);L.IdentityToRef(s);let _=0;if((C=this.mesh)!=null&&C.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(e!=0||t!=this.nbParticles-1)){const A=(y=this.mesh)==null?void 0:y.getBoundingInfo();A&&(f.copyFrom(A.minimum),m.copyFrom(A.maximum))}_=0;let x=0,E=0,S=0;for(let A=e;A<=t;A++){const I=this.particles[A];_=I.idx,x=3*_,E=4*_,S=2*_,this.updateParticle(I);const R=I._rotationMatrix,N=I.position,k=I._globalPosition;if(this._computeParticleRotation&&I.getRotationMatrix(s),I.parentId!==null){const ie=this.particles[I.parentId],he=ie._rotationMatrix,ke=ie._globalPosition,Ye=N.x*he[1]+N.y*he[4]+N.z*he[7],et=N.x*he[0]+N.y*he[3]+N.z*he[6],ye=N.x*he[2]+N.y*he[5]+N.z*he[8];if(k.x=ke.x+et,k.y=ke.y+Ye,k.z=ke.z+ye,this._computeParticleRotation){const Ae=s.m;R[0]=Ae[0]*he[0]+Ae[1]*he[3]+Ae[2]*he[6],R[1]=Ae[0]*he[1]+Ae[1]*he[4]+Ae[2]*he[7],R[2]=Ae[0]*he[2]+Ae[1]*he[5]+Ae[2]*he[8],R[3]=Ae[4]*he[0]+Ae[5]*he[3]+Ae[6]*he[6],R[4]=Ae[4]*he[1]+Ae[5]*he[4]+Ae[6]*he[7],R[5]=Ae[4]*he[2]+Ae[5]*he[5]+Ae[6]*he[8],R[6]=Ae[8]*he[0]+Ae[9]*he[3]+Ae[10]*he[6],R[7]=Ae[8]*he[1]+Ae[9]*he[4]+Ae[10]*he[7],R[8]=Ae[8]*he[2]+Ae[9]*he[5]+Ae[10]*he[8]}}else if(k.x=0,k.y=0,k.z=0,this._computeParticleRotation){const ie=s.m;R[0]=ie[0],R[1]=ie[1],R[2]=ie[2],R[3]=ie[4],R[4]=ie[5],R[5]=ie[6],R[6]=ie[8],R[7]=ie[9],R[8]=ie[10]}const Q=h[11];I.translateFromPivot?Q.setAll(0):Q.copyFrom(I.pivot);const ne=h[0];ne.copyFrom(I.position);const de=ne.x-I.pivot.x,ge=ne.y-I.pivot.y,fe=ne.z-I.pivot.z;let Ee=de*R[0]+ge*R[3]+fe*R[6],De=de*R[1]+ge*R[4]+fe*R[7],Te=de*R[2]+ge*R[5]+fe*R[8];Ee+=Q.x,De+=Q.y,Te+=Q.z;const ue=o[x]=k.x+c.x*Ee+u.x*De+d.x*Te,oe=o[x+1]=k.y+c.y*Ee+u.y*De+d.y*Te,F=o[x+2]=k.z+c.z*Ee+u.z*De+d.z*Te;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(ue,oe,F),m.maximizeInPlaceFromFloats(ue,oe,F)),this._computeParticleColor&&I.color){const ie=I.color,he=this._colors32;he[E]=ie.r,he[E+1]=ie.g,he[E+2]=ie.b,he[E+3]=ie.a}if(this._computeParticleTexture&&I.uv){const ie=I.uv,he=this._uvs32;he[S]=ie.x,he[S+1]=ie.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(P.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(P.UVKind,l,!1,!1),r.updateVerticesData(P.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(f,m,r._worldMatrix):r.buildBoundingInfo(f,m,r._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 T(-t,-t,-t),new T(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){}}Object.defineProperty(Ft.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(a){this._physicsImpostor!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0});Ft.prototype.getPhysicsImpostor=function(){return this.physicsImpostor};Ft.prototype.applyImpulse=function(a,e){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(a,e),this):this};Ft.prototype.setPhysicsLinkWith=function(a,e,t,i){return!this.physicsImpostor||!a.physicsImpostor?this:(this.physicsImpostor.createJoint(a.physicsImpostor,Fi.HingeJoint,{mainPivot:e,connectedPivot:t,nativeParams:i}),this)};class CC{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ot("")}constructor(e,t=CC.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new T(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}_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,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new Tx;return this._physicsPlugin.raycast(e,t,s,i),s}}var sR;(function(a){a[a.FREE=0]="FREE",a[a.LIMITED=1]="LIMITED",a[a.LOCKED=2]="LOCKED"})(sR||(sR={}));var rR;(function(a){a[a.LINEAR_X=0]="LINEAR_X",a[a.LINEAR_Y=1]="LINEAR_Y",a[a.LINEAR_Z=2]="LINEAR_Z",a[a.ANGULAR_X=3]="ANGULAR_X",a[a.ANGULAR_Y=4]="ANGULAR_Y",a[a.ANGULAR_Z=5]="ANGULAR_Z",a[a.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"})(rR||(rR={}));var nR;(function(a){a[a.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",a[a.DISTANCE=2]="DISTANCE",a[a.HINGE=3]="HINGE",a[a.SLIDER=4]="SLIDER",a[a.LOCK=5]="LOCK",a[a.PRISMATIC=6]="PRISMATIC",a[a.SIX_DOF=7]="SIX_DOF"})(nR||(nR={}));var aR;(function(a){a[a.SPHERE=0]="SPHERE",a[a.CAPSULE=1]="CAPSULE",a[a.CYLINDER=2]="CYLINDER",a[a.BOX=3]="BOX",a[a.CONVEX_HULL=4]="CONVEX_HULL",a[a.CONTAINER=5]="CONTAINER",a[a.MESH=6]="MESH",a[a.HEIGHTFIELD=7]="HEIGHTFIELD"})(aR||(aR={}));var oR;(function(a){a[a.NONE=0]="NONE",a[a.VELOCITY=1]="VELOCITY",a[a.POSITION=2]="POSITION"})(oR||(oR={}));var lR;(function(a){a.COLLISION_STARTED="COLLISION_STARTED",a.COLLISION_CONTINUED="COLLISION_CONTINUED",a.COLLISION_FINISHED="COLLISION_FINISHED",a.TRIGGER_ENTERED="TRIGGER_ENTERED",a.TRIGGER_EXITED="TRIGGER_EXITED"})(lR||(lR={}));var hR;(function(a){a[a.STATIC=0]="STATIC",a[a.ANIMATED=1]="ANIMATED",a[a.DYNAMIC=2]="DYNAMIC"})(hR||(hR={}));var cR;(function(a){a[a.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",a[a.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",a[a.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"})(cR||(cR={}));var uR;(function(a){a[a.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",a[a.MINIMUM=1]="MINIMUM",a[a.MAXIMUM=2]="MAXIMUM",a[a.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",a[a.MULTIPLY=4]="MULTIPLY"})(uR||(uR={}));Ue.prototype.getPhysicsEngine=function(){return this._physicsEngine};Ue.prototype.enablePhysics=function(a=null,e){if(this._physicsEngine)return!0;let t=this._getComponent(ve.NAME_PHYSICSENGINE);t||(t=new MK(this),this._addComponent(t));try{if(!e||(e==null?void 0:e.getPluginVersion())===1)this._physicsEngine=new iM(a,e);else if((e==null?void 0:e.getPluginVersion())===2)this._physicsEngine=new CC(a,e);else throw new Error("Unsupported Physics plugin version.");return this._physicsTimeAccumulator=0,!0}catch(i){return U.Error(i.message),!1}};Ue.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)};Ue.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==void 0};Ue.prototype.deleteCompoundImpostor=function(a){const e=a.parts[0].mesh;e.physicsImpostor&&(e.physicsImpostor.dispose(),e.physicsImpostor=null)};Ue.prototype._advancePhysicsEngineStep=function(a){if(this._physicsEngine){const e=this._physicsEngine.getSubTimeStep();if(e>0)for(this._physicsTimeAccumulator+=a;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(a/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class MK{constructor(e){this.name=ve.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new K,this.scene.onAfterPhysicsObservable=new K,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(ut.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(a){this._physicsBody!==a&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=a,a&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0});ut.prototype.getPhysicsBody=function(){return this.physicsBody};ut.prototype.applyImpulse=function(a,e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(a,e),this};ut.prototype.applyAngularImpulse=function(a){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(a),this};T.Zero();var dR;(function(a){a[a.Constant=0]="Constant",a[a.Linear=1]="Linear"})(dR||(dR={}));var fR;(function(a){a[a.Center=0]="Center",a[a.Perpendicular=1]="Perpendicular"})(fR||(fR={}));const OK="blackAndWhitePixelShader",DK=`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);}`;j.ShadersStore[OK]=DK;class Mx extends je{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add(o=>{o.setFloat("degree",this.degree)})}static _Parse(e,t,i,s){return Pe.Parse(()=>new Mx(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}v([O()],Mx.prototype,"degree",void 0);H("BABYLON.BlackAndWhitePostProcess",Mx);class qt{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!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=r.attachPostProcess(o);this._indicesForCamera[n].push(l)}),this._cameras[n]||(this._cameras[n]=r)}}_detachCameras(e){const t=Z.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(o)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=Z.MakeArray(e||this._cameras);if(t)for(let i=0;i{s.detachPostProcess(n)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const NK="extractHighlightsPixelShader",wK=`#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;}`;j.ShadersStore[NK]=wK;class bC extends je{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,l),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(h=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&h.setTextureFromPostProcess("textureSampler",this._inputPostProcess),h.setFloat("threshold",Math.pow(this.threshold,ip)),h.setFloat("exposure",this._exposure)})}}v([O()],bC.prototype,"threshold",void 0);H("BABYLON.ExtractHighlightsPostProcess",bC);const FK="bloomMergePixelShader",LK=`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); } +`;j.ShadersStore[FK]=LK;class yC extends je{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,l,h,c=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,l,h,null,c,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("bloomBlur",i),d.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}v([O()],yC.prototype,"weight",void 0);H("BABYLON.BloomMergePostProcess",yC);class pR extends qt{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,s,r=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new bC("highlights",1,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Hs("horizontal blur",new ce(1,0),10,t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Hs("vertical blur",new ce(0,1),10,t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new yC("bloomMerge",this._downscale,this._blurY,i,t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{u.setFloat("chromatic_aberration",this.aberrationAmount),u.setFloat("screen_width",t),u.setFloat("screen_height",i),u.setFloat("radialIntensity",this.radialIntensity),u.setFloat2("direction",this.direction.x,this.direction.y),u.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,s){return Pe.Parse(()=>new Xo(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}v([O()],Xo.prototype,"aberrationAmount",void 0);v([O()],Xo.prototype,"radialIntensity",void 0);v([O()],Xo.prototype,"direction",void 0);v([O()],Xo.prototype,"centerPosition",void 0);v([O()],Xo.prototype,"screenWidth",void 0);v([O()],Xo.prototype,"screenHeight",void 0);H("BABYLON.ChromaticAberrationPostProcess",Xo);const VK="circleOfConfusionPixelShader",kK=`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);} +`;j.ShadersStore[VK]=kK;class Ef extends je{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,l=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,l,void 0,null,h),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(c=>{if(!this._depthTexture){U.Warn("No depth texture set on CircleOfConfusionPostProcess");return}c.setTexture("depthSampler",this._depthTexture);const d=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);c.setFloat("focusDistance",this.focusDistance),c.setFloat("cocPrecalculation",d);const f=this._depthTexture.activeCamera;c.setFloat2("cameraMinMaxZ",f.minZ,f.maxZ-f.minZ)})}set depthTexture(e){this._depthTexture=e}}v([O()],Ef.prototype,"lensSize",void 0);v([O()],Ef.prototype,"fStop",void 0);v([O()],Ef.prototype,"focusDistance",void 0);v([O()],Ef.prototype,"focalLength",void 0);H("BABYLON.CircleOfConfusionPostProcess",Ef);const GK="colorCorrectionPixelShader",zK=`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);}`;j.ShadersStore[GK]=zK;class Ox extends je{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const l=(s==null?void 0:s.getScene())||null;this._colorTableTexture=new X(t,l,!0,!1,X.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=X.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=X.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=h=>{h.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Pe.Parse(()=>new Ox(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}v([O()],Ox.prototype,"colorTableUrl",void 0);H("BABYLON.ColorCorrectionPostProcess",Ox);const WK="convolutionPixelShader",HK=`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);}`;j.ShadersStore[WK]=HK;class Yo extends je{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,l=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,l),this.kernel=t,this.onApply=h=>{h.setFloat2("screenSize",this.width,this.height),h.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return Pe.Parse(()=>new Yo(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,s)}}Yo.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1];Yo.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0];Yo.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1];Yo.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0];Yo.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2];Yo.GaussianKernel=[0,1,0,1,1,1,0,1,0];v([O()],Yo.prototype,"kernel",void 0);H("BABYLON.ConvolutionPostProcess",Yo);class Dg extends Hs{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,l=null,h=X.BILINEAR_SAMPLINGMODE,c,u,d=0,f=!1,m=5){super(e,i,s,r,n,h=2,c,u,d,`#define DOF 1 +`,f,m),this.direction=i,this.externalTextureSamplerBinding=!!l,this.onApplyObservable.add(_=>{l!=null&&_.setTextureFromPostProcess("textureSampler",l),_.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)})}}v([O()],Dg.prototype,"direction",void 0);H("BABYLON.DepthOfFieldBlurPostProcess",Dg);const XK="depthOfFieldMergePixelShader",YK=`#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 +} +`;j.ShadersStore[XK]=YK;class $K extends je{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,l,h,c=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,l,h,null,c,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(d=>{d.setTextureFromPostProcess("textureSampler",t),d.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach((f,m)=>{d.setTextureFromPostProcessOutput("blurStep"+(s.length-m-1),f)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+` +`),super.updateEffect(e,t,i,s,r,n)}}var _u;(function(a){a[a.Low=0]="Low",a[a.Medium=1]="Medium",a[a.High=2]="High"})(_u||(_u={}));class _R extends qt{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=_u.Low,s=0,r=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new Ef("circleOfConfusion",t,1,null,X.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case _u.High:{l=3,h=51;break}case _u.Medium:{l=2,h=31;break}default:{h=15,l=1;break}}const c=h/Math.pow(2,l-1);let u=1;for(let d=0;dnew AC(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}H("BABYLON.DisplayPassPostProcess",AC);const qK="filterPixelShader",QK=`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);}`;j.ShadersStore[qK]=QK;class Dx extends je{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=l=>{l.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Pe.Parse(()=>new Dx(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}v([iv()],Dx.prototype,"kernelMatrix",void 0);H("BABYLON.FilterPostProcess",Dx);const ZK="fxaaPixelShader",JK=`#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{const c=this.texelSize;h.setFloat2("texelSize",c.x,c.y)})}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?`#define MALI 1 +`:null}static _Parse(e,t,i,s){return Pe.Parse(()=>new Sf(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}H("BABYLON.FxaaPostProcess",Sf);const ij="grainPixelShader",sj=`#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);}`;j.ShadersStore[ij]=sj;class vf extends je{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,l),this.intensity=30,this.animated=!1,this.onApplyObservable.add(h=>{h.setFloat("intensity",this.intensity),h.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,s){return Pe.Parse(()=>new vf(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}v([O()],vf.prototype,"intensity",void 0);v([O()],vf.prototype,"animated",void 0);H("BABYLON.GrainPostProcess",vf);const rj="highlightsPixelShader",nj=`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); }`;j.ShadersStore[rj]=nj;const aj="imageProcessingPixelShader",oj=`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;}`;j.ShadersStore[aj]=oj;class RC extends je{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 s=this.getEngine(),r=this.getCamera();if(r)i=r.getScene();else if(s&&s.scenes){const n=s.scenes;i=n[n.length-1]}else i=We.LastCreatedScene;i?this._imageProcessingConfiguration=i.imageProcessingConfiguration:this._imageProcessingConfiguration=new Mt}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,s,r,n,o=0,l){super(e,"imageProcessing",[],[],t,i,s,r,n,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=h=>{this.imageProcessingConfiguration.bind(h,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const s in this._defines){const r=this._defines[s];switch(typeof r){case"number":case"string":e+=`#define ${s} ${r}; +`;break;default:r&&(e+=`#define ${s}; +`);break}}const t=["textureSampler"],i=["scale"];Mt&&(Mt.PrepareSamplers(t,this._defines),Mt.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([O()],RC.prototype,"_fromLinearSpace",void 0);const lj="mrtFragmentDeclaration",hj=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;j.IncludesShadersStore[lj]=hj;const cj="geometryPixelShader",uj=`#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[RENDER_TARGET_COUNT] +#include +#include +#include +void main() { +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef ENCODE_NORMAL +normalOutput=normalOutput*0.5+0.5; +#endif +#ifdef PREPASS +#ifdef PREPASS_DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef PREPASS_NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#else +gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`;j.ShadersStore[cj]=uj;const dj="geometryVertexDeclaration",fj="uniform mat4 viewProjection;uniform mat4 view;";j.IncludesShadersStore[dj]=fj;const pj="geometryUboDeclaration",_j=`#include +`;j.IncludesShadersStore[pj]=_j;const mj="geometryVertexShader",gj=`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 +} +`;j.ShadersStore[mj]=gj;const JM=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Va(JM);class ui{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===ui.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===ui.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===ui.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===ui.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===ui.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 ui.POSITION_TEXTURE_TYPE:return this._positionIndex;case ui.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case ui.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case ui.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case ui.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}constructor(e,t=1,i=15,s){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 Oe(0,0,0,0),this._clearDepthColor=new Oe(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._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},ui._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[P.PositionKind,P.NormalKind],n=e.getMesh();if(i){let f=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),f=!0),i.bumpTexture&&Ce.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),f=!0),this._enableReflectivity){let m=!1;i.getClassName()==="PBRMetallicRoughnessMaterial"?(i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),f=!0,m=!0),i.metallic!=null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),m=!0),i.roughness!=null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),m=!0),m&&(i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),f=!0),i.baseColor&&s.push("#define ALBEDOCOLOR"))):i.getClassName()==="PBRSpecularGlossinessMaterial"?(i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),f=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&s.push("#define GLOSSINESS")):i.getClassName()==="PBRMaterial"?(i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),f=!0,m=!0),i.metallic!=null&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),m=!0),i.roughness!=null&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),m=!0),m?(i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),f=!0),i.albedoColor&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0):i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&s.push("#define GLOSSINESS"))):i.getClassName()==="StandardMaterial"&&(i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),f=!0),i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}f&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),this._depthIndex!==-1&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),this._normalIndex!==-1&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(n)===-1&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let l=0;o&&(l=o.numMaxInfluencers||o.numInfluencers,l>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+l),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),o_(r,n,l))),t&&(s.push("#define INSTANCES"),bh(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),vh(i,this._scene,s);const h=this._scene.getEngine(),c=e._getDrawWrapper(void 0,!0),u=c.defines,d=s.join(` +`);return u!==d&&c.setEffect(h.createEffect("geometry",{attributes:r,uniformsNames:JM,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}},h),d),c.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[ui.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[ui.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[ui.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[ui.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[ui.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[];for(const x of s)x?(o.push(x.textureType),l.push(x.textureFormat)):(o.push(r),l.push(5));if(this._normalsAreUnsigned=o[ui.NORMAL_TEXTURE_TYPE]===11||o[ui.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new jh("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=X.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=X.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const h=[!0],c=[!1],u=[!0];for(let x=1;x{x.bindAttachments(this.useSpecificClearForDepthTexture?f:d),x.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(x.bindAttachments(m),x.clear(this._clearDepthColor,!0,!0,!0)),x.bindAttachments(d)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){const x=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(x)}});const _=x=>{const E=x.getRenderingMesh(),S=x.getEffectiveMesh(),C=this._scene,y=C.getEngine(),A=x.getMaterial();if(!A)return;if(S._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[S.uniqueId]&&(this._previousTransformationMatrices[S.uniqueId]={world:L.Identity(),viewProjection:C.getTransformMatrix()},E.skeleton)){const k=E.skeleton.getTransformMatrices(E);this._previousBonesTransformationMatrices[E.uniqueId]=this._copyBonesTransformationMatrices(k,new Float32Array(k.length))}const I=E._getInstancesRenderList(x._id,!!x.getReplacementMesh());if(I.mustReturn)return;const R=y.getCaps().instancedArrays&&(I.visibleInstances[x._id]!==null||E.hasThinInstances),N=S.getWorldMatrix();if(this.isReady(x,R)){const k=x._getDrawWrapper();if(!k)return;const B=k.effect;y.enableEffect(k),R||E._bind(x,B,A.fillMode),this._useUbo?(Gg(B,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(B.setMatrix("viewProjection",C.getTransformMatrix()),B.setMatrix("view",C.getViewMatrix()));let Q;const ne=E._instanceDataStorage;if(!ne.isFrozen&&(A.backFaceCulling||E.overrideMaterialSideOrientation!==null)){const de=S._getWorldMatrixDeterminant();Q=E.overrideMaterialSideOrientation,Q===null&&(Q=A.sideOrientation),de<0&&(Q=Q===pe.ClockWiseSideOrientation?pe.CounterClockWiseSideOrientation:pe.ClockWiseSideOrientation)}else Q=ne.sideOrientation;if(A._preBind(k,Q),A.needAlphaTesting()){const de=A.getAlphaTestTexture();de&&(B.setTexture("diffuseSampler",de),B.setMatrix("diffuseMatrix",de.getTextureMatrix()))}if(A.bumpTexture&&C.getEngine().getCaps().standardDerivatives&&Ce.BumpTextureEnabled&&(B.setFloat3("vBumpInfos",A.bumpTexture.coordinatesIndex,1/A.bumpTexture.level,A.parallaxScaleBias),B.setMatrix("bumpMatrix",A.bumpTexture.getTextureMatrix()),B.setTexture("bumpSampler",A.bumpTexture),B.setFloat2("vTangentSpaceParams",A.invertNormalMapX?-1:1,A.invertNormalMapY?-1:1)),this._enableReflectivity&&(A.getClassName()==="PBRMetallicRoughnessMaterial"?(A.metallicRoughnessTexture!==null&&(B.setTexture("reflectivitySampler",A.metallicRoughnessTexture),B.setMatrix("reflectivityMatrix",A.metallicRoughnessTexture.getTextureMatrix())),A.metallic!==null&&B.setFloat("metallic",A.metallic),A.roughness!==null&&B.setFloat("glossiness",1-A.roughness),A.baseTexture!==null&&(B.setTexture("albedoSampler",A.baseTexture),B.setMatrix("albedoMatrix",A.baseTexture.getTextureMatrix())),A.baseColor!==null&&B.setColor3("albedoColor",A.baseColor)):A.getClassName()==="PBRSpecularGlossinessMaterial"?(A.specularGlossinessTexture!==null?(B.setTexture("reflectivitySampler",A.specularGlossinessTexture),B.setMatrix("reflectivityMatrix",A.specularGlossinessTexture.getTextureMatrix())):A.specularColor!==null&&B.setColor3("reflectivityColor",A.specularColor),A.glossiness!==null&&B.setFloat("glossiness",A.glossiness)):A.getClassName()==="PBRMaterial"?(A.metallicTexture!==null&&(B.setTexture("reflectivitySampler",A.metallicTexture),B.setMatrix("reflectivityMatrix",A.metallicTexture.getTextureMatrix())),A.metallic!==null&&B.setFloat("metallic",A.metallic),A.roughness!==null&&B.setFloat("glossiness",1-A.roughness),A.roughness!==null||A.metallic!==null||A.metallicTexture!==null?(A.albedoTexture!==null&&(B.setTexture("albedoSampler",A.albedoTexture),B.setMatrix("albedoMatrix",A.albedoTexture.getTextureMatrix())),A.albedoColor!==null&&B.setColor3("albedoColor",A.albedoColor)):(A.reflectivityTexture!==null?(B.setTexture("reflectivitySampler",A.reflectivityTexture),B.setMatrix("reflectivityMatrix",A.reflectivityTexture.getTextureMatrix())):A.reflectivityColor!==null&&B.setColor3("reflectivityColor",A.reflectivityColor),A.microSurface!==null&&B.setFloat("glossiness",A.microSurface))):A.getClassName()==="StandardMaterial"&&(A.specularTexture!==null&&(B.setTexture("reflectivitySampler",A.specularTexture),B.setMatrix("reflectivityMatrix",A.specularTexture.getTextureMatrix())),A.specularColor!==null&&B.setColor3("reflectivityColor",A.specularColor))),pa(B,A,this._scene),E.useBones&&E.computeBonesUsingShaders&&E.skeleton){const de=E.skeleton;if(de.isUsingTextureForMatrices&&B.getUniformIndex("boneTextureWidth")>-1){const ge=de.getTransformMatrixTexture(E);B.setTexture("boneSampler",ge),B.setFloat("boneTextureWidth",4*(de.bones.length+1))}else B.setMatrices("mBones",E.skeleton.getTransformMatrices(E));this._enableVelocity&&B.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[E.uniqueId])}Al(E,B),E.morphTargetManager&&E.morphTargetManager.isUsingTextureForTargets&&E.morphTargetManager._bind(B),this._enableVelocity&&(B.setMatrix("previousWorld",this._previousTransformationMatrices[S.uniqueId].world),B.setMatrix("previousViewProjection",this._previousTransformationMatrices[S.uniqueId].viewProjection)),R&&E.hasThinInstances&&B.setMatrix("world",N),E._processRendering(S,x,B,A.fillMode,I,R,(de,ge)=>{de||B.setMatrix("world",ge)})}this._enableVelocity&&(this._previousTransformationMatrices[S.uniqueId].world=N.clone(),this._previousTransformationMatrices[S.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),E.skeleton&&this._copyBonesTransformationMatrices(E.skeleton.getTransformMatrices(E),this._previousBonesTransformationMatrices[S.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(x,E,S)=>{if((S||E===0)&&x.subMeshes)for(let C=0;C{let y;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(C.length){for(e.setColorWrite(!1),y=0;y{throw ot("GeometryBufferRendererSceneComponent")};class xj{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Ue.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(a){a&&a.isSupported&&(this._geometryBufferRenderer=a)},enumerable:!0,configurable:!0});Ue.prototype.enableGeometryBufferRenderer=function(a=1,e=15,t){return this._geometryBufferRenderer?this._geometryBufferRenderer:(this._geometryBufferRenderer=new ui(this,a,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null),this._geometryBufferRenderer)};Ue.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class Tj{constructor(e){this.name=ve.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}ui._SceneComponentInitialization=a=>{let e=a._getComponent(ve.NAME_GEOMETRYBUFFERRENDERER);e||(e=new Tj(a),a._addComponent(e))};const Ej="motionBlurPixelShader",Sj=`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 +} +`;j.ShadersStore[Ej]=Sj;class vc extends je{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,s,r,n,o,l=0,h=!1,c=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,`#define GEOMETRY_SUPPORTED +#define SAMPLES 64.0 +#define OBJECT_BASED`,l,void 0,null,h),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=c,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new xj)),this._applyMode()}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 U.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=L.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 ce(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(ui.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=W.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 ce(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const i=this._geometryBufferRenderer.getTextureIndex(ui.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,s){return Pe.Parse(()=>new vc(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,s)}}v([O()],vc.prototype,"motionStrength",void 0);v([O()],vc.prototype,"motionBlurSamples",null);v([O()],vc.prototype,"isObjectBased",null);H("BABYLON.MotionBlurPostProcess",vc);const vj="refractionPixelShader",Cj="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);}";j.ShadersStore[vj]=Cj;class Cc extends je{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,s,r,n,o,l,h,c){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,l,h,c),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add(u=>{this._refTexture=this._refTexture||new X(t,u.getScene())}),this.onApplyObservable.add(u=>{u.setColor3("baseColor",this.color),u.setFloat("depth",this.depth),u.setFloat("colorLevel",this.colorLevel),u.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return Pe.Parse(()=>new Cc(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,s)}}v([O()],Cc.prototype,"color",void 0);v([O()],Cc.prototype,"depth",void 0);v([O()],Cc.prototype,"colorLevel",void 0);v([O()],Cc.prototype,"refractionTextureUrl",void 0);H("BABYLON.RefractionPostProcess",Cc);const bj="sharpenPixelShader",yj=`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.);}`;j.ShadersStore[bj]=yj;class Cf extends je{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,l=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,l),this.colorAmount=1,this.edgeAmount=.3,this.onApply=h=>{h.setFloat2("screenSize",this.width,this.height),h.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return Pe.Parse(()=>new Cf(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}v([O()],Cf.prototype,"colorAmount",void 0);v([O()],Cf.prototype,"edgeAmount",void 0);H("BABYLON.SharpenPostProcess",Cf);class bc{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(Z.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Z.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Z.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){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 s of i)s.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}v([O()],bc.prototype,"_name",void 0);class Aj{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 s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._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(Ue.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let a=this._getComponent(ve.NAME_POSTPROCESSRENDERPIPELINEMANAGER);a||(a=new Rj(this),this._addComponent(a)),this._postProcessRenderPipelineManager=new Aj}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class Rj{constructor(e){this.name=ve.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ve.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 Cr extends bc{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 pR(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 _R(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 pR(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new Xo("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,X.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new qt(o,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new vf("Grain",1,null,X.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new qt(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?Z.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 RC("imageProcessing",1,null,X.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new qt(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 Sf("fxaa",1,null,X.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new qt(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&&U.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 Cr(e._name,e._name._hdr,t),e,t,i)}}v([O()],Cr.prototype,"sharpenEnabled",null);v([O()],Cr.prototype,"bloomKernel",null);v([O()],Cr.prototype,"_bloomWeight",void 0);v([O()],Cr.prototype,"_bloomThreshold",void 0);v([O()],Cr.prototype,"_hdr",void 0);v([O()],Cr.prototype,"bloomWeight",null);v([O()],Cr.prototype,"bloomThreshold",null);v([O()],Cr.prototype,"bloomScale",null);v([O()],Cr.prototype,"bloomEnabled",null);v([O()],Cr.prototype,"depthOfFieldEnabled",null);v([O()],Cr.prototype,"depthOfFieldBlurLevel",null);v([O()],Cr.prototype,"fxaaEnabled",null);v([O()],Cr.prototype,"samples",null);v([O()],Cr.prototype,"imageProcessingEnabled",null);v([O()],Cr.prototype,"glowLayerEnabled",null);v([O()],Cr.prototype,"chromaticAberrationEnabled",null);v([O()],Cr.prototype,"grainEnabled",null);H("BABYLON.DefaultRenderingPipeline",Cr);const Ij="lensHighlightsPixelShader",Pj=`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;}`;j.ShadersStore[Ij]=Pj;const Mj="depthOfFieldPixelShader",Oj=`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;}} +`;j.ShadersStore[Mj]=Oj;class Dj{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const Nj="ssao2PixelShader",wj=`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=depth/abs(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; ithis._originalColorPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const h=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,c=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;l.setFloat("outSize",h>0?h:c),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}_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,s=1-e*.85,r=Math.sqrt(1-s*s);return new T(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(r.setArray3("sampleSphere",this._sampleSphere),r.setFloat("randTextureTiles",32),r.setFloat("samplesFactor",1/this.samples),r.setFloat("totalStrength",this.totalStrength),r.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),r.setFloat("radius",this.radius),r.setFloat("maxZ",this.maxZ),r.setFloat("minZAspect",this.minZAspect),r.setFloat("base",this.base),r.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===Ve.PERSPECTIVE_CAMERA)r.setMatrix3x3("depthProjection",Xs.PERSPECTIVE_DEPTH_PROJECTION),r.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),r.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const n=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,l=this._scene.activeCamera.orthoLeft??-n,h=this._scene.activeCamera.orthoRight??n,c=this._scene.activeCamera.orthoBottom??-o,u=this._scene.activeCamera.orthoTop??o;r.setMatrix3x3("depthProjection",Xs.ORTHO_DEPTH_PROJECTION),r.setFloat("xViewport",(h-l)*.5),r.setFloat("yViewport",(u-c)*.5)}r.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(r.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),r.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(r.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),r.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),r.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new Dj)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new je("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=i=>{const s=this._scene.activeCamera.viewport;i.setVector4("viewport",W.Vector4[0].copyFromFloats(s.x,s.y,s.width,s.height)),i.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const t=new Uint8Array(65536),i=ce.Zero();for(let r=0;rnew Xs(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}Xs.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1];Xs.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1];v([O()],Xs.prototype,"totalStrength",void 0);v([O()],Xs.prototype,"maxZ",void 0);v([O()],Xs.prototype,"minZAspect",void 0);v([O("epsilon")],Xs.prototype,"_epsilon",void 0);v([O("samples")],Xs.prototype,"_samples",void 0);v([O("textureSamples")],Xs.prototype,"_textureSamples",void 0);v([O()],Xs.prototype,"_forceGeometryBuffer",void 0);v([O()],Xs.prototype,"_ratio",void 0);v([O()],Xs.prototype,"_textureType",void 0);v([O()],Xs.prototype,"radius",void 0);v([O()],Xs.prototype,"base",void 0);v([O("bypassBlur")],Xs.prototype,"_bypassBlur",void 0);v([O("expensiveBlur")],Xs.prototype,"_expensiveBlur",void 0);v([O()],Xs.prototype,"bilateralSamples",void 0);v([O()],Xs.prototype,"bilateralSoften",void 0);v([O()],Xs.prototype,"bilateralTolerance",void 0);H("BABYLON.SSAO2RenderingPipeline",Xs);const Bj="ssaoPixelShader",Uj=`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 qt(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new qt(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_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],s=1/16;this._ssaoPostProcess=new je("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,`#define SAMPLES 16 +#define SSAO`),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=r=>{this._firstUpdate&&(r.setArray3("sampleSphere",i),r.setFloat("samplesFactor",s),r.setFloat("randTextureTiles",4)),r.setFloat("totalStrength",this.totalStrength),r.setFloat("radius",this.radius),r.setFloat("area",this.area),r.setFloat("fallOff",this.fallOff),r.setFloat("base",this.base),r.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),r.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new je("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,X.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=t=>{t.setVector4("viewport",W.Vector4[0].copyFromFloats(0,0,1,1)),t.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const t=new Uint8Array(1048576);for(let s=0;s0.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 E=d.getTextureIndex(ui.POSITION_TEXTURE_TYPE),S=d.getTextureIndex(ui.REFLECTIVITY_TEXTURE_TYPE);u.setTexture("normalSampler",d.getGBuffer().textures[1]),u.setTexture("positionSampler",d.getGBuffer().textures[E]),u.setTexture("reflectivitySampler",d.getGBuffer().textures[S])}else if(f){const E=f.getIndex(1),S=f.getIndex(3),C=f.getIndex(6);u.setTexture("normalSampler",f.getRenderTarget().textures[C]),u.setTexture("positionSampler",f.getRenderTarget().textures[E]),u.setTexture("reflectivitySampler",f.getRenderTarget().textures[S])}const m=t.activeCamera;if(!m)return;const _=m.getViewMatrix(!0),x=m.getProjectionMatrix(!0);u.setMatrix("projection",x),u.setMatrix("view",_),u.setFloat("threshold",this.threshold),u.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),u.setFloat("strength",this.strength),u.setFloat("stepSize",this.step),u.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,s){return Pe.Parse(()=>new ka(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}v([O()],ka.prototype,"threshold",void 0);v([O()],ka.prototype,"strength",void 0);v([O()],ka.prototype,"reflectionSpecularFalloffExponent",void 0);v([O()],ka.prototype,"step",void 0);v([O()],ka.prototype,"roughnessFactor",void 0);v([O()],ka.prototype,"enableSmoothReflections",null);v([O()],ka.prototype,"reflectionSamples",null);v([O()],ka.prototype,"smoothSteps",null);H("BABYLON.ScreenSpaceReflectionPostProcess",ka);const zj="standardPixelShader",Wj=`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 +`;j.ShadersStore[zj]=Wj;class ti extends bc{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()){U.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,s=null,r){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=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,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 ka("HDRPass",t,e,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new qt(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new je("HDRPass","standard",[],[],e,null,X.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 qt(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 je("HDRDepthOfFieldSource","standard",[],[],e,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qt(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new je("HDRVLSFinal","standard",[],[],e,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qt(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new je("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qt(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new je("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qt(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 Sf("fxaa",1,null,X.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new qt(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),this._cameras!==null&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&U.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 je("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=s=>{let r=0;const n=this.downSampleX4PostProcess.width,o=this.downSampleX4PostProcess.height;for(let l=-2;l<2;l++)for(let h=-2;h<2;h++)i[r]=(l+.5)*(1/n),i[r+1]=(h+.5)*(1/o),r+=2;s.setArray2("dsOffsets",i)},this.addEffect(new qt(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new je("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=s=>{const r=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*r,i[1]=.5*n,i[2]=.5*r,i[3]=.5*n,i[4]=-.5*r,i[5]=-.5*n,i[6]=.5*r,i[7]=-.5*n,s.setArray2("dsOffsets",i),s.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new qt(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new Hs("HDRBlurH_"+i,new ce(1,0),this[s],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Hs("HDRBlurV_"+i,new ce(0,1),this[s],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{const l=n.width/r.getRenderWidth();n.kernel=this[s]*l}),o.onActivateObservable.add(()=>{const l=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*l:this[s]*l}),this.addEffect(new qt(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new qt(e.getEngine(),"HDRBlurV"+i,()=>o,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new je("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,X.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 qt(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new je("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define VLS +#define NB_STEPS `+this._volumetricLightStepsCount.toFixed(1));const r=ce.Zero();this.volumetricLightPostProcess.onApply=n=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const o=this.sourceLight.getShadowGenerator();n.setTexture("shadowMapSampler",o.getShadowMap()),n.setTexture("positionSampler",s.textures[2]),n.setColor3("sunColor",this.sourceLight.diffuse),n.setVector3("sunDirection",this.sourceLight.getShadowDirection()),n.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),n.setMatrix("shadowViewProjection",o.getTransformMatrix()),n.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),n.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),n.setVector2("depthValues",r)}},this.addEffect(new qt(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new je("HDRVLSMerge","standard",[],["originalSampler"],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=n=>{n.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new qt(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,ti.LuminanceSteps);this.luminancePostProcess=new je("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=n=>{const o=1/this.luminancePostProcess.width,l=1/this.luminancePostProcess.height;s[0]=-.5*o,s[1]=.5*l,s[2]=.5*o,s[3]=.5*l,s[4]=-.5*o,s[5]=-.5*l,s[6]=.5*o,s[7]=-.5*l,n.setArray2("lumOffsets",s)},this.addEffect(new qt(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let n=ti.LuminanceSteps-1;n>=0;n--){i=Math.pow(3,n);let o=`#define LUMINANCE_DOWN_SAMPLE +`;n===0&&(o+="#define FINAL_DOWN_SAMPLER");const l=new je("HDRLuminanceDownSample"+n,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,o,t);this.luminanceDownSamplePostProcesses.push(l)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((n,o)=>{const l=new Array(18);n.onApply=h=>{if(!r)return;let c=0;for(let u=-1;u<2;u++)for(let d=-1;d<2;d++)l[c]=u/r.width,l[c+1]=d/r.height,c+=2;h.setArray2("dsOffsets",l),h.setFloat("halfDestPixelSize",.5/r.width),o===this.luminanceDownSamplePostProcesses.length-1?r=this.luminancePostProcess:r=n},o===this.luminanceDownSamplePostProcesses.length-1&&(n.onAfterRender=()=>{const h=e.getEngine().readPixels(0,0,1,1),c=new tt(1/(255*255*255),1/(255*255),1/255,1);h.then(u=>{const d=new Uint8Array(u.buffer);this._hdrCurrentLuminance=(d[0]*c.x+d[1]*c.y+d[2]*c.z+d[3]*c.w)/100})}),this.addEffect(new qt(e.getEngine(),"HDRLuminanceDownSample"+o,()=>n,!0))})}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new je("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join(` +`),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=o=>{if(o.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const l=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*l?s-=this.hdrIncreaseRate*l:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=Ne.Clamp(s,this.hdrMinimumLuminance,1e20),o.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new qt(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new je("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new qt(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new je("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new qt(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));const i=new ce(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=n=>{n.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),n.setTexture("lensColorSampler",this.lensColorTexture),n.setFloat("strength",this.lensFlareStrength),n.setFloat("ghostDispersal",this.lensFlareGhostDispersal),n.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,n.setVector2("resolution",i),n.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=L.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=L.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=n=>{if(!this._scene.activeCamera)return;n.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),n.setTexture("lensDirtSampler",this.lensFlareDirtTexture),n.setTexture("lensStarSampler",this.lensStarTexture);const o=this._scene.activeCamera.getViewMatrix().getRow(0),l=this._scene.activeCamera.getViewMatrix().getRow(2);let h=T.Dot(o.toVector3(),new T(1,0,0))+T.Dot(l.toVector3(),new T(0,0,1));h*=4;const c=L.FromValues(Math.cos(h)*.5,-Math.sin(h),0,0,Math.sin(h),Math.cos(h)*.5,0,0,0,0,1,0,0,0,0,1),u=r.multiply(c).multiply(s);n.setMatrix("lensStarMatrix",u),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new je("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,X.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 qt(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new vc("HDRMotionBlur",e,t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new je("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,X.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,`#define MOTION_BLUR +#define MAX_MOTION_SAMPLES `+this.motionBlurSamples.toFixed(1),0);let i=0,s=L.Identity();const r=L.Identity();let n=L.Identity();const o=ce.Zero();this.motionBlurPostProcess.onApply=l=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),l.setMatrix("inverseViewProjection",r),l.setMatrix("prevViewProjection",s),s=n,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 qt(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 ti(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Pe.Parse(()=>s.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),s}}ti.LuminanceSteps=6;v([O()],ti.prototype,"brightThreshold",void 0);v([O()],ti.prototype,"blurWidth",void 0);v([O()],ti.prototype,"horizontalBlur",void 0);v([O()],ti.prototype,"exposure",null);v([Dt("lensTexture")],ti.prototype,"lensTexture",void 0);v([O()],ti.prototype,"volumetricLightCoefficient",void 0);v([O()],ti.prototype,"volumetricLightPower",void 0);v([O()],ti.prototype,"volumetricLightBlurScale",void 0);v([O()],ti.prototype,"hdrMinimumLuminance",void 0);v([O()],ti.prototype,"hdrDecreaseRate",void 0);v([O()],ti.prototype,"hdrIncreaseRate",void 0);v([O()],ti.prototype,"hdrAutoExposure",null);v([Dt("lensColorTexture")],ti.prototype,"lensColorTexture",void 0);v([O()],ti.prototype,"lensFlareStrength",void 0);v([O()],ti.prototype,"lensFlareGhostDispersal",void 0);v([O()],ti.prototype,"lensFlareHaloWidth",void 0);v([O()],ti.prototype,"lensFlareDistortionStrength",void 0);v([O()],ti.prototype,"lensFlareBlurWidth",void 0);v([Dt("lensStarTexture")],ti.prototype,"lensStarTexture",void 0);v([Dt("lensFlareDirtTexture")],ti.prototype,"lensFlareDirtTexture",void 0);v([O()],ti.prototype,"depthOfFieldDistance",void 0);v([O()],ti.prototype,"depthOfFieldBlurWidth",void 0);v([O()],ti.prototype,"motionStrength",null);v([O()],ti.prototype,"objectBasedMotionBlur",null);v([O()],ti.prototype,"_ratio",void 0);v([O()],ti.prototype,"BloomEnabled",null);v([O()],ti.prototype,"DepthOfFieldEnabled",null);v([O()],ti.prototype,"LensFlareEnabled",null);v([O()],ti.prototype,"HDREnabled",null);v([O()],ti.prototype,"VLSEnabled",null);v([O()],ti.prototype,"MotionBlurEnabled",null);v([O()],ti.prototype,"fxaaEnabled",null);v([O()],ti.prototype,"screenSpaceReflectionsEnabled",null);v([O()],ti.prototype,"volumetricLightStepsCount",null);v([O()],ti.prototype,"motionBlurSamples",null);v([O()],ti.prototype,"samples",null);H("BABYLON.StandardRenderingPipeline",ti);class Hj{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const Xj="screenSpaceRayTrace",Yj=`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 +ndc.z=-projection[2].z-projection[3].z/depth; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`;j.IncludesShadersStore[Xj]=Yj;const $j="screenSpaceReflection2PixelShader",Kj=`#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);vec3 csViewDirection=normalize(csPosition);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 +} +`;j.ShadersStore[$j]=Kj;const jj="screenSpaceReflection2BlurPixelShader",qj=`#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);} +`;j.ShadersStore[jj]=qj;const Qj="screenSpaceReflection2BlurCombinerPixelShader",Zj=`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 +} +`;j.ShadersStore[Qj]=Zj;const Jj=L.Compose(new T(.5,.5,.5),ae.Identity(),new T(.5,.5,.5)),e7=L.Compose(new T(.5,.5,1),ae.Identity(),new T(.5,.5,0));class Ni extends bc{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,s=!1,r=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=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const n=t.enableGeometryBufferRenderer();n&&(n.enableReflectivity=!0,n.useSpecificClearForDepthTexture=!0)}else{const n=t.enablePrePassRenderer();n&&(n.useSpecificClearForDepthTexture=!0,n.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 s,r;const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&((s=this._scene.activeCamera)==null?void 0:s._getFirstPostProcess())===this._ssrPostProcess){const n=t.getRenderTarget();n&&n.textures&&(i=n.textures[t.getIndex(4)].getSize())}else(r=this._ssrPostProcess)!=null&&r.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){var t,i,s,r;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"),(((t=this._geometryBufferRenderer)==null?void 0:t.generateNormalsInWorldSpace)??((i=this._prePassRenderer)==null?void 0:i.generateNormalsInWorldSpace))&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(s=this._geometryBufferRenderer)!=null&&s.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL"),(r=this._ssrPostProcess)==null||r.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 Ec(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 qt(e,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new qt(e,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new qt(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)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==s)&&this._depthRenderer.getDepthMap().resize({width:i,height:s})}_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,s;for(let r=0;r{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const l=t.getTextureIndex(ui.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),h=i.getIndex(3),c=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[c]),e.setTexture("depthSampler",i.getRenderTarget().textures[l]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[h])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(W.Matrix[0]),r.invertToRef(W.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",W.Matrix[1]),e.setMatrix("invProjectionMatrix",W.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",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();L.ScalingToRef(o.width,o.height,1,W.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?e7:Jj,W.Matrix[3]),W.Matrix[3].multiplyToRef(W.Matrix[2],W.Matrix[4]),e.setMatrix("projectionPixel",W.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 Hj)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new je("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(r=>{var o;const n=((o=this._blurPostProcessX)==null?void 0:o.inputTexture.width)??this._scene.getEngine().getRenderWidth();r.setFloat2("texelOffsetScale",this._blurDispersionStrength/n,0)}),this._blurPostProcessY=new je("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(r=>{var o;const n=((o=this._blurPostProcessY)==null?void 0:o.inputTexture.height)??this._scene.getEngine().getRenderHeight();r.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/n)});const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+=`#define SSRAYTRACE_DEBUG +`),this._inputTextureColorIsInGammaSpace&&(s+=`#define SSR_INPUT_IS_GAMMA_SPACE +`),this._generateOutputInGammaSpace&&(s+=`#define SSR_OUTPUT_IS_GAMMA_SPACE +`),this.useFresnel&&(s+=`#define SSR_BLEND_WITH_FRESNEL +`,t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),this._reflectivityThreshold===0&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new je("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(r=>{var l;const n=this._geometryBufferRenderer,o=this._prePassRenderer;if(!(!o&&!n)){if(o&&((l=this._scene.activeCamera)==null?void 0:l._getFirstPostProcess())===this._ssrPostProcess){const h=o.getRenderTarget();h&&h.textures&&r.setTexture("mainSampler",h.textures[o.getIndex(4)])}else r.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(n){const h=n.getTextureIndex(ui.REFLECTIVITY_TEXTURE_TYPE);r.setTexture("reflectivitySampler",n.getGBuffer().textures[h]),this.useFresnel&&(r.setTexture("normalSampler",n.getGBuffer().textures[1]),r.setTexture("depthSampler",n.getGBuffer().textures[0]))}else if(o){const h=o.getIndex(3);if(r.setTexture("reflectivitySampler",o.getRenderTarget().textures[h]),this.useFresnel){const c=o.getIndex(5),u=o.getIndex(6);r.setTexture("normalSampler",o.getRenderTarget().textures[u]),r.setTexture("depthSampler",o.getRenderTarget().textures[c])}}if(r.setFloat("strength",this.strength),r.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),r.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const h=this._scene.activeCamera;if(h){const c=h.getProjectionMatrix();c.invertToRef(W.Matrix[0]),r.setMatrix("projection",c),r.setMatrix("invProjectionMatrix",W.Matrix[0])}}}})}serialize(){const e=Pe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Pe.Parse(()=>new Ni(e._name,t,e._ratio),e,t,i)}}v([O()],Ni.prototype,"samples",null);v([O()],Ni.prototype,"maxDistance",void 0);v([O()],Ni.prototype,"step",void 0);v([O()],Ni.prototype,"thickness",void 0);v([O()],Ni.prototype,"strength",void 0);v([O()],Ni.prototype,"reflectionSpecularFalloffExponent",void 0);v([O()],Ni.prototype,"maxSteps",void 0);v([O()],Ni.prototype,"roughnessFactor",void 0);v([O()],Ni.prototype,"selfCollisionNumSkip",void 0);v([O()],Ni.prototype,"_reflectivityThreshold",void 0);v([O("_ssrDownsample")],Ni.prototype,"_ssrDownsample",void 0);v([O()],Ni.prototype,"ssrDownsample",null);v([O("blurDispersionStrength")],Ni.prototype,"_blurDispersionStrength",void 0);v([O("blurDownsample")],Ni.prototype,"_blurDownsample",void 0);v([O("enableSmoothReflections")],Ni.prototype,"_enableSmoothReflections",void 0);v([O("environmentTexture")],Ni.prototype,"_environmentTexture",void 0);v([O("environmentTextureIsProbe")],Ni.prototype,"_environmentTextureIsProbe",void 0);v([O("attenuateScreenBorders")],Ni.prototype,"_attenuateScreenBorders",void 0);v([O("attenuateIntersectionDistance")],Ni.prototype,"_attenuateIntersectionDistance",void 0);v([O("attenuateIntersectionIterations")],Ni.prototype,"_attenuateIntersectionIterations",void 0);v([O("attenuateFacingCamera")],Ni.prototype,"_attenuateFacingCamera",void 0);v([O("attenuateBackfaceReflection")],Ni.prototype,"_attenuateBackfaceReflection",void 0);v([O("clipToFrustum")],Ni.prototype,"_clipToFrustum",void 0);v([O("useFresnel")],Ni.prototype,"_useFresnel",void 0);v([O("enableAutomaticThicknessComputation")],Ni.prototype,"_enableAutomaticThicknessComputation",void 0);v([O("backfaceDepthTextureDownsample")],Ni.prototype,"_backfaceDepthTextureDownsample",void 0);v([O("backfaceForceDepthWriteTransparentMeshes")],Ni.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0);v([O("isEnabled")],Ni.prototype,"_isEnabled",void 0);v([O("inputTextureColorIsInGammaSpace")],Ni.prototype,"_inputTextureColorIsInGammaSpace",void 0);v([O("generateOutputInGammaSpace")],Ni.prototype,"_generateOutputInGammaSpace",void 0);v([O("debug")],Ni.prototype,"_debug",void 0);H("BABYLON.SSRRenderingPipeline",Ni);const t7="taaPixelShader",i7=`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);} +`;j.ShadersStore[t7]=i7;class Ph extends bc{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,s=0){const r=t.getEngine();super(r,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=s,this._hs=new Q6(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.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 s,r;const i=this._scene.getEngine();(s=this._ping)==null||s.dispose(),(r=this._pong)==null||r.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 qt(e,this.TAARenderEffect,()=>this._taaPostProcess,!0)),this._createPassPostProcess(),this.addEffect(new qt(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 s=this._scene.getEngine();this._createPingPongTextures(s.getRenderWidth(),s.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===Ve.PERSPECTIVE_CAMERA){const s=e.getProjectionMatrix();s.setRowFromFloats(2,this._hs.x,this._hs.y,s.m[10],s.m[11])}else{const s=e.getProjectionMatrix(!0);s.setRowFromFloats(3,this._hs.x+s.m[12],this._hs.y+s.m[13],s.m[14],s.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 uo("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=Pe.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return Pe.Parse(()=>new Ph(e._name,t,e._ratio),e,t,i)}}v([O("samples")],Ph.prototype,"_samples",void 0);v([O("msaaSamples")],Ph.prototype,"_msaaSamples",void 0);v([O()],Ph.prototype,"factor",void 0);v([O()],Ph.prototype,"disableOnCameraMove",void 0);v([O("isEnabled")],Ph.prototype,"_isEnabled",void 0);H("BABYLON.TAARenderingPipeline",Ph);const s7="tonemapPixelShader",r7=`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);}`;j.ShadersStore[s7]=r7;var mR;(function(a){a[a.Hable=0]="Hable",a[a.Reinhard=1]="Reinhard",a[a.HejiDawson=2]="HejiDawson",a[a.Photographic=3]="Photographic"})(mR||(mR={}));const n7="volumetricLightScatteringPixelShader",a7=`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 +} +`;j.ShadersStore[o7]=l7;const h7="volumetricLightScatteringPassPixelShader",c7=`#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);} +`;j.ShadersStore[h7]=c7;class Ta extends je{get useDiffuseColor(){return U.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){U.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,s,r=100,n=X.BILINEAR_SAMPLINGMODE,o,l,h){super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,o,l,"#define NUM_SAMPLES "+r),this._screenCoordinates=ce.Zero(),this.customMeshPosition=T.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,h=(i==null?void 0:i.getScene())??h??this._scene,o=h.getEngine(),this._viewPort=new da(0,0,1,1).toGlobal(o.getRenderWidth(),o.getRenderHeight()),this.mesh=s??Ta.CreateDefaultMesh("VolumetricLightScatteringMesh",h),this._createPass(h,t.passRatio||t),this.onActivate=c=>{this.isSupported||this.dispose(c),this.onActivate=null},this.onApplyObservable.add(c=>{this._updateMeshScreenCoordinates(h),c.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),c.setFloat("exposure",this.exposure),c.setFloat("decay",this.decay),c.setFloat("weight",this.weight),c.setFloat("density",this.density),c.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var u;const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=(u=i._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:u[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[P.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(P.UVKind)&&(n.push(P.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(P.UV2Kind)&&(n.push(P.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(P.MatricesIndicesKind),n.push(P.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),bh(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),h=l.defines,c=r.join(` +`);return h!==c&&l.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);t!==-1&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&this.includedMeshes.indexOf(e)===-1||this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new Yi("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=X.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=X.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=l=>{var x;const h=l.getRenderingMesh(),c=l.getEffectiveMesh();if(this._meshExcluded(h))return;c._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const u=l.getMaterial();if(!u)return;const d=h.getScene(),f=d.getEngine();f.setState(u.backFaceCulling,void 0,void 0,void 0,u.cullBackFaces);const m=h._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(m.mustReturn)return;const _=f.getCaps().instancedArrays&&(m.visibleInstances[l._id]!==null||h.hasThinInstances);if(this._isReady(l,_)){const E=(x=c._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:x[f.currentRenderPassId];let S=l._getDrawWrapper();if(h===this.mesh&&!S&&(S=u._getDrawWrapper()),!S)return;const C=S.effect;if(f.enableEffect(S),_||h._bind(l,C,u.fillMode),h===this.mesh)u.bind(c.getWorldMatrix(),h);else if(E)E.bindForSubMesh(c.getWorldMatrix(),c,l);else{if(C.setMatrix("viewProjection",d.getTransformMatrix()),u&&u.needAlphaTesting()){const y=u.getAlphaTestTexture();C.setTexture("diffuseSampler",y),y&&C.setMatrix("diffuseMatrix",y.getTextureMatrix())}h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&C.setMatrices("mBones",h.skeleton.getTransformMatrices(h))}_&&h.hasThinInstances&&C.setMatrix("world",c.getWorldMatrix()),h._processRendering(c,l,C,pe.TriangleFillMode,m,_,(y,A)=>{y||C.setMatrix("world",A)})}};let n;const o=new Oe(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{n=e.clearColor,e.clearColor=o}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=n}),this._volumetricLightScatteringRTT.customIsReadyFunction=(l,h,c)=>{if((c||h===0)&&l.subMeshes)for(let u=0;u{const d=e.getEngine();let f;if(u.length){for(d.setColorWrite(!1),f=0;f_._alphaIndex>x._alphaIndex?1:_._alphaIndexx._distanceToCamera?-1:0),d.setAlphaMode(2),f=0;f{c.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),c.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const u=this._geometryBufferRenderer.getGBuffer().textures[1];c.setTexture("normalSampler",u)}):U.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=We.LastCreatedEngine;return e?e.getCaps().drawBuffersExtension:!1}static _Parse(e,t,i,s){return Pe.Parse(()=>new S_(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,s)}}v([O()],S_.prototype,"ridge",void 0);v([O()],S_.prototype,"valley",void 0);H("BABYLON.ScreenSpaceCurvaturePostProcess",S_);const f7="boundingBoxRendererFragmentDeclaration",p7=`uniform vec4 color; +`;j.IncludesShadersStore[f7]=p7;const _7="boundingBoxRendererUboDeclaration",m7=`#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 +`;j.IncludesShadersStore[_7]=m7;const g7="boundingBoxRendererPixelShader",x7=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;j.ShadersStore[g7]=x7;const T7="boundingBoxRendererVertexDeclaration",E7=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;j.IncludesShadersStore[T7]=E7;const S7="boundingBoxRendererVertexShader",v7=`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 +} +`;j.ShadersStore[S7]=v7;Object.defineProperty(Ue.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(a){this._forceShowBoundingBoxes=a,a&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Ue.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new C7(this)),this._boundingBoxRenderer};Object.defineProperty(Ft.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(a){this._showBoundingBox=a,a&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class C7{constructor(e){this.name=ve.NAME_BOUNDINGBOXRENDERER,this.frontColor=new re(1,1,1),this.backColor=new re(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new K,this.onAfterBoxRenderingObservable=new K,this.onResourcesReadyObservable=new K,this.enabled=!0,this.renderList=new Ps(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new ze(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new ze(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),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(ve.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ve.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ve.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ve.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 vn("colorShader",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new vn("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[P.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=Gv({size:1});this._vertexBuffers[P.PositionKind]=new P(e,t.positions,P.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[P.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 s=0;s{let e=a._getComponent(ve.NAME_DEPTHRENDERER);e||(e=new b7(a),a._addComponent(e))};const y7="oitFinalPixelShader",A7=`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 +);}`;j.ShadersStore[y7]=A7;const R7="oitBackBlendPixelShader",I7=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;j.ShadersStore[R7]=I7;class P7{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class _l{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 Ps(10),this._excludedSubMeshes=new Ps(10),this._excludedMeshes=[],this._colorCache=[new Oe(_l._DEPTH_CLEAR_VALUE,_l._DEPTH_CLEAR_VALUE,0,0),new Oe(-_l._MIN_DEPTH,_l._MAX_DEPTH,0,0),new Oe(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){U.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let i=0;i +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 +}`;j.ShadersStore[O7]=D7;const N7="lineVertexShader",w7=`#include +#include +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;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 +}`;j.ShadersStore[N7]=w7;Ft.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this};Ft.prototype.enableEdgesRendering=function(a=.95,e=!1,t){return this.disableEdgesRendering(),this._edgesRenderer=new Nx(this,a,e,!0,t),this};Object.defineProperty(Ft.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0});xh.prototype.enableEdgesRendering=function(a=.95,e=!1){return this.disableEdgesRendering(),this._edgesRenderer=new L7(this,a,e),this};BP.prototype.enableEdgesRendering=function(a=.95,e=!1){return xh.prototype.enableEdgesRendering.apply(this,arguments),this};class F7{constructor(){this.edges=[],this.edgesConnectedCount=0}}class Nx{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new vn("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){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 Ps(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Ws(e.getEngine())),this._prepareRessources(),s&&((r==null?void 0:r.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=Nx._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[P.PositionKind];e&&e._rebuild(),e=this._buffers[P.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[P.PositionKind];e&&(e.dispose(),this._buffers[P.PositionKind]=null),e=this._buffers[P.NormalKind],e&&(e.dispose(),this._buffers[P.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),(t=this._drawWrapper)==null||t.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)?1:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)?2:-1}_checkEdge(e,t,i,s,r){let n;t===void 0?n=!0:n=T.Dot(i[e],i[t]){B>=0&&k.push(B);for(let Q=0;Q=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let N=0;N<3;++N)N===n?e[N].sort((k,B)=>k[1]B[1]?1:0):e[N].sort((k,B)=>k[1]>B[1]?-1:k[1]=n+1;--N)r(e[N%3],l,N!==n+2?s[i[t+(N+1)%3]]:-1);const c=l.length,u=0,d=0;i.push(s[i[t+n]],o[0],l[0]),i.push(s[i[t+(n+1)%3]],l[c-1],o[h-1]);const f=h<=c,m=f?h:c,_=f?c:h,x=f?h-1:c-1,E=f?0:1;let S=h+c-2,C=f?u:d,y=f?d:u;const A=f?o:l,I=f?l:o;let R=0;for(;S-- >0;){E?i.push(A[C],I[y]):i.push(I[y],A[C]),R+=m;let N;R>=_&&CC){const R=S;S=C,C=R}const A=S+"_"+C,I=o[A];I?I.done||(T.Dot(x,I.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,s=i||this._source.hasThinInstances;let r=0;if(s)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(r=this.customInstances.length,!o.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!o.isFrozen){let l=0;for(let h=0;h0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[r]===5?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.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(s)}_resetLayout(){for(let e=0;el!=null),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),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;es!=null),t)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw ot("PrePassRendererSceneComponent")};Pr.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}];Object.defineProperty(Ue.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(a){a&&a.isSupported&&(this._prePassRenderer=a)},enumerable:!0,configurable:!0});Ue.prototype.enablePrePassRenderer=function(){return this._prePassRenderer?this._prePassRenderer:(this._prePassRenderer=new Pr(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,U.Error(`PrePassRenderer needs WebGL 2 support. +Maybe you tried to use the following features that need the PrePassRenderer : + + Subsurface Scattering`)),this._prePassRenderer)};Ue.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class U7{constructor(e){this.name=ve.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ve.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ve.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ve.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ve.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ve.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ve.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ve.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ve.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,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}Pr._SceneComponentInitialization=a=>{let e=a._getComponent(ve.NAME_PREPASSRENDERER);e||(e=new U7(a),a._addComponent(e))};const V7="fibonacci",k7=`#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);}`;j.IncludesShadersStore[V7]=k7;const G7="diffusionProfile",z7="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";j.IncludesShadersStore[G7]=z7;const W7="subSurfaceScatteringPixelShader",H7=`#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){U.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}const c=this.texelSize;h.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),h.setFloat2("texelSize",c.x,c.y),h.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),h.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),h.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),h.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),h.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),h.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),h.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class v_{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=ve.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new re(1,1,1)),this._scene=e,v_._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return U.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw ot("SubSurfaceSceneComponent")};xs.AddParser(ve.NAME_SUBSURFACE,(a,e)=>{if(a.ssDiffusionProfileColors!==void 0&&a.ssDiffusionProfileColors!==null&&(e.enableSubSurfaceForPrePass(),e.subSurfaceConfiguration))for(let t=0,i=a.ssDiffusionProfileColors.length;t{let e=a._getComponent(ve.NAME_SUBSURFACE);e||(e=new Y7(a),a._addComponent(e))};const $7="outlinePixelShader",K7=`#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 +}`;j.ShadersStore[$7]=K7;const j7="outlineVertexShader",q7=`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 +} +`;j.ShadersStore[j7]=q7;Ue.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new jp(this)),this._outlineRenderer};Object.defineProperty(q.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOutline=a},enumerable:!0,configurable:!0});Object.defineProperty(q.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(a){a&&this.getScene().getOutlineRenderer(),this._renderOverlay=a},enumerable:!0,configurable:!0});class jp{constructor(e){this.name=ve.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId(`Outline Renderer (${t})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(ve.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ve.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{m.setMatrix("world",x)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[P.PositionKind,P.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const l=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(P.UVKind)&&(r.push(P.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(P.UV2Kind)&&(r.push(P.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),vh(o,l,s),n.useBones&&n.computeBonesUsingShaders?(r.push(P.MatricesIndicesKind),r.push(P.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(P.MatricesIndicesExtraKind),r.push(P.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const h=n.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),o_(r,n,c))),t&&(s.push("#define INSTANCES"),bh(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),d=u.defines,f=s.join(` +`);if(d!==f){const m=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Va(m),u.setEffect(this.scene.getEngine().createEffect("outline",r,m,["diffuseSampler","morphTargets"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),f)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.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(jp._StencilReference),this._engine.setStencilFunctionReference(jp._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),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const s=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(s),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}jp._StencilReference=4;class eO{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 K,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 xl({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new xl({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(),(t=this._thicknessEffectWrapper)==null||t.dispose()}}class Q7 extends eO{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 AE{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 s=0;s{this._postProcessRunningIndex===0?x.setTexture("textureSampler",e):x._bindTexture("textureSampler",f.inputTexture.texture),x.setInt("filterSize",this.blurFilterSize),x.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),f.onSizeChangedObservable.add(()=>{f._textures.forEach(x=>{x.texture.wrapU=X.CLAMP_ADDRESSMODE,x.texture.wrapV=X.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(f);const m=new je("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);m.samples=this._samples,m.onApplyObservable.add(x=>{x.setInt("filterSize",this.blurFilterSize),x.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),m.onSizeChangedObservable.add(()=>{m._textures.forEach(x=>{x.texture.wrapU=X.CLAMP_ADDRESSMODE,x.texture.wrapV=X.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(m),f.autoClear=!1,m.autoClear=!1;const _=[];for(let x=0;x{this._postProcessRunningIndex===0?E.setTexture("textureSampler",e):E._bindTexture("textureSampler",m.inputTexture.texture),E.setInt("maxFilterSize",this.blurMaxFilterSize),E.setFloat2("blurDir",1/this._blurTextureSizeX,0),E.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),E.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),m.onSizeChangedObservable.add(()=>{m._textures.forEach(E=>{E.texture.wrapU=X.CLAMP_ADDRESSMODE,E.texture.wrapV=X.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(m);const _=new je("BilateralBlurY","fluidRenderingBilateralBlur",f,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add(E=>{E.setInt("maxFilterSize",this.blurMaxFilterSize),E.setFloat2("blurDir",0,1/this._blurTextureSizeY),E.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),E.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),_.onSizeChangedObservable.add(()=>{_._textures.forEach(E=>{E.texture.wrapU=X.CLAMP_ADDRESSMODE,E.texture.wrapV=X.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(_),m.autoClear=!1,_.autoClear=!1;const x=[];for(let E=0;E{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,s;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,(s=this._textureBlurred)==null||s.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var sa;(function(a){a[a.DepthTexture=0]="DepthTexture",a[a.DepthBlurredTexture=1]="DepthBlurredTexture",a[a.ThicknessTexture=2]="ThicknessTexture",a[a.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",a[a.DiffuseTexture=4]="DiffuseTexture",a[a.Normals=5]="Normals",a[a.DiffuseRendering=6]="DiffuseRendering"})(sa||(sa={}));class gR{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 camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new re(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new T(-2,-1,1).normalize(),this._debugFeature=sa.DepthBlurredTexture,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 K,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new L,this._depthClearColor=new Oe(1e6,1e6,1e6,1),this._thicknessClearColor=new Oe(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 AE("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const r=this._diffuseMapSize??this._engine.getRenderWidth(),n=this._diffuseMapSize!==null?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new AE("Diffuse",this._scene,r,n,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=this._thicknessMapSize!==null?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new AE("Thickness",this._scene,i,s,i,s,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"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new ce(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),this._environmentMap!==null&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===sa.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===sa.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),(this._debugFeature===sa.DepthTexture||this._debugFeature===sa.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new je("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join(` +`)),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(o=>{var l,h,c,u,d,f,m,_,x,E;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),e.isWebGPU&&o.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(o.setTexture("depthSampler",this._depthRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((h=this._depthRenderTarget.textureBlur)==null?void 0:h.getInternalTexture())??null)):(o.setTexture("depthSampler",this._depthRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("depthSamplerSampler",((l=this._depthRenderTarget.texture)==null?void 0:l.getInternalTexture())??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(o.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((u=this._diffuseRenderTarget.textureBlur)==null?void 0:u.getInternalTexture())??null)):(o.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("diffuseSamplerSampler",((c=this._diffuseRenderTarget.texture)==null?void 0:c.getInternalTexture())??null)):o.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(o.setFloat("thickness",this.minimumThickness),o._bindTexture("bgDepthSampler",this._bgDepthTexture),e.isWebGPU&&o.setTextureSampler("bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(o.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((f=this._thicknessRenderTarget.textureBlur)==null?void 0:f.getInternalTexture())??null)):(o.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),e.isWebGPU&&o.setTextureSampler("thicknessSamplerSampler",((d=this._thicknessRenderTarget.texture)==null?void 0:d.getInternalTexture())??null)),o.setFloat("minimumThickness",this.minimumThickness)),this._environmentMap!==null){const S=this._environmentMap??this._scene.environmentTexture;S&&(o.setTexture("reflectionSampler",S),e.isWebGPU&&o.setTextureSampler("reflectionSamplerSampler",(S==null?void 0:S.getInternalTexture())??null))}if(o.setMatrix("viewMatrix",this._scene.getViewMatrix()),o.setMatrix("invProjectionMatrix",this._invProjectionMatrix),o.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),o.setVector2("texelSize",n),o.setFloat("density",this.density),o.setFloat("refractionStrength",this.refractionStrength),o.setFloat("fresnelClamp",this.fresnelClamp),o.setFloat("specularPower",this.specularPower),o.setVector3("dirLight",this.dirLight),o.setFloat("cameraFar",this._camera.maxZ),this._debug){let S=null;switch(this._debugFeature){case sa.DepthTexture:S=this._depthRenderTarget.texture;break;case sa.DepthBlurredTexture:S=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case sa.ThicknessTexture:S=((m=this._thicknessRenderTarget)==null?void 0:m.texture)??null;break;case sa.ThicknessBlurredTexture:S=(_=this._thicknessRenderTarget)!=null&&_.enableBlur?((x=this._thicknessRenderTarget)==null?void 0:x.textureBlur)??null:((E=this._thicknessRenderTarget)==null?void 0:E.texture)??null;break;case sa.DiffuseTexture:this._diffuseRenderTarget&&(S=this._diffuseRenderTarget.texture);break}this._debugFeature!==sa.Normals&&(o.setTexture("debugSampler",S),e.isWebGPU&&o.setTextureSampler("debugSamplerSampler",(S==null?void 0:S.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,s,r,n,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)),(s=this._diffuseRenderTarget)!=null&&s.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(r=this._thicknessRenderTarget)!=null&&r.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),(n=this._depthRenderTarget)==null||n.applyBlurPostProcesses(),(o=this._diffuseRenderTarget)==null||o.applyBlurPostProcesses(),(l=this._thicknessRenderTarget)==null||l.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){var t,i,s,r;e||((t=this._depthRenderTarget)==null||t.dispose(),this._depthRenderTarget=null,(i=this._diffuseRenderTarget)==null||i.dispose(),this._diffuseRenderTarget=null,(s=this._thicknessRenderTarget)==null||s.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),(r=this._renderPostProcess)==null||r.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Z7 extends eO{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,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1;break}this._vertexBuffers[t]=new P(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects();const e=["view","projection","size"],t=["position","offset","color"];this._diffuseEffectWrapper=new xl({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 P(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={}}}const J7="copyTextureToTexturePixelShader",eq=`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 +} +`;j.ShadersStore[J7]=eq;var aS;(function(a){a[a.None=0]="None",a[a.ToLinearSpace=1]="ToLinearSpace",a[a.ToGammaSpace=2]="ToGammaSpace"})(aS||(aS={}));class tq{_textureIsInternal(e){return e.getInternalTexture===void 0}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new Qg(e),this._effectWrapper=new xl({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.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._effectWrapper.effect.isReady()}copy(e,t,i=aS.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class iq{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new tq(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"});const r=this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil");r.label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const sq="fluidRenderingParticleDepthVertexShader",rq=`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 +} +`;j.ShadersStore[sq]=rq;const nq="fluidRenderingParticleDepthPixelShader",aq=`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 +} +`;j.ShadersStore[nq]=aq;const oq="fluidRenderingParticleThicknessVertexShader",lq=`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;} +`;j.ShadersStore[oq]=lq;const hq="fluidRenderingParticleThicknessPixelShader",cq=`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);} +`;j.ShadersStore[hq]=cq;const uq="fluidRenderingParticleDiffuseVertexShader",dq=`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;} +`;j.ShadersStore[uq]=dq;const fq="fluidRenderingParticleDiffusePixelShader",pq=`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);} +`;j.ShadersStore[fq]=pq;const _q="fluidRenderingBilateralBlurPixelShader",mq=`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.);} +`;j.ShadersStore[_q]=mq;const gq="fluidRenderingStandardBlurPixelShader",xq=`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.);} +`;j.ShadersStore[gq]=xq;const Tq="fluidRenderingRenderPixelShader",Eq=`/* 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 +glFragColor=backColor;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);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);} +`;j.ShadersStore[Tq]=Eq;Object.defineProperty(Ue.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(a){this._fluidRenderer=a},enumerable:!0,configurable:!0});Ue.prototype.enableFluidRenderer=function(){return this._fluidRenderer?this._fluidRenderer:(this._fluidRenderer=new IC(this),this._fluidRenderer)};Ue.prototype.disableFluidRenderer=function(){var a;(a=this._fluidRenderer)==null||a.dispose(),this._fluidRenderer=null};function Sq(a){return!!a.particleSystem}function vq(a){return!!a.addBuffers}class Cq{constructor(e){this.name=ve.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ve.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ve.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 IC{static _SceneComponentInitialization(e){let t=e._getComponent(ve.NAME_FLUIDRENDERER);t||(t=new Cq(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,IC._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,s){const r=new Q7(this._scene,e);r.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new gR(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),t!==void 0&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new Z7(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),s||(s=new gR(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),i!==void 0&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};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 s=0;s{var h;n.inputTexture.depthStencilTexture||n.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,o[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${n.name}`);for(const c of o){const u=(h=c._thicknessRenderTarget)==null?void 0:h.renderTarget,d=u==null?void 0:u.texture;if(u&&d){const f=d.width+"_"+d.height;let m=l[f];m||(m=l[f]=new iq(this._engine,d.width,d.height)),m.depthRTWrapper.shareDepth(u)}}})}t=this._cameras.keys();for(let i=t.next();i.done!==!0;i=t.next()){const s=i.value,n=this._cameras.get(s)[1],o=e.get(s);if(o)for(const l in n)o[1][l]||n[l].dispose();else for(const l in n)n[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 s=0;s{const t=e[1];for(const i in t)t[i].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class bq extends Gr{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class bf extends hn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,bf.Name,300,new bq),this._lightColor=new re,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof ei?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===yt.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}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()===yt.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=W.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){return e==="vertex"?null:{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 + `}}}bf.Name="RSMCreate";v([O()],bf.prototype,"light",void 0);v([O(),_e("_markAllSubMeshesAsTexturesDirty")],bf.prototype,"isEnabled",void 0);H("BABYLON.RSMCreatePluginMaterial",bf);const yq="bilateralBlurPixelShader",Aq=`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.);} +`;j.ShadersStore[yq]=Aq;const Rq="bilateralBlurQualityPixelShader",Iq=`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.);} +`;j.ShadersStore[Rq]=Iq;const Pq="rsmGlobalIlluminationPixelShader",Mq=`/** +* 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;} +`;j.ShadersStore[Pq]=Mq;const Oq="rsmFullGlobalIlluminationPixelShader",Dq=`/** +* 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; j0.) {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;}`;j.ShadersStore[wq]=Fq;const Lq="spriteMapVertexShader",Bq=`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;}`;j.ShadersStore[Lq]=Bq;var xR;(function(a){a[a.INIT=0]="INIT",a[a.RUNNING=1]="RUNNING",a[a.DONE=2]="DONE",a[a.ERROR=3]="ERROR"})(xR||(xR={}));class ep{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}K.prototype.notifyObserversWithPromise=async function(a,e=-1,t,i,s){let r=Promise.resolve(a);if(!this.observers.length)return r;const n=this._eventState;return n.mask=e,n.target=t,n.currentTarget=i,n.skipNextObservers=!1,n.userInfo=s,this.observers.forEach(o=>{n.skipNextObservers||o._willBeUnregistered||o.mask&e&&(o.scope?r=r.then(l=>(n.lastReturnValue=l,o.callback.apply(o.scope,[a,n]))):r=r.then(l=>(n.lastReturnValue=l,o.callback(a,n))),o.unregisterOnNextCall&&this._deferUnregister(o))}),await r,a};let Gl=null;function tO(a,e,t,i,s="image/png",r=!1,n){const{height:o,width:l}=iO(a,e,t);if(!(o&&l)){U.Error("Invalid 'size' parameter !");return}Gl||(Gl=document.createElement("canvas")),Gl.width=l,Gl.height=o;const h=Gl.getContext("2d"),c=a.getRenderWidth()/a.getRenderHeight();let u=l,d=u/c;d>o&&(d=o,u=d*c);const f=Math.max(0,l-u)/2,m=Math.max(0,o-d)/2;e.getScene().activeCamera!==e?PC(a,e,t,x=>{if(r){const E=new Blob([x]);Z.DownloadBlob(E),i&&i("")}else i&&i(x)},s,1,a.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):a.onEndFrameObservable.addOnce(()=>{const x=a.getRenderingCanvas();h&&x&&h.drawImage(x,f,m,u,d),Gl&&(r?(Z.EncodeScreenshotCanvasData(Gl,void 0,s,void 0,n),i&&i("")):Z.EncodeScreenshotCanvasData(Gl,i,s,void 0,n))})}function Uq(a,e,t,i="image/png",s){return new Promise((r,n)=>{tO(a,e,t,o=>{typeof o<"u"?r(o):n(new Error("Data is undefined"))},i,void 0,s)})}function PC(a,e,t,i,s="image/png",r=1,n=!1,o,l=!1,h=!1,c=!0,u,d){const{height:f,width:m,finalWidth:_,finalHeight:x}=iO(a,e,t),E={width:m,height:f};if(!(f&&m)){U.Error("Invalid 'size' parameter !");return}const S={width:a.getRenderWidth(),height:a.getRenderHeight()};a.setSize(m,f);const C=e.getScene(),y=new Yi("screenShot",E,C,!1,!1,0,!1,X.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);y.renderList=C.meshes.slice(),y.samples=r,y.renderSprites=l,y.activeCamera=e,y.forceLayerMaskCheck=c,d==null||d(y);const A=()=>{y.isReadyForRendering()&&e.isReady(!0)?(a.onEndFrameObservable.addOnce(()=>{_===m&&x===f?y.readPixels(void 0,void 0,void 0,!1).then(R=>{Lr.DumpData(m,f,R,i,s,o,!0,void 0,u),y.dispose()}):Kv("pass",y.getInternalTexture(),C,void 0,void 0,void 0,_,x).then(R=>{a._readTexturePixels(R,_,x,-1,0,null,!0,!1,0,0).then(N=>{Lr.DumpData(_,x,N,i,s,o,!0,void 0,u),R.dispose()})})}),y.render(!0),C.incrementRenderId(),C.resetCachedMaterial(),a.setSize(S.width,S.height),e.getProjectionMatrix(!0),C.render()):setTimeout(A,16)},I=()=>{C.incrementRenderId(),C.resetCachedMaterial(),A()};if(n){const R=new Sf("antialiasing",1,C.activeCamera);y.addPostProcess(R),R.getEffect().isReady()?I():R.getEffect().onCompiled=()=>{I()}}else I()}function Vq(a,e,t,i="image/png",s=1,r=!1,n,o=!1,l=!1,h=!0,c){return new Promise((u,d)=>{PC(a,e,t,f=>{typeof f<"u"?u(f):d(new Error("Data is undefined"))},i,s,r,n,o,l,h,c)})}function iO(a,e,t){let i=0,s=0,r=0,n=0;if(typeof t=="object"){const o=t.precision?Math.abs(t.precision):1;t.width&&t.height?(i=t.height*o,s=t.width*o):t.width&&!t.height?(s=t.width*o,i=Math.round(s/a.getAspectRatio(e))):t.height&&!t.width?(i=t.height*o,s=Math.round(i*a.getAspectRatio(e))):(s=Math.round(a.getRenderWidth()*o),i=Math.round(s/a.getAspectRatio(e))),t.finalWidth&&t.finalHeight?(n=t.finalHeight,r=t.finalWidth):t.finalWidth&&!t.finalHeight?(r=t.finalWidth,n=Math.round(r/a.getAspectRatio(e))):t.finalHeight&&!t.finalWidth?(n=t.finalHeight,r=Math.round(n*a.getAspectRatio(e))):(r=s,n=i)}else isNaN(t)||(i=t,s=t,r=t,n=t);return s&&(s=Math.floor(s)),i&&(i=Math.floor(i)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),{height:i|0,width:s|0,finalWidth:r|0,finalHeight:n|0}}const kq=()=>{Z.CreateScreenshot=tO,Z.CreateScreenshotAsync=Uq,Z.CreateScreenshotUsingRenderTarget=PC,Z.CreateScreenshotUsingRenderTargetAsync=Vq};kq();var TR;(function(a){a[a.Checkbox=0]="Checkbox",a[a.Slider=1]="Slider",a[a.Vector3=2]="Vector3",a[a.Quaternion=3]="Quaternion",a[a.Color3=4]="Color3",a[a.String=5]="String",a[a.Button=6]="Button",a[a.Options=7]="Options",a[a.Tab=8]="Tab",a[a.FileButton=9]="FileButton",a[a.Vector2=10]="Vector2"})(TR||(TR={}));class Gm{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 RU(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class ER{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())}}ER._Storage=ER._GetStorage();var SR;(function(a){class e{serialize(){const s={},r=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((n,o)=>{r[n]=o}),s.characters=r,s.insertionCosts=this._insertionCosts,s.deletionCosts=this._deletionCosts,s.substitutionCosts=this._substitutionCosts,JSON.stringify(s)}static Deserialize(s){const r=JSON.parse(s),n=new e(r.characters);return n._insertionCosts=r.insertionCosts,n._deletionCosts=r.deletionCosts,n._substitutionCosts=r.substitutionCosts,n}constructor(s,r=null,n=null,o=null){r=r??(()=>1),n=n??(()=>1),o=o??((h,c)=>h===c?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(s.length),this._deletionCosts=new Array(s.length),this._substitutionCosts=new Array(s.length);let l;for(let h=0;ht._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+t._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=r,this._characters=s.map(n=>this._alphabet.getCharacterIdx(n))}distance(s){return t._Distance(this,s)}static _Distance(s,r){const n=s._alphabet;if(n!==r._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const o=s._characters,l=r._characters,h=o.length,c=l.length,u=t._CostMatrix;u[0][0]=0;for(let d=0;dnew Array(t._MAX_SEQUENCE_LENGTH+1)),a.Sequence=t})(SR||(SR={}));new L;const Gq=1.5;class zl{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*Gq),t=new Float32Array(e);t.set(this._view),this._view=t}}const Wl=1800,zq=24,Wq="0",vR="timestamp",CR="numPoints",Hq=/\r/g,RE="@";class ja{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const i=ks.Now-this._startingTimestamp,s=this.datasets.ids.length,r=this.datasets.startingIndices.itemLength;let n=0;if(r>0){const o=this.datasets.startingIndices.at(r-1);n=o+this.datasets.data.at(o+ja.NumberOfPointsOffset)+ja.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(i),this.datasets.data.push(s),this.datasets.ids.forEach(o=>{const l=this._strategies.get(o);l&&this.datasets.data.push(l.getData())}),this.datasetObservable.hasObservers()){const o=[i,s];for(let l=0;li.callback(this._datasetMeta,new aI(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&((n=this._strategies.get(e))==null||n.dispose(),this._strategies.delete(e));const s=o=>{let l=0,h=0;const c=o.onAfterRenderObservable.add(()=>{h=l,l=0}),u=this._customEventObservable.add(d=>{e===d.name&&(d.value!==void 0?l=d.value:l++)});return{id:e,getData:()=>h,dispose:()=>{o.onAfterRenderObservable.remove(c),this._customEventObservable.remove(u)}}},r={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:s,category:i}),r}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:s}of e){const r=t(this._scene);if(this._strategies.has(r.id)){r.dispose();continue}this.datasets.ids.push(r.id),i&&(i=i.replace(new RegExp(RE,"g"),"")),this._datasetMeta.set(r.id,{color:this._getHexColorFromId(r.id),category:i,hidden:s}),this._strategies.set(r.id,r)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let s=0;s>s&255;i+=(Wq+r.toString(16)).substr(-2)}return i}getCurrentSlice(){const e=ks.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(s=>{const r=this._strategies.get(s);r&&this.datasetObservable.hasObservers()&&i.push(r.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new zl(Wl),this.datasets.ids.length=0,this.datasets.startingIndices=new zl(Wl),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(Hq,"").split(` +`).map(u=>u.split(",").filter(d=>d.length>0)).filter(u=>u.length>0),s=0,r=ja.NumberOfPointsOffset;if(i.length<2)return!1;const n={ids:[],data:new zl(Wl),startingIndices:new zl(Wl)},[o,...l]=i;if(o.length<2||o[s]!==vR||o[r]!==CR)return!1;const h=new Map;for(let u=ja.SliceDataOffset;uu.dispose()),this._strategies.clear(),!t)for(const u of this.datasets.ids){const d=h.get(u);this._datasetMeta.set(u,{category:d,color:this._getHexColorFromId(u)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${vR},${CR}`;for(let i=0;i{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}Ue.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new ja(this)),this._perfCollector};function Xq(a){const e=new Array,t=new Array,i=new Array,s=a.add(()=>{const n=e.length;for(let o=0;o{e.push(n),t.push(o),i.push(l)},dispose:()=>{a.remove(s)}}}K.prototype.runCoroutineAsync=function(a){if(!this._coroutineScheduler){const e=Xq(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return qI(a,this._coroutineScheduler)};K.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};const Yq="equirectangularPanoramaPixelShader",$q=`#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 );}`;j.ShadersStore[Yq]=$q;class ch extends nr{constructor(e,t={}){super(e),this.options=t,this._direction=new T(0,0,-1),this._mat=new L,this._onSelectEnabled=!1,this._origin=new T(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new K,this._onHitTestResults=i=>{const s=i.map(r=>{const n=L.FromArray(r.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||n.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&n.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),n),{xrHitResult:r,transformationMatrix:n}});this.lastNativeXRHitResults=i,this.onHitTestResultObservable.notifyObservers(s)},this._onSelect=i=>{this._onSelectEnabled&&ch.XRHitTestWithSelectEvent(i,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Z.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then(r=>{const n=s||(o=>!!o.hitMatrix);return r.filter(n)})}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,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;L.FromArrayToRef(t.transform.matrix,0,this._mat),T.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),T.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});ch.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}ch.Name=Vt.HIT_TEST;ch.Version=1;qi.AddWebXRFeature(ch.Name,(a,e)=>()=>new ch(a,e),ch.Version,!1);let Kq=0;class lp extends nr{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 K,this.onAnchorRemovedObservable=new K,this.onAnchorUpdatedObservable=new K,this._tmpVector=new T,this._tmpQuaternion=new ae,this.xrNativeFeatureName="anchors"}_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 T,i=new ae){this._populateTmpTransformation(t,i);const s=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 r=await e.xrHitResult.createAnchor(s);return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!0,xrTransformation:s,resolve:n,reject:o})})}catch(r){throw new Error(r)}else throw this.detach(),new Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new ae,i=!1){this._populateTmpTransformation(e,t);const s=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}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise((n,o)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:n,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();if(e){try{e.remove()}catch{}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(r=>!t.has(r.xrAnchor)).map(r=>this._trackedAnchors.indexOf(r));let s=0;i.forEach(r=>{const n=this._trackedAnchors.splice(r-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(n),s++}),t.forEach(r=>{if(this._lastFrameDetected.has(r)){const n=this._findIndexInAnchorArray(r),o=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(r,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new ae,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(o)}catch{Z.Warn("Anchor could not be updated")}}else{const n={id:Kq++,xrAnchor:r,remove:()=>r.delete()},o=this._updateAnchorWithXRFrame(r,n,e);this._trackedAnchors.push(o),this.onAnchorAddedObservable.notifyObservers(o);const h=this._futureAnchors.filter(c=>c.nativeAnchor===r)[0];h&&(h.resolve(o),h.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(i=>{!i.resolved&&!i.submitted&&(this._createAnchorAtTransformation(i.xrTransformation,e).then(s=>{i.nativeAnchor=s},s=>{i.resolved=!0,i.reject(s)}),i.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new lp(a,e),lp.Version);let jq=0;class hp extends nr{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new K,this.onPlaneRemovedObservable=new K,this.onPlaneUpdatedObservable=new K,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 s=0;s{if(this._lastFrameDetected.has(s)){if(s.lastChangedTime===this._xrSessionManager.currentTimestamp){const r=this._findIndexInPlaneArray(s),n=this._detectedPlanes[r];this._updatePlaneWithXRPlane(s,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const r={id:jq++,xrPlane:s,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(s,r,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}}),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(r=>{const n=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new T(r.x,r.y,r.z*n)});const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const r=t.transformationMatrix||new L;L.FromArrayToRef(s.transform.matrix,0,r),this._xrSessionManager.scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),t.transformationMatrix=r,this._options.worldParentNode&&r.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),r)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new hp(a,e),hp.Version);class cp extends nr{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new K}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)}}cp.Name=Vt.BACKGROUND_REMOVER;cp.Version=1;qi.AddWebXRFeature(cp.Name,(a,e)=>()=>new cp(a,e),cp.Version,!0);class up extends nr{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||ht.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=Go("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});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new ae;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new ht(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=i=>{this._controllers[i.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||U.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&i.inputSource.gamepad?i.onMotionControllerInitObservable.addOnce(s=>{s._doNotLoadControllerMesh?this._createPhysicsImpostor(i):s.onModelLoadedObservable.addOnce(()=>{const r=new ht(s.rootMesh,ht.MeshImpostor,{mass:0,...this._options.physicsProperties}),n=i.grip||i.pointer;this._controllers[i.uniqueId]={xrController:i,impostor:r,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(i))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new ae,this._tmpVector=new T,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:ht.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Go("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 ae,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ht(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 s=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if((i=this._options.xrInput.xrCamera._lastXRViewerPose)!=null&&i.angularVelocity){const s=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(s.x,s.y,s.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(s=>{var h,c;const r=this._controllers[s],n=r.xrController.grip||r.xrController.pointer,o=r.oldPos||r.impostorMesh.position;if((h=r.xrController._lastXRPose)!=null&&h.linearVelocity){const u=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(u.x,u.y,u.z),r.impostor.setLinearVelocity(this._tmpVector)}else n.position.subtractToRef(o,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);o.copyFrom(n.position),this._debugMode&&U.Log([this._tmpVector,"linear"]);const l=r.oldRotation||r.impostorMesh.rotationQuaternion;if((c=r.xrController._lastXRPose)!=null&&c.angularVelocity){const u=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(u.x,u.y,u.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!l.equalsWithEpsilon(n.rotationQuaternion)){l.conjugateInPlace().multiplyToRef(n.rotationQuaternion,this._tmpQuaternion);const u=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),u<.001)this._tmpVector.scaleInPlace(2);else{const d=2*Math.atan2(u,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(d/(u*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}l.copyFrom(n.rotationQuaternion),this._debugMode&&U.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}up.Name=Vt.PHYSICS_CONTROLLERS;up.Version=1;qi.AddWebXRFeature(up.Name,(a,e)=>()=>new up(a,e),up.Version,!0);class dp extends nr{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new L,this._tmpPos=new T,this._tmpQuat=new ae,this._initHitTestSource=i=>{if(!i)return;const s=new XRRay(this.options.offsetRay||{}),r={space:this.options.useReferenceSpace?i:this._xrSessionManager.viewerReferenceSpace,offsetRay:s};if(this.options.entityTypes&&(r.entityTypes=this.options.entityTypes),!r.space){Z.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(r).then(n=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=n})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new K,this.paused=!1,this.xrNativeFeatureName="hit-test",Z.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(s=>{const r=s.getPose(this._xrSessionManager.referenceSpace);if(!r)return;const n=r.transform.position,o=r.transform.orientation;this._tmpPos.set(n.x,n.y,n.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(o.x,o.y,o.z,o.w),L.FromFloat32ArrayToRefScaled(r.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:s};i.push(l)}),this.onHitTestResultObservable.notifyObservers(i)}}dp.Name=Vt.HIT_TEST;dp.Version=2;qi.AddWebXRFeature(dp.Name,(a,e)=>()=>new dp(a,e),dp.Version,!1);class fp extends nr{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new K,this.onFeaturePointsUpdatedObservable=new K,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,s=[],r=[];for(let n=0;n0&&this.onFeaturePointsAddedObservable.notifyObservers(r),s.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(s)}}_init(){!this._xrSessionManager.session.trySetFeaturePointCloudEnabled||!this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)||(this._enabled=!0)}}fp.Name=Vt.FEATURE_POINTS;fp.Version=1;qi.AddWebXRFeature(fp.Name,a=>()=>new fp(a),fp.Version);let qq=0;class pp extends nr{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onMeshUpdatedObservable=new K,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 s=new Set;this._detectedMeshes.forEach((r,n)=>{i.has(n)||s.add(n)}),s.forEach(r=>{const n=this._detectedMeshes.get(r);n&&(this.onMeshRemovedObservable.notifyObservers(n),this._detectedMeshes.delete(r))}),i.forEach(r=>{if(this._detectedMeshes.has(r)){if(r.lastChangedTime===this._xrSessionManager.currentTimestamp){const n=this._detectedMeshes.get(r);n&&(this._updateVertexDataWithXRMesh(r,n,e),this.onMeshUpdatedObservable.notifyObservers(n))}}else{const n={id:qq++,xrMesh:r},o=this._updateVertexDataWithXRMesh(r,n,e);this._detectedMeshes.set(r,o),this.onMeshAddedObservable.notifyObservers(o)}})}}catch(i){U.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 r;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let o=0;o()=>new pp(a,e),pp.Version,!1);var bo;(function(a){a[a.NotReceived=0]="NotReceived",a[a.Waiting=1]="Waiting",a[a.Received=2]="Received"})(bo||(bo={}));class _p extends nr{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new K,this.onTrackableImageFoundObservable=new K,this.onTrackedImageUpdatedObservable=new K,this._trackableScoreStatus=bo.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,s)=>({image:i,widthInMeters:this.options.images[s].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch{return Z.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===bo.Waiting)return;if(this._trackableScoreStatus===bo.NotReceived){this._checkScoresAsync();return}const t=e.getImageTrackingResults();for(const i of t){let s=!1;const r=i.index,n=this._trackedImages[r];if(!n)continue;n.xrTrackingResult=i,n.realWorldWidth!==i.measuredWidthInMeters&&(n.realWorldWidth=i.measuredWidthInMeters,s=!0);const o=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(o){const c=n.transformationMatrix;L.FromArrayToRef(o.transform.matrix,0,c),this._xrSessionManager.scene.useRightHandedSystem||c.toggleModelMatrixHandInPlace(),s=!0}const h=i.trackingState==="emulated";n.emulated!==h&&(n.emulated=h,s=!0),s&&this.onTrackedImageUpdatedObservable.notifyObservers(n)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==bo.NotReceived)return;this._trackableScoreStatus=bo.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||e.length===0){this._trackableScoreStatus=bo.NotReceived;return}for(let t=0;t0?bo.Received:bo.NotReceived}}_p.Name=Vt.IMAGE_TRACKING;_p.Version=1;qi.AddWebXRFeature(_p.Name,(a,e)=>()=>new _p(a,e),_p.Version,!1);class mp extends nr{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Z.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 Z.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 Z.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}}}}mp.Name=Vt.DOM_OVERLAY;mp.Version=1;qi.AddWebXRFeature(mp.Name,(a,e)=>()=>new mp(a,e),mp.Version,!1);class uh extends nr{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 ae,this._tmpRotationMatrix=L.Identity(),this._tmpTranslationDirection=new T,this._tmpMovementTranslation=new T,this._tempCacheQuaternion=new ae,this._attachController=i=>{if(this._controllers[i.uniqueId])return;this._controllers[i.uniqueId]={xrController:i,registeredComponents:[]};const s=this._controllers[i.uniqueId];if(s.xrController.inputSource.targetRayMode==="tracked-pointer"&&s.xrController.inputSource.gamepad){const r=()=>{if(i.motionController)for(const n of this._currentRegistrationConfigurations){let o=null;if(n.allowedComponentTypes)for(const h of n.allowedComponentTypes){const c=i.motionController.getComponentOfType(h);if(c!==null){o=c;break}}if(n.mainComponentOnly){const h=i.motionController.getMainComponent();if(h===null)continue;o=h}if(typeof n.componentSelectionPredicate=="function"&&(o=n.componentSelectionPredicate(i)),o&&n.forceHandedness&&i.inputSource.handedness!==n.forceHandedness||o===null)continue;const l={registrationConfiguration:n,component:o};s.registeredComponents.push(l),"axisChangedHandler"in n&&(l.onAxisChangedObserver=o.onAxisValueChangedObservable.add(h=>{n.axisChangedHandler(h,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in n&&(l.onButtonChangedObserver=o.onButtonStateChangedObservable.add(()=>{o.changes.pressed&&n.buttonChangedhandler(o.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};i.motionController?r():i.onMotionControllerInitObservable.addOnce(()=>{r()})}},!t||t.xrInput===void 0){Z.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=uh.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,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);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=i,ae.RotationYawPitchRollToRef(i,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(ae.RotationYawPitchRollToRef(i*3,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(L.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),T.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]}}}uh.Name=Vt.MOVEMENT;uh.REGISTRATIONS={default:[{allowedComponentTypes:[$n.THUMBSTICK_TYPE,$n.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(a,e,t)=>{e.rotateX=Math.abs(a.x)>t.rotationThreshold?a.x:0,e.rotateY=Math.abs(a.y)>t.rotationThreshold?a.y:0}},{allowedComponentTypes:[$n.THUMBSTICK_TYPE,$n.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(a,e,t)=>{e.moveX=Math.abs(a.x)>t.movementThreshold?a.x:0,e.moveY=Math.abs(a.y)>t.movementThreshold?a.y:0}}]};uh.Version=1;qi.AddWebXRFeature(uh.Name,(a,e)=>()=>new uh(a,e),uh.Version,!0);class gp extends nr{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=T.Up().negateInPlace(),this._lightColor=re.White(),this._intensity=1,this._sphericalHarmonics=new uc,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new K,this._updateReflectionCubeMap=()=>{var s;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const r=Date.now();if(r-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 ga("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new T(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=hi.FALLOFF_GLTF),this._hdrFilter=new tM(this._xrSessionManager.scene.getEngine()),Z.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 Kt(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 gp(a,e),gp.Version,!1);class xp extends nr{constructor(e){super(e),this.onEyeTrackingStartedObservable=new K,this.onEyeTrackingEndedObservable=new K,this.onEyeTrackingFrameUpdateObservable=new K,this._eyeTrackingStartListener=t=>{this._latestEyeSpace=t.gazeSpace,this._gazeRay=new Ct(T.Zero(),T.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;W.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?T.RightHandedForwardReadOnly.rotateByQuaternionToRef(W.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,W.Quaternion[0].z*=-1,W.Quaternion[0].w*=-1,T.LeftHandedForwardReadOnly.rotateByQuaternionToRef(W.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))}}xp.Name=Vt.EYE_TRACKING;xp.Version=1;qi.AddWebXRFeature(xp.Name,a=>()=>new xp(a),xp.Version,!1);class Qq{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 Zq{constructor(){this._samples=new Qq(20),this._entropy=0,this.onFirstStepDetected=new K}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=ce.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(l=A,o=y);if(on*this._squaredProjectionDistanceThreshold)return;const _=W.Vector3[0];_.set(i,s,0);const x=W.Vector3[1];x.set(c.x,c.y,0);const E=T.Cross(_,x).z>0,S=r.clone(),C=r.clone();h.subtractToRef(r,c),E?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,S),c.scaleAndAddToRef(this._axisToApexExtendFactor,C)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,S),c.scaleAndAddToRef(this._axisToApexShrinkFactor,C)),this.onFirstStepDetected.notifyObservers({leftApex:S,rightApex:C,currentPosition:r,currentStepDirection:E?"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 Tp{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new Zq,this._walker=null,this._movement=new ce,this._millisecondsSinceLastUpdate=Tp._MillisecondsPerUpdate,this.movementThisFrame=T.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(t=>{this._walker||(this._walker=new Jq(t.leftApex,t.rightApex,t.currentPosition,t.currentStepDirection),this._walker.onFootfall.add(()=>{U.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>=Tp._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=Tp._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 IE extends nr{static get Name(){return Vt.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 T,this._forward=new T,this._position=new T,this._movement=new T,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&U.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 Tp(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,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[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||T.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}qi.AddWebXRFeature(IE.Name,(a,e)=>()=>new IE(a,e),IE.Version,!1);class sO extends Nv{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class rO extends wv{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new K,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s=t=="right"?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||(i==null?void 0:i.textureWidth)!==r||(i==null?void 0:i.textureHeight)!==n){let o;const l=e.depthStencilTextureWidth??r,h=e.depthStencilTextureHeight??n;(r===l||n===h)&&(o=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,o,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_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,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return i?(this._setViewportForSubImage(e,i),!0):!1}}class e9 extends sO{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,s=>new t9(s,i,this)),this.layer=e}}class t9 extends rO{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 bR={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},i9={};class Ep extends nr{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={...bR,...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=i9){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Fv(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=bR,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new e9(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new sO(()=>n.width,()=>n.height,n,"XRQuadLayer",!1,h=>new rO(h,this._xrWebGLBinding,o));t&&this._compositionLayerTextureMapping.set(n,t);const l=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,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),s=i.layer,n={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)},o={x:0,y:0,z:0,w:1};s.transform=new XRRigidTransform(n,o);const l=this._layerToRTTProviderMapping.get(s);if(!l)throw new Error("Could not find the RTT provider for the layer");const h=this._xrSessionManager.scene.layers.find(c=>c.texture===e);if(!h)throw new Error("Could not find the babylon layer for the texture");return l.onRenderTargetTextureCreatedObservable.add(c=>{c.eye&&c.eye==="right"||(c.texture.clearColor=new Oe(0,0,0,0),h.renderTargetTextures.push(c.texture),h.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add(()=>{c.texture.render()}),h.renderTargetTextures.push(c.texture),h.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce(()=>{h.renderTargetTextures.splice(h.renderTargetTextures.indexOf(c.texture),1),h.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 r={x:0,y:0,z:-10},n={x:0,y:0,z:0,w:1};i.transform=new XRRigidTransform(r,n);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 Oe(0,0,0,0),l.texture.customRenderFunction=()=>{e.render()}}),this._xrSessionManager.onXRSessionInit.add(()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)}),this._xrSessionManager.onXRSessionEnded.add(()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)}),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map(i=>i.layer),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&typeof XRWebGLBinding<"u"&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new Ep(a,e),Ep.Version,!1);class Sp extends nr{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 $t(e,xt.Unknown);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 of(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 K,this.xrNativeFeatureName="depth-sensing",Z.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 s of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,s,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,s,this.depthDataFormat);break;default:Z.Error("Unknown depth usage"),this.detach();break}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{data:r,width:n,height:o,rawValueToMeters:l,getDepthInMeters:h}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=l,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(h.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=gs.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,X.NEAREST_SAMPLINGMODE,ee.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map(c=>c*l));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map(c=>c*l));break}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(s===null)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const l=this._xrSessionManager.scene,c=l.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=gs.CreateRTexture(null,n,o,l,!1,!0,X.NEAREST_SAMPLINGMODE,i==="ushort"?ee.TEXTURETYPE_UNSIGNED_BYTE:ee.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=c}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 s=this.options.usagePreference.map(n=>{switch(n){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),r=this.options.dataFormatPreference.map(n=>{switch(n){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:s,dataFormatPreference:r}})}else i({})})}}Sp.Name=Vt.DEPTH_SENSING;Sp.Version=1;qi.AddWebXRFeature(Sp.Name,(a,e)=>()=>new Sp(a,e),Sp.Version,!1);const s9="velocityPixelShader",r9=`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 +}`;j.ShadersStore[s9]=r9;const n9="velocityVertexShader",a9=`#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 +}`;j.ShadersStore[n9]=a9;class o9 extends Yi{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[L.Identity(),L.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 vn("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(r=>{this._previousWorldMatrices[r.uniqueId]=this._previousWorldMatrices[r.uniqueId]||r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[r.uniqueId]),this._previousWorldMatrices[r.uniqueId]=r.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(s=>{this._originalPairing.push([s,s.material]),s.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(s=>{s[0].material=s[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 l9{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,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new o9(s,r,this._scene,n),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return(!s||(i==null?void 0:i.textureWidth)!==r||(i==null?void 0:i.textureHeight)!=n)&&(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}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 vp extends nr{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[Vt.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 l9(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)}}vp.Name=Vt.SPACE_WARP;vp.Version=1;qi.AddWebXRFeature(vp.Name,a=>()=>new vp(a),vp.Version,!1);class Cp extends nr{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new K,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},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],l=i.height/2*s[5],h=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:l,gamma:h,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var s,r;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(s=this._glBinding)==null?void 0:s.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(r=this._cachedInternalTextures[t]._hardwareTexture)==null||r.set(i);else{const n=new $t(this._xrSessionManager.scene.getEngine(),xt.Unknown,!0);n.isCube=!0,n.invertY=!1,n.format=5,n.generateMipMaps=!0,n.type=1,n.samplingMode=3,n.width=e.camera.width,n.height=e.camera.height,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new of(i,this._glContext),this._cachedInternalTextures[t]=n;const o=new Kt(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 s=!0;i.views.forEach((r,n)=>{s=s&&this._updateInternalTextures(r,n)}),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}Cp.Name=Vt.RAW_CAMERA_ACCESS;Cp.Version=1;qi.AddWebXRFeature(Cp.Name,(a,e)=>()=>new Cp(a,e),Cp.Version,!1);class h9 extends _f{constructor(e,t,i){super(e,c9[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(){}}Js.RegisterController("generic-hand-select-grasp",(a,e)=>new h9(e,a.gamepad,a.handedness));const c9={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 dh extends _f{constructor(e,t,i){super(e,u9["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=dh.MODEL_LEFT_FILENAME:e=dh.MODEL_RIGHT_FILENAME;const i=dh.MODEL_BASE_URL+"default"+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=ft.IsPluginForExtensionAvailable(".glb");return e||U.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 s=this._mapping.buttons[t],r=s.rootNodeName;if(!r){U.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){U.Warn("Missing button mesh with name: "+r);return}if(s.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.valueNodeName),s.pressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.pressedNodeName),s.unpressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.unpressedNodeName),s.valueMesh&&s.pressedMesh&&s.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else U.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(s=>{if(!this.rootMesh)return;const r=this._mapping.axes[t][s],n=this._getChildByName(this.rootMesh,r.rootNodeName);if(!n){U.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=s==="x-axis"?o.x:o.y;this._lerpTransform(r,l,!0)},void 0,!0):U.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new q(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew dh(e,a.gamepad,a.handedness));const u9={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 ao extends _f{constructor(e,t,i,s=!1,r=!1){super(e,d9[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=ao.MODEL_LEFT_FILENAME:e=ao.MODEL_RIGHT_FILENAME;const t=this._isQuest()?ao.QUEST_MODEL_BASE_URL:ao.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(s=>{const r=s&&this.getComponent(s);r&&r.onButtonStateChangedObservable.add(n=>{if(!(!this.rootMesh||this.disableAnimation))switch(s){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-n.value*.2,this._modelRootNode.getChildren()[3].position.y=-n.value*.005,this._modelRootNode.getChildren()[3].position.z=-n.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new q(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=ae.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}}ao.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";ao.MODEL_LEFT_FILENAME="left.babylon";ao.MODEL_RIGHT_FILENAME="right.babylon";ao.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";Js.RegisterController("oculus-touch",(a,e)=>new ao(e,a.gamepad,a.handedness));Js.RegisterController("oculus-touch-legacy",(a,e)=>new ao(e,a.gamepad,a.handedness,!0));const d9={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 Du extends _f{constructor(e,t,i){super(e,f9[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=Du.MODEL_FILENAME,t=Du.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(s=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-s.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new q(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=ae.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}Du.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";Du.MODEL_FILENAME="wand.babylon";Js.RegisterController("htc-vive",(a,e)=>new Du(e,a.gamepad,a.handedness));const f9={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 p9{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 s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.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")}}g4("NativeXRFrame",p9);var Kn;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(Kn||(Kn={}));class oS{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=La(),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=Z.Instantiate(e.className),s=new i(e.name,e._connectionType,t);return s.deserialize(e),s}}class cs{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new cs(this.value+e.value)}subtract(e){return new cs(this.value-e.value)}multiply(e){return new cs(Math.imul(this.value,e.value))}divide(e){return new cs(this.value/e.value)}getClassName(){return cs.ClassName}equals(e){return this.value===e.value}static Parse(e){return new cs(e.value)}}cs.ClassName="FlowGraphInteger";H("FlowGraphInteger",cs);class An{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new An(e.typeName,e.defaultValue)}}const Fe=new An("any",void 0),_9=new An("string",""),vi=new An("number",0),fr=new An("boolean",!1),lS=new An("Vector2",ce.Zero()),Tl=new An("Vector3",T.Zero()),m9=new An("Vector4",tt.Zero()),fh=new An("Matrix",L.Identity()),g9=new An("Color3",re.Black()),x9=new An("Color4",new Oe(0,0,0,0)),T9=new An("Quaternion",ae.Identity()),us=new An("FlowGraphInteger",new cs(0));function E9(a){switch(typeof a){case"string":return _9;case"number":return vi;case"boolean":return fr;case"object":return a instanceof ce?lS:a instanceof T?Tl:a instanceof tt?m9:a instanceof re?g9:a instanceof Oe?x9:a instanceof ae?T9:a instanceof cs?us:Fe;default:return Fe}}class hS extends oS{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===Kn.Input}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===Kn.Output?(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=oS.Parse(e,t);return i.richType=An.Parse(e.richType),i}}H("FGDataConnection",hS);function nO(a){return a==="Mesh"||a==="AbstractMesh"||a==="GroundMesh"||a==="InstanceMesh"||a==="LinesMesh"||a==="GoldbergMesh"||a==="GreasedLineMesh"||a==="TrailMesh"}function aO(a){return a==="Vector2"||a==="Vector3"||a==="Vector4"||a==="Quaternion"||a==="Color3"||a==="Color4"}function S9(a,e){if(a==="Vector2")return ce.FromArray(e);if(a==="Vector3")return T.FromArray(e);if(a==="Vector4")return tt.FromArray(e);if(a==="Quaternion")return ae.FromArray(e);if(a==="Color3")return new re(e[0],e[1],e[2]);if(a==="Color4")return new Oe(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${a}`)}function MC(a,e,t){var s;const i=((s=e==null?void 0:e.getClassName)==null?void 0:s.call(e))??"";nO(i)?t[a]={name:e.name,className:i}:aO(i)?t[a]={value:e.asArray(),className:i}:t[a]=e}function wx(a,e,t){const i=e[a];let s;const r=i==null?void 0:i.className;return nO(r)?s=t.getMeshByName(i.name):aO(r)?s=S9(r,i.value):r==="Matrix"?s=L.FromArray(i.value):r===cs.ClassName?s=cs.Parse(i):i&&i.value!==void 0?s=i.value:s=i,s}function v9(a){return a==="FGSetPropertyBlock"||a==="FGGetPropertyBlock"||a==="FGPlayAnimationBlock"||a==="FGMeshPickEventBlock"}class Oh{constructor(e){var t;this.config=e,this.uniqueId=La(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new hS(e,Kn.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new hS(e,Kn.Output,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=MC){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 s={};i.serialize(s),e.dataInputs.push(s)}for(const i of this.dataOutputs){const s={};i.serialize(s),e.dataOutputs.push(s)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Z.Instantiate(e.className),s={},r=t.valueParseFunction??wx;if(e.config)for(const o in e.config)s[o]=r(o,e.config,t.scene);v9(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.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 n,o,l;r.type===Ke.POINTERPICK&&((n=r.pickInfo)!=null&&n.pickedMesh)&&(((o=r.pickInfo)==null?void 0:o.pickedMesh)===i||DC((l=r.pickInfo)==null?void 0:l.pickedMesh,i))&&this._execute(e)});const s=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return Nu.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}Nu.ClassName="FGMeshPickEventBlock";H(Nu.ClassName,Nu);var Qh;(function(a){a[a.Stopped=0]="Stopped",a[a.Started=1]="Started"})(Qh||(Qh={}));class wu{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=Qh.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){const e=new uS({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!==Qh.Started){this.state=Qh.Started,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()===Nu.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const r of s.dataInputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId));if(s instanceof ko)for(const r of s.signalOutputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const s={};i.serialize(s),e.allBlocks.push(s)}),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const s of i.dataOutputs)if(s.uniqueId===t)return s;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 ko){for(const s of i.signalInputs)if(s.uniqueId===t)return s}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??wx;for(const n of e.allBlocks){const o=Oh.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(o),o instanceof C_&&i.addEventBlock(o)}for(const n of s){for(const o of n.dataInputs)for(const l of o.connectedPointIds){const h=wu.GetDataOutConnectionByUniqueId(s,l);o.connectTo(h)}if(n instanceof ko)for(const o of n.signalOutputs)for(const l of o.connectedPointIds){const h=wu.GetSignalInConnectionByUniqueId(s,l);o.connectTo(h)}}for(const n of e.executionContexts)uS.Parse(n,{graph:i,valueParseFunction:r});return i}}class mu{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(mu.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new wu({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=mu.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 s={};i.serialize(s,t),e._flowGraphs.push(s)})}static Parse(e,t){var r;const i=t.valueParseFunction??wx,s=new mu({scene:t.scene});return(r=e._flowGraphs)==null||r.forEach(n=>{wu.Parse(n,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})}),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new K,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}mu.SceneCoordinators=new Map;class Ea extends ko{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Fu extends Ea{constructor(e){super(e),this.message=this.registerDataInput("message",Fe)}_execute(e){const t=this.message.getValue(e);U.Log(t),this.out._activateSignal(e)}getClassName(){return Fu.ClassName}}Fu.ClassName="FGConsoleLogBlock";H(Fu.ClassName,Fu);class Lu extends Ea{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Fe)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return Lu.ClassName}}Lu.ClassName="FGSetVariableBlock";H(Lu.ClassName,Lu);const yR=new RegExp(/\{(\w+)\}/g);class Ng{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=yR.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,us)),i=yR.exec(e)}}getAccessor(e,t){let i=this.path;for(const s of this.templatedInputs){const r=s.getValue(t).value;i=i.replace(`{${s.name}}`,r.toString())}return e.convert(i)}}class b_ extends Ea{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Fe),this.templateComponent=new Ng(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 b_.ClassName}}b_.ClassName="FGSetPropertyBlock";H("FGSetPropertyBlock",b_);class y_ extends Ea{constructor(e){super(e),this.config=e;for(let t=0;ts.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return y_.ClassName}}y_.ClassName="FGSendCustomEventBlock";H("FGSendCustomEventBlock",y_);class C9 extends ko{constructor(e){super(e),this.condition=this.registerDataInput("condition",fr),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"}}H("FGBranchBlock",C9);class Bu extends Ea{constructor(e={startIndex:new cs(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",us),this.value=this.registerDataOutput("value",us)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const n=s-(r-i);this.timeRemaining.setValue(n,e)}}getClassName(){return"FGThrottleBlock"}}H("FGThrottleBlock",y9);class A_ extends OC{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",vi)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new v5({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);s!==-1?i.splice(s,1):Z.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 A_.ClassName}}A_.ClassName="FGTimerBlock";H("FGTimerBlock",A_);class A9 extends ko{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",vi),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)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter(n=>n!==r),s.length===0)for(let n=0;n=0&&(i[s+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(s=>s)){this.out._activateSignal(e);for(let s=0;s=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}H("FGDebounceBlock",M9);class O9 extends ko{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",fr)}_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"}}H("FGFlipFlopBlock",O9);class Vu extends ko{constructor(e){super(e),this.config=e,this.outFlows=[];for(let t=0;tthis._onAnimationEnd(h,e));this.runningAnimatable.setValue(h,e),n.push(h)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);s!==-1&&i.splice(s,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 qp.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}qp.ClassName="FGPlayAnimationBlock";H(qp.ClassName,qp);class D9 extends Ea{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Fe)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}H("FGStopAnimationBlock",D9);class N9 extends Ea{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Fe)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}H("FGPauseAnimationBlock",N9);class w9 extends Oh{constructor(e){super(e),this.condition=this.registerDataInput("condition",fr),this.trueValue=this.registerDataInput("trueValue",Fe),this.falseValue=this.registerDataInput("falseValue",Fe),this.output=this.registerDataOutput("output",Fe)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}H("FGConditionalDataBlock",w9);class ku extends Oh{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Fe)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return ku.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}ku.ClassName="FGGetVariableBlock";H(ku.ClassName,ku);class F9 extends Oh{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Fe),this.destinationSystem=this.registerDataInput("destinationSystem",Fe),this.inputCoordinates=this.registerDataInput("inputCoordinates",Tl),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Tl)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=W.Matrix[0].copyFrom(n);o.invert();const l=W.Matrix[1];o.multiplyToRef(r,l);const h=this.outputCoordinates.getValue(e);T.TransformCoordinatesToRef(s,l,h)}getClassName(){return"FGCoordinateTransformBlock"}}H("FGCoordinateTransformBlock",F9);class L9 extends Oh{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",E9(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=MC){super.serialize(e),t("value",this.config.value,e.config)}}H("FGConstantBlock",L9);class Gu extends Oh{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Fe),this.templateComponent=new Ng(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 Gu.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Gu.ClassName="FGGetPropertyBlock";H(Gu.ClassName,Gu);const AR="cachedOperationValue",RR="cachedExecutionId";class Fx extends Oh{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,RR),i=e._getExecutionVariable(this,AR);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const s=this._doOperation(e);e._setExecutionVariable(this,AR,s),e._setExecutionVariable(this,RR,e.executionId),this.value.setValue(s,e)}}}class ys extends Fx{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,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 oi extends Fx{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const yf="FGLogic",oO="AndBlock",lO="OrBlock",hO="NotBlock";class B9 extends ys{constructor(e){super(fr,fr,fr,(t,i)=>t&&i,`${yf}${oO}`,e)}}H(`${yf}${oO}`,B9);class U9 extends ys{constructor(e){super(fr,fr,fr,(t,i)=>t||i,`${yf}${lO}`,e)}}H(`${yf}${lO}`,U9);class V9 extends oi{constructor(e){super(fr,fr,t=>!t,`${yf}${hO}`,e)}}H(`${yf}${hO}`,V9);class R_ extends Fx{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class NC extends Fx{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,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 Er(a){return a.getClassName?a.getClassName():""}function I_(a,e){return a==="Vector2"&&e==="Vector2"||a==="Vector3"&&e==="Vector3"||a==="Vector4"&&e==="Vector4"}function P_(a,e){return a==="Matrix"&&e==="Matrix"}function M_(a,e){return a==="FlowGraphInteger"&&e==="FlowGraphInteger"}class zu extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicAdd(t,i),zu.ClassName,e)}_polymorphicAdd(e,t){const i=Er(e),s=Er(t);return I_(i,s)||P_(i,s)||M_(i,s)?e.add(t):e+t}}zu.ClassName="FGAddBlock";H(zu.ClassName,zu);class Wu extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicAdd(t,i),Wu.ClassName,e)}_polymorphicAdd(e,t){const i=Er(e),s=Er(t);return I_(i,s)||M_(i,s)?e.subtract(t):P_(i,s)?e.add(t.scale(-1)):e-t}}Wu.ClassName="FGSubBlock";H(Wu.ClassName,Wu);class Hu extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicMultiply(t,i),Hu.ClassName,e)}_polymorphicMultiply(e,t){const i=Er(e),s=Er(t);return I_(i,s)||M_(i,s)?e.multiply(t):P_(i,s)?L.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}}Hu.ClassName="FGMultiplyBlock";H(Hu.ClassName,Hu);class Xu extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicDivide(t,i),Xu.ClassName,e)}_polymorphicDivide(e,t){const i=Er(e),s=Er(t);return I_(i,s)||M_(i,s)?e.divide(t):P_(i,s)?L.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}}Xu.ClassName="FGDivideBlock";H(Xu.ClassName,Xu);class Yu extends R_{constructor(e){super(vi,()=>Math.random(),Yu.ClassName,e)}}Yu.ClassName="FGRandomBlock";H(Yu.ClassName,Yu);class $u extends ys{constructor(e){super(Fe,Fe,vi,(t,i)=>this._polymorphicDot(t,i),$u.ClassName,e)}_polymorphicDot(e,t){switch(Er(e)){case"Vector2":return ce.Dot(e,t);case"Vector3":return T.Dot(e,t);case"Vector4":return tt.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}$u.ClassName="FGDotBlock";H($u.ClassName,$u);class Ku extends R_{constructor(e){super(vi,()=>Math.E,Ku.ClassName,e)}}Ku.ClassName="FGEBlock";H(Ku.ClassName,Ku);class ju extends R_{constructor(e){super(vi,()=>Math.PI,ju.ClassName,e)}}ju.ClassName="FGPIBlock";H(ju.ClassName,ju);class qu extends R_{constructor(e){super(vi,()=>Number.POSITIVE_INFINITY,qu.ClassName,e)}}qu.ClassName="FGInfBlock";H(qu.ClassName,qu);class Qu extends R_{constructor(e){super(vi,()=>Number.NaN,Qu.ClassName,e)}}Qu.ClassName="FGNaNBlock";H(Qu.ClassName,Qu);function ns(a,e){switch(Er(a)){case"FlowGraphInteger":return new cs(e(a.value));case"Vector2":return new ce(e(a.x),e(a.y));case"Vector3":return new T(e(a.x),e(a.y),e(a.z));case"Vector4":return new tt(e(a.x),e(a.y),e(a.z),e(a.w));case"Matrix":return L.FromValues(e(a.m[0]),e(a.m[4]),e(a.m[8]),e(a.m[12]),e(a.m[1]),e(a.m[5]),e(a.m[9]),e(a.m[13]),e(a.m[2]),e(a.m[6]),e(a.m[10]),e(a.m[14]),e(a.m[3]),e(a.m[7]),e(a.m[11]),e(a.m[15]));default:return e(a)}}class Zu extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicAbs(t),Zu.ClassName,e)}_polymorphicAbs(e){return ns(e,Math.abs)}}Zu.ClassName="FGAbsBlock";H(Zu.ClassName,Zu);class Ju extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicSign(t),Ju.ClassName,e)}_polymorphicSign(e){return ns(e,Math.sign)}}Ju.ClassName="FGSignBlock";H(Ju.ClassName,Ju);class ed extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicTrunc(t),ed.ClassName,e)}_polymorphicTrunc(e){return ns(e,Math.trunc)}}ed.ClassName="FGTruncBlock";H(ed.ClassName,ed);class td extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicFloor(t),td.ClassName,e)}_polymorphicFloor(e){return ns(e,Math.floor)}}td.ClassName="FGFloorBlock";H(td.ClassName,td);class id extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicCeiling(t),id.ClassName,e)}_polymorphicCeiling(e){return ns(e,Math.ceil)}}id.ClassName="FGCeilBlock";H(id.ClassName,id);class sd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicFract(t),sd.ClassName,e)}_polymorphicFract(e){return ns(e,t=>t-Math.floor(t))}}sd.ClassName="FGFractBlock";H(sd.ClassName,sd);class rd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicNeg(t),rd.ClassName,e)}_polymorphicNeg(e){return ns(e,t=>-t)}}rd.ClassName="FGNegBlock";H(rd.ClassName,rd);function O_(a,e,t){switch(Er(a)){case"FlowGraphInteger":return new cs(t(a.value,e.value));case"Vector2":return new ce(t(a.x,e.x),t(a.y,e.y));case"Vector3":return new T(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z));case"Vector4":return new tt(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z),t(a.w,e.w));case"Matrix":return L.FromValues(t(a.m[0],e.m[0]),t(a.m[4],e.m[4]),t(a.m[8],e.m[8]),t(a.m[12],e.m[12]),t(a.m[1],e.m[1]),t(a.m[5],e.m[5]),t(a.m[9],e.m[9]),t(a.m[13],e.m[13]),t(a.m[2],e.m[2]),t(a.m[6],e.m[6]),t(a.m[10],e.m[10]),t(a.m[14],e.m[14]),t(a.m[3],e.m[3]),t(a.m[7],e.m[7]),t(a.m[11],e.m[11]),t(a.m[15],e.m[15]));default:return t(a,e)}}class nd extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicRemainder(t,i),nd.ClassName,e)}_polymorphicRemainder(e,t){return O_(e,t,(i,s)=>i%s)}}nd.ClassName="FGRemainderBlock";H(nd.ClassName,nd);class ad extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicMin(t,i),ad.ClassName,e)}_polymorphicMin(e,t){return O_(e,t,Math.min)}}ad.ClassName="FGMinBlock";H(ad.ClassName,ad);class od extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicMax(t,i),od.ClassName,e)}_polymorphicMax(e,t){return O_(e,t,Math.max)}}od.ClassName="FGMaxBlock";H(od.ClassName,od);function k9(a,e,t){return Math.min(Math.max(a,Math.min(e,t)),Math.max(e,t))}function cO(a,e,t,i){switch(Er(a)){case"FlowGraphInteger":return new cs(i(a.value,e.value,t.value));case"Vector2":return new ce(i(a.x,e.x,t.x),i(a.y,e.y,t.y));case"Vector3":return new T(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z));case"Vector4":return new tt(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z),i(a.w,e.w,t.w));case"Matrix":return L.FromValues(i(a.m[0],e.m[0],t.m[0]),i(a.m[4],e.m[4],t.m[4]),i(a.m[8],e.m[8],t.m[8]),i(a.m[12],e.m[12],t.m[12]),i(a.m[1],e.m[1],t.m[1]),i(a.m[5],e.m[5],t.m[5]),i(a.m[9],e.m[9],t.m[9]),i(a.m[13],e.m[13],t.m[13]),i(a.m[2],e.m[2],t.m[2]),i(a.m[6],e.m[6],t.m[6]),i(a.m[10],e.m[10],t.m[10]),i(a.m[14],e.m[14],t.m[14]),i(a.m[3],e.m[3],t.m[3]),i(a.m[7],e.m[7],t.m[7]),i(a.m[11],e.m[11],t.m[11]),i(a.m[15],e.m[15],t.m[15]));default:return i(a,e,t)}}class ld extends NC{constructor(e){super(Fe,Fe,Fe,Fe,(t,i,s)=>this._polymorphicClamp(t,i,s),ld.ClassName,e)}_polymorphicClamp(e,t,i){return cO(e,t,i,k9)}}ld.ClassName="FGClampBlock";H(ld.ClassName,ld);function G9(a){return Math.min(Math.max(a,0),1)}class hd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicSaturate(t),hd.ClassName,e)}_polymorphicSaturate(e){return ns(e,G9)}}hd.ClassName="FGSaturateBlock";H(hd.ClassName,hd);class cd extends NC{constructor(e){super(Fe,Fe,Fe,Fe,(t,i,s)=>this._polymorphicInterpolate(t,i,s),cd.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return cO(e,t,i,this._interpolate)}}cd.ClassName="FGInterpolateBlock";H(cd.ClassName,cd);class ud extends ys{constructor(e){super(Fe,Fe,fr,(t,i)=>this._polymorphicEq(t,i),ud.ClassName,e)}_polymorphicEq(e,t){const i=Er(e),s=Er(t);return I_(i,s)||P_(i,s)||M_(i,s)?e.equals(t):e===t}}ud.ClassName="FGEqBlock";H(ud.ClassName,ud);function Lx(a,e,t){const i=Er(a),s=Er(e);if(i===s){if(i==="")return t(a,e);if(i==="FlowGraphInteger")return t(a.value,e.value);throw new Error(`Cannot compare ${a} and ${e}`)}throw new Error(`${a} and ${e} are of different types.`)}class dd extends ys{constructor(e){super(Fe,Fe,fr,(t,i)=>this._polymorphicLessThan(t,i),dd.ClassName,e)}_polymorphicLessThan(e,t){return Lx(e,t,(i,s)=>ithis._polymorphicLessThanOrEqual(t,i),Bx.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return Lx(e,t,(i,s)=>i<=s)}}Bx.ClassName="FGLessThanOrEqualBlock";class fd extends ys{constructor(e){super(Fe,Fe,fr,(t,i)=>this._polymorphicGreaterThan(t,i),fd.ClassName,e)}_polymorphicGreaterThan(e,t){return Lx(e,t,(i,s)=>i>s)}}fd.ClassName="FGGreaterThanBlock";H(fd.ClassName,fd);class pd extends ys{constructor(e){super(Fe,Fe,fr,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),pd.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return Lx(e,t,(i,s)=>i>=s)}}pd.ClassName="FGGreaterThanOrEqualBlock";H(pd.ClassName,pd);class _d extends oi{constructor(e){super(Fe,fr,t=>this._polymorphicIsNan(t),_d.ClassName,e)}_polymorphicIsNan(e){const t=Er(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}_d.ClassName="FGIsNanBlock";H(_d.ClassName,_d);class Ux extends oi{constructor(e){super(Fe,fr,t=>this._polymorphicIsInf(t),Ux.ClassName,e)}_polymorphicIsInf(e){const t=Er(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Ux.ClassName="FGIsInfBlock";class md extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicDegToRad(t),md.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return ns(e,this._degToRad)}}md.ClassName="FGDegToRadBlock";H(md.ClassName,md);class gd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicRadToDeg(t),gd.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return ns(e,this._radToDeg)}}gd.ClassName="FGRadToDegBlock";H(gd.ClassName,gd);class xd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicSin(t),xd.ClassName,e)}_polymorphicSin(e){return ns(e,Math.sin)}}xd.ClassName="FGSinBlock";H(xd.ClassName,xd);class Td extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicCos(t),Td.ClassName,e)}_polymorphicCos(e){return ns(e,Math.cos)}}Td.ClassName="FGCosBlock";H(Td.ClassName,Td);class Ed extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicTan(t),Ed.ClassName,e)}_polymorphicTan(e){return ns(e,Math.tan)}}Ed.ClassName="FGTanBlock";H(Ed.ClassName,Ed);class Sd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicAsin(t),Sd.ClassName,e)}_polymorphicAsin(e){return ns(e,Math.asin)}}Sd.ClassName="FGAsinBlock";H(Sd.ClassName,Sd);class vd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicAcos(t),vd.ClassName,e)}_polymorphicAcos(e){return ns(e,Math.acos)}}vd.ClassName="FGAcosBlock";H(vd.ClassName,vd);class Cd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicAtan(t),Cd.ClassName,e)}_polymorphicAtan(e){return ns(e,Math.atan)}}Cd.ClassName="FGAtanBlock";H(Cd.ClassName,Cd);class bd extends ys{constructor(e){super(Fe,Fe,Fe,(t,i)=>this._polymorphicAtan2(t,i),bd.ClassName,e)}_polymorphicAtan2(e,t){return O_(e,t,Math.atan2)}}bd.ClassName="FGAtan2Block";H(bd.ClassName,bd);class yd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicSinh(t),yd.ClassName,e)}_polymorphicSinh(e){return ns(e,Math.sinh)}}yd.ClassName="FGSinhBlock";H(yd.ClassName,yd);class Ad extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicCosh(t),Ad.ClassName,e)}_polymorphicCosh(e){return ns(e,Math.cosh)}}Ad.ClassName="FGCoshBlock";H(Ad.ClassName,Ad);class Rd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicTanh(t),Rd.ClassName,e)}_polymorphicTanh(e){return ns(e,Math.tanh)}}Rd.ClassName="FGTanhBlock";H(Rd.ClassName,Rd);class Id extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicAsinh(t),Id.ClassName,e)}_polymorphicAsinh(e){return ns(e,Math.asinh)}}Id.ClassName="FGAsinhBlock";H(Id.ClassName,Id);class Pd extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicAcosh(t),Pd.ClassName,e)}_polymorphicAcosh(e){return ns(e,Math.acosh)}}Pd.ClassName="FGAcoshBlock";H(Pd.ClassName,Pd);class Md extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicAtanh(t),Md.ClassName,e)}_polymorphicAtanh(e){return ns(e,Math.atanh)}}Md.ClassName="FGAtanhBlock";H(Md.ClassName,Md);class Od extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicExp(t),Od.ClassName,e)}_polymorphicExp(e){return ns(e,Math.exp)}}Od.ClassName="FGExpBlock";H(Od.ClassName,Od);class Dd extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicLog(t),Dd.ClassName,e)}_polymorphicLog(e){return ns(e,Math.log)}}Dd.ClassName="FGLogBlock";H(Dd.ClassName,Dd);class Nd extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicLog2(t),Nd.ClassName,e)}_polymorphicLog2(e){return ns(e,Math.log2)}}Nd.ClassName="FGLog2Block";H(Nd.ClassName,Nd);class wd extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicLog10(t),wd.ClassName,e)}_polymorphicLog10(e){return ns(e,Math.log10)}}wd.ClassName="FGLog10Block";H(wd.ClassName,wd);class Fd extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicSqrt(t),Fd.ClassName,e)}_polymorphicSqrt(e){return ns(e,Math.sqrt)}}Fd.ClassName="FGSqrtBlock";H(Fd.ClassName,Fd);class Ld extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicCubeRoot(t),Ld.ClassName,e)}_polymorphicCubeRoot(e){return ns(e,Math.cbrt)}}Ld.ClassName="FGCubeRootBlock";H(Ld.ClassName,Ld);class Bd extends ys{constructor(e){super(Fe,vi,vi,(t,i)=>this._polymorphicPow(t,i),Bd.ClassName,e)}_polymorphicPow(e,t){return O_(e,t,Math.pow)}}Bd.ClassName="FGPowBlock";H(Bd.ClassName,Bd);class Ud extends oi{constructor(e){super(Fe,vi,t=>this._polymorphicLength(t),Ud.ClassName,e)}_polymorphicLength(e){switch(Er(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}Ud.ClassName="FGLengthBlock";H(Ud.ClassName,Ud);class Vd extends oi{constructor(e){super(Fe,Fe,t=>this._polymorphicNormalize(t),Vd.ClassName,e)}_polymorphicNormalize(e){switch(Er(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Vd.ClassName="FGNormalizeBlock";H(Vd.ClassName,Vd);class kd extends ys{constructor(e){super(Tl,Tl,Tl,(t,i)=>T.Cross(t,i),kd.ClassName,e)}}kd.ClassName="FGCrossBlock";H(kd.ClassName,kd);class Gd extends ys{constructor(e){super(lS,vi,lS,(t,i)=>ce.Transform(t,L.RotationZ(i)),Gd.ClassName,e)}}Gd.ClassName="FGRotate2DBlock";H(Gd.ClassName,Gd);class zd extends NC{constructor(e){super(Tl,Tl,vi,Tl,(t,i,s)=>T.TransformCoordinates(t,L.RotationAxis(i,s)),zd.ClassName,e)}}zd.ClassName="FGRotate3DBlock";H(zd.ClassName,zd);class Wd extends oi{constructor(e){super(fh,fh,t=>L.Transpose(t),Wd.ClassName,e)}}Wd.ClassName="FGTransposeBlock";H(Wd.ClassName,Wd);class Hd extends oi{constructor(e){super(fh,vi,t=>t.determinant(),Hd.ClassName,e)}}Hd.ClassName="FGDeterminantBlock";H(Hd.ClassName,Hd);class Xd extends oi{constructor(e){super(fh,fh,t=>L.Invert(t),Xd.ClassName,e)}}Xd.ClassName="FGInvertMatrixBlock";H(Xd.ClassName,Xd);class Yd extends ys{constructor(e){super(fh,fh,fh,(t,i)=>i.multiply(t),Yd.ClassName,e)}}Yd.ClassName="FGMatMulBlock";H(Yd.ClassName,Yd);class $d extends oi{constructor(e){super(us,us,t=>new cs(~t.value),$d.ClassName,e)}}$d.ClassName="FGBitwiseNotBlock";H($d.ClassName,$d);class Kd extends ys{constructor(e){super(us,us,us,(t,i)=>new cs(t.value&i.value),Kd.ClassName,e)}}Kd.ClassName="FGBitwiseAndBlock";H(Kd.ClassName,Kd);class jd extends ys{constructor(e){super(us,us,us,(t,i)=>new cs(t.value|i.value),jd.ClassName,e)}}jd.ClassName="FGBitwiseOrBlock";H(jd.ClassName,jd);class qd extends ys{constructor(e){super(us,us,us,(t,i)=>new cs(t.value^i.value),qd.ClassName,e)}}qd.ClassName="FGBitwiseXorBlock";H(qd.ClassName,qd);class Qd extends ys{constructor(e){super(us,us,us,(t,i)=>new cs(t.value<new cs(t.value>>i.value),Zd.ClassName,e)}}Zd.ClassName="FGBitwiseRightShiftBlock";H(Zd.ClassName,Zd);class Jd extends oi{constructor(e){super(us,us,t=>new cs(Math.clz32(t.value)),Jd.ClassName,e)}}Jd.ClassName="FGCountLeadingZerosBlock";H(Jd.ClassName,Jd);class ef extends oi{constructor(e){super(us,us,t=>new cs(t.value?31-Math.clz32(t.value&-t.value):32),ef.ClassName,e)}}ef.ClassName="FGCountTrailingZerosBlock";H(ef.ClassName,ef);function z9(a){let e=0;for(;a;)e+=a&1,a>>=1;return e}class tf extends oi{constructor(e){super(us,us,t=>new cs(z9(t.value)),tf.ClassName,e)}}tf.ClassName="FGCountOneBitsBlock";H(tf.ClassName,tf);class D_ extends C_{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return D_.ClassName}}D_.ClassName="FGSceneReadyEventBlock";H("FGSceneReadyEventBlock",D_);class sf extends C_{constructor(e){super(e),this.config=e;for(let t=0;t{for(let s=0;s{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 rf.ClassName}}rf.ClassName="FGSceneTickEventBlock";H(rf.ClassName,rf);function dS(a,e,t,i){const s={externalResourceFunction:i};return t&&(s.uri=e==="file:"?t:e+t),ArrayBuffer.isView(a)?GLTFValidator.validateBytes(a,s):GLTFValidator.validateString(a,s)}function W9(){const a=[];onmessage=e=>{const t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{dS(t.data,t.rootUrl,t.fileName,i=>new Promise((s,r)=>{const n=a.length;a.push({resolve:s,reject:r}),postMessage({id:"getExternalResource",index:n,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{a[t.index].resolve(t.value);break}case"getExternalResource.reject":{a[t.index].reject(t.reason);break}}}}class uO{static ValidateAsync(e,t,i,s){return typeof Worker=="function"?new Promise((r,n)=>{const o=`${dS}(${W9})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),h=new Worker(l),c=d=>{h.removeEventListener("error",c),h.removeEventListener("message",u),n(d)},u=d=>{const f=d.data;switch(f.id){case"getExternalResource":{s(f.uri).then(m=>{h.postMessage({id:"getExternalResource.resolve",index:f.index,value:m},[m.buffer])},m=>{h.postMessage({id:"getExternalResource.reject",index:f.index,reason:m})});break}case"validate.resolve":{h.removeEventListener("error",c),h.removeEventListener("message",u),r(f.value),h.terminate();break}case"validate.reject":h.removeEventListener("error",c),h.removeEventListener("message",u),n(f.reason),h.terminate()}};if(h.addEventListener("error",c),h.addEventListener("message",u),h.postMessage({id:"init",url:Z.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const d=e.slice();h.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else h.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=Z.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>dS(e,t,i,s)))}}uO.Configuration={url:`${Z._DefaultCdnUrl}/gltf_validator.js`};function IR(a,e,t){try{return Promise.resolve(new Uint8Array(a,e,t))}catch(i){return Promise.reject(i)}}function H9(a,e,t){try{if(e<0||e>=a.byteLength)throw new RangeError("Offset is out of range.");if(e+t>a.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(a.buffer,a.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var Qp;(function(a){a[a.AUTO=0]="AUTO",a[a.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(Qp||(Qp={}));var gu;(function(a){a[a.NONE=0]="NONE",a[a.FIRST=1]="FIRST",a[a.ALL=2]="ALL"})(gu||(gu={}));var Bn;(function(a){a[a.LOADING=0]="LOADING",a[a.READY=1]="READY",a[a.COMPLETE=2]="COMPLETE"})(Bn||(Bn={}));class is{constructor(){this.onParsedObservable=new K,this.coordinateSystemMode=Qp.AUTO,this.animationStartMode=gu.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new K,this.onSkinLoadedObservable=new K,this.onTextureLoadedObservable=new K,this.onMaterialLoadedObservable=new K,this.onCameraLoadedObservable=new K,this.onCompleteObservable=new K,this.onErrorObservable=new K,this.onDisposeObservable=new K,this.onExtensionLoadedObservable=new K,this.validate=!1,this.onValidatedObservable=new K,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new K,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,l),null;this._progressCallback=r;const h=t.name||Z.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&U.Warn("glTF validation is not supported when range requests are enabled");const c={abort:()=>{},onCompleteObservable:new K},u={readAsync:(d,f)=>new Promise((m,_)=>{this._loadFile(e,t,x=>{m(new Uint8Array(x))},!0,x=>{_(x)},x=>{x.setRequestHeader("Range",`bytes=${d}-${d+f-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new Gm(u)).then(d=>{c.onCompleteObservable.notifyObservers(c),s(d)},o?d=>o(void 0,d):void 0),c}return this._loadFile(e,t,c=>{this._validate(e,new Uint8Array(c,0,c.byteLength),i,h),this._unpackBinaryAsync(new Gm({readAsync:(u,d)=>IR(c,u,d),byteLength:c.byteLength})).then(u=>{s(u)},o?u=>o(void 0,u):void 0)},!0,o)}else return this._loadFile(e,t,c=>{this._validate(e,c,i,h),s({json:this._parseJson(c)})},!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new Gm({readAsync:(o,l)=>H9(t,o,l),byteLength:t.byteLength})).then(o=>{s(o)},r?o=>r(void 0,o):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n)))}loadAsync(e,t,i,s,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r)))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new Kg(e),o=[];this.onMaterialLoadedObservable.add(u=>{o.push(u)});const l=[];this.onTextureLoadedObservable.add(u=>{l.push(u)});const h=[];this.onCameraLoadedObservable.add(u=>{h.push(u)});const c=[];return this.onMeshLoadedObservable.add(u=>{u.morphTargetManager&&c.push(u.morphTargetManager)}),this._loader.importMeshAsync(null,e,n,t,i,s,r).then(u=>(Array.prototype.push.apply(n.geometries,u.geometries),Array.prototype.push.apply(n.meshes,u.meshes),Array.prototype.push.apply(n.particleSystems,u.particleSystems),Array.prototype.push.apply(n.skeletons,u.skeletons),Array.prototype.push.apply(n.animationGroups,u.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,l),Array.prototype.push.apply(n.lights,u.lights),Array.prototype.push.apply(n.transformNodes,u.transformNodes),Array.prototype.push.apply(n.cameras,h),Array.prototype.push.apply(n.morphTargetManagers,c),n))})}canDirectLoad(e){return e.indexOf("asset")!==-1&&e.indexOf("version")!==-1||e.startsWith("data:base64,"+is._MagicBase64Encoded)||e.startsWith("data:;base64,"+is._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+is._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+is._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+is._MagicBase64Encoded)||t.startsWith(";base64,"+is._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+is._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+is._MagicBase64Encoded)){const i=n_(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new Gm({readAsync:(s,r)=>IR(i,s,r),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new is}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(Bn[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,s,r,n);return o.onCompleteObservable.add(l=>{this._requests.splice(this._requests.indexOf(l),1)}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const n of this._requests){if(n._lengthComputable===void 0||n._loaded===void 0||n._total===void 0)return;i=i&&n._lengthComputable,s+=n._loaded,r+=n._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),uO.ValidateAsync(t,i,s,r=>this.preprocessUrlAsync(i+r).then(n=>e._loadFileAsync(n,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(r=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(r),this.onValidatedObservable.clear()},r=>{this._endPerformanceCounter("Validate JSON"),Z.Warn(`Failed to validate: ${r.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=is._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){const n=is._parseVersion(t.minVersion);if(!n)throw new Error("Invalid minimum version: "+t.minVersion);if(is._compareVersion(n,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const r={1:is._CreateGLTF1Loader,2:is._CreateGLTF2Loader}[i.major];if(!r)throw new Error("Unsupported version: "+t.version);return r(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new oo("Unexpected magic: "+i,ml.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const r=e.readUint32();!this.useRangeRequests&&r!==e.buffer.byteLength&&U.Warn(`Length in header does not match actual data length: ${r} != ${e.buffer.byteLength}`);let n;switch(s){case 1:{n=this._unpackBinaryV1Async(e,r);break}case 2:{n=this._unpackBinaryV2Async(e,r);break}default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),n})}_unpackBinaryV1Async(e,t){const i={JSON:0},s=e.readUint32(),r=e.readUint32();if(r!==i.JSON)throw new Error(`Unexpected content format: ${r}`);const n=t-e.byteOffset,o={json:this._parseJson(e.readString(s)),bin:null};if(n!==0){const l=e.byteOffset;o.bin={readAsync:(h,c)=>e.buffer.readAsync(l+h,c),byteLength:n}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){const i={JSON:1313821514,BIN:5130562},s=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then(()=>({json:this._parseJson(e.readString(s)),bin:null})):e.loadAsync(s+8).then(()=>{const n={json:this._parseJson(e.readString(s)),bin:null},o=()=>{const l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{const c=e.byteOffset;n.bin={readAsync:(u,d)=>e.buffer.readAsync(c+u,d),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(n)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case rh.BYTE:return new Int8Array(o,i,s);case rh.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case rh.SHORT:return new Int16Array(o,i,s);case rh.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*er.GetByteStrideFromType(t);return er.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const dO=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],fO=["world","view","projection","worldView","worldViewProjection","mBones"],X9=["translation","rotation","scale"],Y9=["position","rotationQuaternion","scaling"],$9=(a,e)=>{for(const t in a){const i=a[t];e.buffers[t]=i,e.buffersCount++}},K9=(a,e)=>{for(const t in a){const i=a[t];e.shaders[t]=i,e.shaderscount++}},Jr=(a,e,t)=>{for(const i in a){const s=a[i];t[e][i]=s}},j9=a=>{if(a)for(let e=0;e{if(a.semantic==="NORMAL")return"normal";if(a.semantic==="POSITION")return"position";if(a.semantic==="JOINT")return"matricesIndices";if(a.semantic==="WEIGHT")return"matricesWeights";if(a.semantic==="COLOR")return"color";if(a.semantic&&a.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(a.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},q9=a=>{for(const e in a.animations){const t=a.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let s=0;s{let e=null;if(a.translation||a.rotation||a.scale){const t=T.FromArray(a.scale||[1,1,1]),i=ae.FromArray(a.rotation||[0,0,0,1]),s=T.FromArray(a.translation||[0,0,0]);e=L.Compose(t,i,s)}else e=L.FromArray(a.matrix);return e},pO=(a,e,t,i)=>{for(let r=0;r{for(let t=0;t{const t=a.nodes;let i=t[e];if(i)return{node:i,id:e};for(const s in t)if(i=t[s],i.jointName===e)return{node:i,id:s};return null},Z9=(a,e)=>{for(let t=0;t{for(const s in a.nodes){const r=a.nodes[s],n=s;if(!r.jointName||Z9(t,r.jointName))continue;const o=wC(r),l=new mi(r.name||"",e,null,o);l.id=n,i.push({bone:l,node:r,id:n})}for(let s=0;s{if(i||(i=new gh(e.name||"","",a.scene)),!e.babylonSkeleton)return i;const s=[],r=[];J9(a,i,e,s),i.bones=[];for(let o=0;o0&&(f=Q9(s,c),f&&r.indexOf(f)===-1&&r.push(f));const _=new mi(h.jointName||"",i,f,m);_.id=c}const n=i.bones;i.bones=[];for(let o=0;o{if(s||(a.scene._blockEntityCollection=!!a.assetContainer,s=new q(e.name||"",a.scene),s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const o=[],l=[],h=[],c=[];for(let f=0;f1?(u=new Sl("multimat"+i,a.scene),u.subMaterials=r):u=new Ie("multimat"+i,a.scene),r.length===1&&(u=r[0]),u._parentContainer=a.assetContainer,s.material||(s.material=u),new Is(i,a.scene,n,!1,s),s.computeWorldMatrix(!0),a.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let f=0;f{a.position&&(a.position=e),(a.rotationQuaternion||a.rotation)&&(a.rotationQuaternion=t),a.scaling&&(a.scaling=i)},tQ=(a,e)=>{if(e.matrix){const t=new T(0,0,0),i=new ae,s=new T(0,0,0);L.FromArray(e.matrix).decompose(s,i,t),_S(a,t,i,s)}else e.translation&&e.rotation&&e.scale&&_S(a,T.FromArray(e.translation),ae.FromArray(e.rotation),T.FromArray(e.scale));a.computeWorldMatrix(!0)},iQ=(a,e,t)=>{let i=null;if(a.importOnlyMeshes&&(e.skin||e.meshes)&&a.importMeshesNames&&a.importMeshesNames.length>0&&a.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=a.skins[e.skin],r=DR(a,e,e.meshes,t,e.babylonNode);r.skeleton=a.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=eQ(a,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=DR(a,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Rh(e.light,T.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=re.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new ga(e.light,T.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=re.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new mf(e.light,T.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=re.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new Cn(e.light,T.Zero(),T.Zero(),0,0,a.scene);n.name=e.name||"",r.color&&(n.diffuse=re.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.cameras[e.camera];if(s){if(a.scene._blockEntityCollection=!!a.assetContainer,s.type==="orthographic"){const r=new ln(e.camera,T.Zero(),a.scene,!1);r.name=e.name||"",r.mode=Ve.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=a.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new ln(e.camera,T.Zero(),a.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=a.scene.getEngine().getRenderWidth()/a.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=a.assetContainer}a.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){a.scene._blockEntityCollection=!!a.assetContainer;const s=new q(e.name||"",a.scene);s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof q)tQ(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];_S(i,T.FromArray(s),ae.FromArray(r),T.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},Zp=(a,e,t,i=!1)=>{const s=a.nodes[e];let r=null;if(a.importOnlyMeshes&&!i&&a.importMeshesNames?a.importMeshesNames.indexOf(s.name||"")!==-1||a.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=iQ(a,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n{let e=a.currentScene;if(e)for(let t=0;t{const o=r.values||s.parameters;for(const l in t){const h=t[l],c=h.type;if(c===xn.FLOAT_MAT2||c===xn.FLOAT_MAT3||c===xn.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)er.SetMatrix(e.scene,a,h,l,i.getEffect());else if(h.semantic&&(h.source||h.node)){let u=e.scene.getNodeByName(h.source||h.node||"");if(u===null&&(u=e.scene.getNodeById(h.source||h.node||"")),u===null)continue;er.SetMatrix(e.scene,u,h,l,i.getEffect())}}else{const u=o[s.uniforms[l]];if(!u)continue;if(c===xn.SAMPLER_2D){const d=e.textures[r.values?u:h.value].babylonTexture;if(d==null)continue;i.getEffect().setTexture(l,d)}else er.SetUniform(i.getEffect(),l,u,c)}}n(i)},rQ=(a,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const o in s){const l=s[o],h=l.type;let c=r[n[o]];if(c===void 0&&(c=l.value),!c)continue;const u=d=>f=>{l.value&&d&&(e.setTexture(d,f),delete s[d])};h===xn.SAMPLER_2D?Mr.LoadTextureAsync(a,i.values?c:l.value,u(o),()=>u(null)):l.value&&er.SetUniform(e,o,i.values?c:l.value,h)&&delete s[o]}},nQ=(a,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+a.name+". Error: "+s+". Default material will be applied")},aQ=(a,e,t,i,s,r)=>n=>{rQ(a,e,t,i,s),e.onBind=o=>{sQ(o,a,s,e,t,i,r)}},wR=(a,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(a.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=dO.indexOf(r.semantic);if(n!==-1)return delete t[i],fO[n]}}return a.currentIdentifier},FR=a=>{for(const e in a.materials)Mr.LoadMaterialAsync(a,e,()=>{},()=>{})};class hl{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&Jr(e.extensions,"extensions",s),e.extensionsUsed&&Jr(e.extensionsUsed,"extensionsUsed",s),e.buffers&&$9(e.buffers,s),e.bufferViews&&Jr(e.bufferViews,"bufferViews",s),e.accessors&&Jr(e.accessors,"accessors",s),e.meshes&&Jr(e.meshes,"meshes",s),e.lights&&Jr(e.lights,"lights",s),e.cameras&&Jr(e.cameras,"cameras",s),e.nodes&&Jr(e.nodes,"nodes",s),e.images&&Jr(e.images,"images",s),e.textures&&Jr(e.textures,"textures",s),e.shaders&&K9(e.shaders,s),e.programs&&Jr(e.programs,"programs",s),e.samplers&&Jr(e.samplers,"samplers",s),e.techniques&&Jr(e.techniques,"techniques",s),e.materials&&Jr(e.materials,"materials",s),e.animations&&Jr(e.animations,"animations",s),e.skins&&Jr(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];Z.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(Z.DecodeBase64(n.uri)))):Z.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),r,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source){s("");return}if(r.babylonTexture){i(null);return}const n=e.images[r.source];Z.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(Z.DecodeBase64(n.uri)))):Z.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),void 0,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture){s(r.babylonTexture);return}const n=e.samplers[r.sampler],o=n.minFilter===so.NEAREST_MIPMAP_NEAREST||n.minFilter===so.NEAREST_MIPMAP_LINEAR||n.minFilter===so.LINEAR_MIPMAP_NEAREST||n.minFilter===so.LINEAR_MIPMAP_LINEAR,l=X.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),d=new X(c,e.scene,!o,!0,l,u,u);n.wrapS!==void 0&&(d.wrapU=er.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(d.wrapV=er.GetWrapMode(n.wrapT)),d.name=t,r.babylonTexture=d,s(d)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(Z.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else Z.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,n=>{n&&s&&s(n.status+" "+n.statusText)})}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique){s&&s("No technique found.");return}const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const I=new Ie(t,e.scene);I._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,I.diffuseColor=new re(.5,.5,.5),I.sideOrientation=pe.CounterClockWiseSideOrientation,i(I);return}const o=e.programs[n.program],l=n.states,h=ri.ShadersStore[o.vertexShader+"VertexShader"],c=ri.ShadersStore[o.fragmentShader+"PixelShader"];let u="",d="";const f=new MR(h),m=new MR(c),_={},x=[],E=[],S=[];for(const I in n.uniforms){const R=n.uniforms[I],N=n.parameters[R];if(_[I]=N,N.semantic&&!N.node&&!N.source){const k=dO.indexOf(N.semantic);k!==-1?(x.push(fO[k]),delete _[I]):x.push(I)}else N.type===xn.SAMPLER_2D?S.push(I):x.push(I)}for(const I in n.attributes){const R=n.attributes[I],N=n.parameters[R];if(N.semantic){const k=OR(N);k&&E.push(k)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==nh.IDENTIFIER){u+=f.currentString;continue}let R=!1;for(const N in n.attributes){const k=n.attributes[N],B=n.parameters[k];if(f.currentIdentifier===N&&B.semantic){u+=OR(B),R=!0;break}}R||(u+=wR(f,n,_))}for(;!m.isEnd()&&m.getNextToken();){if(m.currentToken!==nh.IDENTIFIER){d+=m.currentString;continue}d+=wR(m,n,_)}const C={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},y={attributes:E,uniforms:x,samplers:S,needAlphaBlending:l&&l.enable&&l.enable.indexOf(3042)!==-1};ri.ShadersStore[o.vertexShader+t+"VertexShader"]=u,ri.ShadersStore[o.fragmentShader+t+"PixelShader"]=d;const A=new vn(t,e.scene,C,y);if(A.onError=nQ(o,A,s),A.onCompiled=aQ(e,A,n,r,_,i),A.sideOrientation=pe.CounterClockWiseSideOrientation,l&&l.functions){const I=l.functions;I.cullFace&&I.cullFace[0]!==pS.BACK&&(A.backFaceCulling=!1);const R=I.blendFuncSeparate;R&&(R[0]===_s.SRC_ALPHA&&R[1]===_s.ONE_MINUS_SRC_ALPHA&&R[2]===_s.ONE&&R[3]===_s.ONE?A.alphaMode=J.ALPHA_COMBINE:R[0]===_s.ONE&&R[1]===_s.ONE&&R[2]===_s.ZERO&&R[3]===_s.ONE?A.alphaMode=J.ALPHA_ONEONE:R[0]===_s.SRC_ALPHA&&R[1]===_s.ONE&&R[2]===_s.ZERO&&R[3]===_s.ONE?A.alphaMode=J.ALPHA_ADD:R[0]===_s.ZERO&&R[1]===_s.ONE_MINUS_SRC_COLOR&&R[2]===_s.ONE&&R[3]===_s.ONE?A.alphaMode=J.ALPHA_SUBTRACT:R[0]===_s.DST_COLOR&&R[1]===_s.ZERO&&R[2]===_s.ONE&&R[3]===_s.ONE?A.alphaMode=J.ALPHA_MULTIPLY:R[0]===_s.SRC_ALPHA&&R[1]===_s.ONE_MINUS_SRC_COLOR&&R[2]===_s.ONE&&R[3]===_s.ONE&&(A.alphaMode=J.ALPHA_MAXIMIZED))}}}let nf=class mS{static RegisterExtension(e){if(mS.Extensions[e.name]){Z.Error('Tool with the same name "'+e.name+'" already exists');return}mS.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,l){return t.useRightHandedSystem=!0,Mr.LoadRuntimeAsync(t,i,s,h=>{h.assetContainer=r,h.importOnlyMeshes=!0,e===""?h.importMeshesNames=[]:typeof e=="string"?h.importMeshesNames=[e]:e&&!(e instanceof Array)?h.importMeshesNames=[e]:(h.importMeshesNames=[],Z.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=[],u=[];for(const d in h.nodes){const f=h.nodes[d];f.babylonNode instanceof Ft&&c.push(f.babylonNode)}for(const d in h.skins){const f=h.skins[d];f.babylonSkeleton instanceof gh&&u.push(f.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{FR(h),NR(h),!is.IncrementalLoading&&n&&n(c,u)})}),is.IncrementalLoading&&n&&n(c,u)},l),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((o,l)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{o({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},n,h=>{l(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,Mr.LoadRuntimeAsync(e,t,i,o=>{Mr.LoadRuntimeExtensionsAsync(o,()=>{this._createNodes(o),this._loadBuffersAsync(o,()=>{this._loadShadersAsync(o,()=>{FR(o),NR(o),is.IncrementalLoading||s()})}),is.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,o=>{n(new Error(o))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{Mr.LoadShaderStringAsync(e,r,o=>{o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(ri.ShadersStore[r+(n.type===fS.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},()=>{Z.Error("Error when loading shader program named "+r+" located at "+n.uri)})};for(const r in e.shaders){i=!0;const n=e.shaders[r];n?s.bind(this,r,n)():Z.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{Mr.LoadBufferAsync(e,r,o=>{e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[r].byteLength&&Z.Error("Buffer named "+r+" is length "+o.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=o),e.loadedBufferCount===e.buffersCount&&t()},()=>{Z.Error("Error when loading buffer named "+r+" located at "+n.uri)})};for(const r in e.buffers){i=!0;const n=e.buffers[r];n?s.bind(this,r,n)():Z.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(hl.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){Mr._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){Mr._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{hl.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){Mr._LoadTextureBufferAsync(e,t,r=>{r&&Mr._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){Mr._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{hl.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){Mr._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{hl.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){Mr._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{hl.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){Mr._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{hl.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in nf.Extensions){const s=nf.Extensions[i];if(e(s))return}t()}}is._CreateGLTF1Loader=()=>new nf;const oQ="binary_glTF";class lQ extends Mr{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!r||r.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,s(hl.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==oQ?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,r=>s(r.message)),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView],l=er.GetBufferFromBufferView(e,o,0,o.byteLength,rh.UNSIGNED_BYTE);return i(l),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=er.GetBufferFromBufferView(e,n,0,n.byteLength,rh.UNSIGNED_BYTE);return setTimeout(()=>{const l=er.DecodeBufferToText(o);i(l)}),!0}}nf.RegisterExtension(new lQ);class hQ extends Mr{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const s in i){const r=i[s];switch(r.type){case"ambient":{const n=new Rh(r.name,new T(0,1,0),e.scene),o=r.ambient;o&&(n.diffuse=re.FromArray(o.color||[1,1,1]));break}case"point":{const n=new mf(r.name,new T(10,10,10),e.scene),o=r.point;o&&(n.diffuse=re.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new ga(r.name,new T(0,-1,0),e.scene),o=r.directional;o&&(n.diffuse=re.FromArray(o.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const o=new Cn(r.name,new T(0,10,0),new T(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);o.diffuse=re.FromArray(n.color||[1,1,1])}break}default:Z.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new Ie(t,e.scene);return o.sideOrientation=pe.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(o.disableLighting=!0),o.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,o.alpha=n.values.transparency===void 0?1:n.values.transparency,o.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=re.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=re.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=re.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=re.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){hl.LoadTextureBufferAsync(e,t,n=>{hl.CreateTextureAsync(e,t,n,o=>i[s]=o)},r)}}nf.RegisterExtension(new hQ);function LR(a,e,t,i){return T.FromArray(e,t).scaleInPlace(i)}function cQ(a,e,t,i){return ae.FromArray(e,t).scaleInPlace(i)}function uQ(a,e,t,i){const s=new Array(a._numMorphTargets);for(let r=0;r({frame:l.frame,inTangent:l.inTangent?l.inTangent[n]:void 0,value:l.value[n],outTangent:l.outTangent?l.outTangent[n]:void 0,interpolation:l.interpolation}))),e._primitiveBabylonMeshes){for(const l of e._primitiveBabylonMeshes)if(l.morphTargetManager){const h=l.morphTargetManager.getTarget(n),c=o.clone();h.animations.push(c),r(h,c)}}}}}const tp={translation:[new ME(te.ANIMATIONTYPE_VECTOR3,"position",LR,()=>3)],rotation:[new ME(te.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",cQ,()=>4)],scale:[new ME(te.ANIMATIONTYPE_VECTOR3,"scaling",LR,()=>3)],weights:[new dQ(te.ANIMATIONTYPE_FLOAT,"influence",uQ,a=>a._numMorphTargets)]};function _O(...a){const e=t=>t&&typeof t=="object";return a.reduce((t,i)=>(Object.keys(i).forEach(s=>{const r=t[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?t[s]=r.concat(...n):e(r)&&e(n)?t[s]=_O(r,n):t[s]=n}),t),{})}class mt{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose()),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then(()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let l=null;if(e){const h={};if(this._gltf.nodes)for(const u of this._gltf.nodes)u.name&&(h[u.name]=u.index);l=(e instanceof Array?e:[e]).map(u=>{const d=h[u];if(d===void 0)throw new Error(`Failed to find node '${u}'`);return d})}return this._loadAsync(r,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}loadAsync(e,t,i,s,r=""){return Promise.resolve().then(()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,()=>{})))}_loadAsync(e,t,i,s){return Promise.resolve().then(()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${Bn[Bn.LOADING]} => ${Bn[Bn.READY]}`,n=`${Bn[Bn.LOADING]} => ${Bn[Bn.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(Bn.LOADING),this._extensionsOnLoading();const o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){const c=mt.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${c.index}`,c))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let c=0;c{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then(()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(Bn.READY),this._startAnimations(),s())).then(c=>(this._parent._endPerformanceCounter(r),Z.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(n),this._parent._setState(Bn.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},u=>{this._parent.onErrorObservable.notifyObservers(u),this._parent.onErrorObservable.clear(),this.dispose()})}),c))}).catch(r=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(r),this._parent.onErrorObservable.clear(),this.dispose()),r})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&U.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else U.Warn("Unexpected BIN chunk")}}_setupData(){if(mt.Assign(this._gltf.accessors),mt.Assign(this._gltf.animations),mt.Assign(this._gltf.buffers),mt.Assign(this._gltf.bufferViews),mt.Assign(this._gltf.cameras),mt.Assign(this._gltf.images),mt.Assign(this._gltf.materials),mt.Assign(this._gltf.meshes),mt.Assign(this._gltf.nodes),mt.Assign(this._gltf.samplers),mt.Assign(this._gltf.scenes),mt.Assign(this._gltf.skins),mt.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const s of i.children)e[s]=i.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=s===void 0?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in $e._RegisteredExtensions){const t=$e._RegisteredExtensions[e].factory(this);t.name!==e&&U.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired){for(const e of this._gltf.extensionsRequired)if(!this._extensions.some(i=>i.name===e&&i.enabled))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new q("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case Qp.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],$e._LoadTransform(t,this._rootBabylonMesh));break}case Qp.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const r of t.nodes){const n=mt.Get(`${e}/nodes/${r}`,this._gltf.nodes,r);s.push(this.loadNodeAsync(`/nodes/${n.index}`,n,o=>{o.parent=this._rootBabylonMesh}))}for(const r of this._postSceneLoadActions)r();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{const r=s.geometry;r&&e.indexOf(r)===-1&&e.push(r)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Ft&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{e.push(s)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case gu.NONE:break;case gu.FIRST:{const e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case gu.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:{U.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=o=>{if($e.AddPointerMetadata(o,e),$e._LoadTransform(t,o),t.camera!=null){const l=mt.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${l.index}`,l,h=>{h.parent=o}))}if(t.children)for(const l of t.children){const h=mt.Get(`${e}/children/${l}`,this._gltf.nodes,l);r.push(this.loadNodeAsync(`/nodes/${h.index}`,h,c=>{c.parent=o}))}i(o)};if(t.mesh==null||t.skin!=null){const o=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const l=new ut(o,this._babylonScene);l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=l:t._babylonTransformNodeForSkin=l,n(l)}if(t.mesh!=null)if(t.skin==null){const o=mt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,n))}else{const o=mt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,l=>{const h=t._babylonTransformNodeForSkin;l.metadata=_O(h.metadata,l.metadata||{});const c=mt.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${c.index}`,t,c,u=>{this._forEachPrimitive(t,d=>{d.skeleton=u}),this._postSceneLoadActions.push(()=>{if(c.skeleton!=null){const d=mt.Get(`/skins/${c.index}/skeleton`,this._gltf.nodes,c.skeleton).parent;t.index===d.index?l.parent=h.parent:l.parent=d._babylonTransformNode}else l.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:l})})}))}))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(t,o=>{o.geometry&&o.geometry.useBoundingInfoFromGeometry?o._updateBoundingInfo():o.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);r[0].index==null&&mt.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(r.length===1){const l=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,h=>{t._babylonTransformNode=h,t._primitiveBabylonMeshes=[h]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new ut(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const l of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,h=>{h.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(h)}))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!s.primitives[0].targets;let h,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,h=r._instanceData.babylonSourceMesh.createInstance(t),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const u=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const d=new q(t,this._babylonScene);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?pe.CounterClockWiseSideOrientation:pe.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,d),u.push(this._loadVertexDataAsync(e,r,d).then(m=>this._loadMorphTargetsAsync(e,r,d,m).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,m.applyToMesh(d),m._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})));const f=$e._GetDrawMode(e,r.mode);if(r.material==null){let m=this._defaultBabylonMaterialData[f];m||(m=this._createDefaultMaterial("__GLTFLoader._default",f),this._parent.onMaterialLoadedObservable.notifyObservers(m),this._defaultBabylonMaterialData[f]=m),d.material=m}else if(!this.parent.skipMaterials){const m=mt.Get(`${e}/material`,this._gltf.materials,r.material);u.push(this._loadMaterialAsync(`/materials/${m.index}`,m,d,f,_=>{d.material=_}))}c=Promise.all(u),l&&(r._instanceData={babylonSourceMesh:d,promise:c}),h=d}return $e.AddPointerMetadata(h,e),this._parent.onMeshLoadedObservable.notifyObservers(h),n(h),this.logClose(),c.then(()=>h)}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new Is(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{const h=mt.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${h.index}`,h).then(c=>{o.setIndices(c)}))}const l=(h,c,u)=>{if(r[h]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(c)===-1&&i._delayInfo.push(c);const d=mt.Get(`${e}/attributes/${h}`,this._gltf.accessors,r[h]);n.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,c).then(f=>{if(f.getKind()===P.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&d.min&&d.max){const m=W.Vector3[0].copyFromFloats(...d.min),_=W.Vector3[1].copyFromFloats(...d.max);if(d.normalized&&d.componentType!==5126){let x=1;switch(d.componentType){case 5120:x=127;break;case 5121:x=255;break;case 5122:x=32767;break;case 5123:x=65535;break}const E=1/x;m.scaleInPlace(E),_.scaleInPlace(E)}o._boundingInfo=new En(m,_),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(f,d.count)})),c==P.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),u&&u(d)};return l("POSITION",P.PositionKind),l("NORMAL",P.NormalKind),l("TANGENT",P.TangentKind),l("TEXCOORD_0",P.UVKind),l("TEXCOORD_1",P.UV2Kind),l("TEXCOORD_2",P.UV3Kind),l("TEXCOORD_3",P.UV4Kind),l("TEXCOORD_4",P.UV5Kind),l("TEXCOORD_5",P.UV6Kind),l("JOINTS_0",P.MatricesIndicesKind),l("WEIGHTS_0",P.MatricesWeightsKind),l("JOINTS_1",P.MatricesIndicesExtraKind),l("WEIGHTS_1",P.MatricesWeightsExtraKind),l("COLOR_0",P.ColorKind,h=>{h.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(n).then(()=>o)}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(t._numMorphTargets==null)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new Fo(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{n.areUpdatesFrozen=!1})}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(o,l,h)=>{if(i[o]==null)return;const c=t.getVertexBuffer(l);if(!c)return;const u=mt.Get(`${e}/${o}`,this._gltf.accessors,i[o]);r.push(this._loadFloatAccessorAsync(`/accessors/${u.index}`,u).then(d=>{h(c,d)}))};return n("POSITION",P.PositionKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(l.length,(c,u)=>{h[u]=l[u]+c}),s.setPositions(h)}),n("NORMAL",P.NormalKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(h.length,(c,u)=>{h[u]=l[u]+c}),s.setNormals(h)}),n("TANGENT",P.TangentKind,(o,l)=>{const h=new Float32Array(l.length/3*4);let c=0;o.forEach(l.length/3*4,(u,d)=>{(d+1)%4!==0&&(h[c]=l[c]+u,c++)}),s.setTangents(h)}),Promise.all(r).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=T.Zero(),s=ae.Identity(),r=T.One();e.matrix?L.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=T.FromArray(e.translation)),e.rotation&&(s=ae.FromArray(e.rotation)),e.scale&&(r=T.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new gh(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(h=>{this._updateBoneMatrices(o,h)});return i._data={babylonSkeleton:o,promise:l},s(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){const r=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(r)if(t.skeleton===void 0)t.skeleton=r.index;else{const n=(l,h)=>{for(;h.parent;h=h.parent)if(h.parent===l)return!0;return!1},o=mt.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==r&&!n(o,r)&&(U.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=r.index)}else U.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=mt.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;const i={};for(const r of t){const n=[];let o=mt.Get(`${e}/${r}`,this._gltf.nodes,r);for(;o.index!==-1;)n.unshift(o),o=o.parent;i[r]=n}let s=null;for(let r=0;;++r){let n=i[t[0]];if(r>=n.length)return s;const o=n[r];for(let l=1;l=n.length||o!==n[r])return s;s=o}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?n=this._loadBone(e.parent,t,i,s):t.skeleton!==void 0&&U.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new mi(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);const i=mt.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const s=L.Identity(),r=i._index;t&&r!==-1&&(L.FromArrayToRef(t,r*16,s),s.invertToRef(s));const n=i.getParent();n&&s.multiplyToRef(n.getAbsoluteInverseBindMatrix(),s),i.updateMatrix(s,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?L.FromArray(e.matrix):L.Compose(e.scale?T.FromArray(e.scale):T.One(),e.rotation?ae.FromArray(e.rotation):ae.Identity(),e.translation?T.FromArray(e.translation):T.Zero())}loadCameraAsync(e,t,i=()=>{}){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new ln(t.name||`camera${t.index}`,T.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=o.yfov,n.minZ=o.znear,n.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=Ve.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return $e.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then(()=>n)}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{r.targetedAnimations.length===0&&r.dispose()}))}return Promise.all(t).then(()=>{})}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new Ao(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;mt.Assign(t.channels),mt.Assign(t.samplers);for(const n of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(o,l)=>{o.animations=o.animations||[],o.animations.push(l),s.addTargetedAnimation(l,o)}));return Promise.all(r).then(()=>(s.normalize(0),s))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(s.target.node==null)return Promise.resolve();const o=mt.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if(s.target.path==="weights"&&!o._numMorphTargets||s.target.path!=="weights"&&!o._babylonTransformNode)return Promise.resolve();let l;switch(s.target.path){case"translation":{l=tp.translation;break}case"rotation":{l=tp.rotation;break}case"scale":{l=tp.scale;break}case"weights":{l=tp.weights;break}default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const h={object:o,info:l};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,h,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,l=1/o,h=mt.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,h).then(c=>{let u=0;const d=r.object,f=r.info;for(const m of f){const _=m.getStride(d),x=c.input,E=c.output,S=new Array(x.length);let C=0;switch(c.interpolation){case"STEP":{for(let y=0;y0){const y=`${i.name||`animation${i.index}`}_channel${s.index}_${u}`;m.buildAnimations(d,y,o,S,(A,I)=>{++u,n(A,I)})}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=mt.Get(`${e}/input`,this._gltf.accessors,t.input),r=mt.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then(([n,o])=>({input:n,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(n=>{try{return new Uint8Array(n.buffer,n.byteOffset+i,s)}catch(o){throw new Error(`${e}: ${o.message}`)}})}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=mt.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=$e._GetNumComponents(e,t.type),r=s*P.GetTypeByteLength(t.componentType),n=s*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(n));else{const o=mt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===r))return $e._GetTypedArray(e,t.componentType,l,t.byteOffset,n);{const h=new i(n);return P.ForEach(l,t.byteOffset||0,o.byteStride||r,s,t.componentType,h.length,t.normalized||!1,(c,u)=>{h[u]=c}),h}})}if(t.sparse){const o=t.sparse;t._data=t._data.then(l=>{const h=l,c=mt.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=mt.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${c.index}`,c),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([d,f])=>{const m=$e._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),_=s*o.count;let x;if(t.componentType===5126&&!t.normalized)x=$e._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);else{const S=$e._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);x=new i(_),P.ForEach(S,0,r,s,t.componentType,x.length,t.normalized||!1,(C,y)=>{x[y]=C})}let E=0;for(let S=0;S$e._GetTypedArray(e,t.componentType,s,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new Gs(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var r;if((r=t._babylonVertexBuffer)!=null&&r[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(n=>new P(s,n,i,!1));else{const n=mt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then(o=>{const l=$e._GetNumComponents(e,t.type);return new P(s,o,i,!1,void 0,n.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=re.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=re.White(),i.metallic=t.metallicFactor==null?1:t.metallicFactor,i.roughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,r=>{r.name=`${i.name} (Base Color)`,i.albedoTexture=r})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,r=>{r.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=r})),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,i,s,r=()=>{}){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const l=this.createMaterial(e,t,s);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[s]=o,$e.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{const l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),r(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Xe(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Xe.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?re.FromArray(t.emissiveFactor):new re(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,r=>{r.name=`${i.name} (Normal)`,i.bumpTexture=r})),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,t.normalTexture.scale!=null&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,r=>{r.name=`${i.name} (Occlusion)`,i.ambientTexture=r})),i.useAmbientInGrayScale=!0,t.occlusionTexture.strength!=null&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,r=>{r.name=`${i.name} (Emissive)`,i.emissiveTexture=r})),Promise.all(s).then(()=>{})}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=Xe.PBRMATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=Xe.PBRMATERIAL_ALPHATEST,i.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=Xe.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=mt.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,o=>{o.coordinatesIndex=t.texCoord||0,$e.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),n}_loadTextureAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=t.sampler==null?$e.DefaultSampler:mt.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=mt.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=()=>{},r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,h=new ep;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(d,f)=>{this._disposed||h.reject(new Error(`${e}: ${f&&f.message?f.message:d||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},u=new X(null,this._babylonScene,c);return u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(h.promise),l.push(this.loadImageAsync(`/images/${i.index}`,i).then(d=>{const f=i.uri||`${this._fileName}#image${i.index}`,m=`data:${this._uniqueRootUrl}${f}`;u.updateURL(m,d)})),u.wrapU=o.wrapU,u.wrapV=o.wrapV,s(u),Promise.all(l).then(()=>u)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:$e._GetTextureSamplingMode(e,t),wrapU:$e._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:$e._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=mt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!$e._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Bg(i)){const r=new Uint8Array(n_(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${r.length} bytes)`),Promise.resolve(r)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(r=>new Promise((n,o)=>{this._parent._loadFile(this._babylonScene,r,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),n(new Uint8Array(l)))},!0,l=>{o(new Op(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t??10497,t){case 33071:return X.CLAMP_ADDRESSMODE;case 33648:return X.MIRROR_ADDRESSMODE;case 10497:return X.WRAP_ADDRESSMODE;default:return U.Warn(`${e}: Invalid value (${t})`),X.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=t.magFilter==null?9729:t.magFilter,s=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(s){case 9728:return X.LINEAR_NEAREST;case 9729:return X.LINEAR_LINEAR;case 9984:return X.LINEAR_NEAREST_MIPNEAREST;case 9985:return X.LINEAR_LINEAR_MIPNEAREST;case 9986:return X.LINEAR_NEAREST_MIPLINEAR;case 9987:return X.LINEAR_LINEAR_MIPLINEAR;default:return U.Warn(`${e}/minFilter: Invalid value (${s})`),X.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&U.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return X.NEAREST_NEAREST;case 9729:return X.NEAREST_LINEAR;case 9984:return X.NEAREST_NEAREST_MIPNEAREST;case 9985:return X.NEAREST_LINEAR_MIPNEAREST;case 9986:return X.NEAREST_NEAREST_MIPLINEAR;case 9987:return X.NEAREST_LINEAR_MIPLINEAR;default:return U.Warn(`${e}/minFilter: Invalid value (${s})`),X.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=$e._GetTypedArrayConstructor(`${e}/componentType`,t),l=P.GetTypeByteLength(t);return s%l!==0?(U.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new o(n.slice(s,s+r*l),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Z.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return pe.PointListDrawMode;case 1:return pe.LineListDrawMode;case 2:return pe.LineLoopDrawMode;case 3:return pe.LineStripDrawMode;case 4:return pe.TriangleFillMode;case 5:return pe.TriangleStripDrawMode;case 6:return pe.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials){for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const r of s.babylonMeshes){r.computeWorldMatrix(!0);const n=s.babylonMaterial;e.push(n.forceCompilationAsync(r)),e.push(n.forceCompilationAsync(r,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(r,{clipPlane:!0})),e.push(n.forceCompilationAsync(r,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const s=i.getShadowGenerator();s&&e.push(s.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const l=i(s);if(l)return l}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const n=t.extensions[i];return n?s(`${e}/extensions/${i}`,n):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const n=t.extras[i];return n?s(`${e}/extras/${i}`,n):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}$e._RegisteredExtensions={};$e.DefaultSampler={index:-1};is._CreateGLTF2Loader=a=>new $e(a);const gS="EXT_lights_image_based";class fQ{constructor(e){this.name=gS,this._loader=e,this.enabled=this._loader.isExtensionUsed(gS)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return $e.LoadExtensionAsync(e,t,this.name,(i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=mt.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then(o=>{this._loader.babylonScene.environmentTexture=o})),this._loader.logClose(),Promise.all(r).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][o]=u})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then(()=>{const r=new fC(this._loader.babylonScene,null,t.specularImageSize);if(r.name=t.name||"environment",t._babylonTexture=r,t.intensity!=null&&(r.level=t.intensity),t.rotation){let h=ae.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(h=ae.Inverse(h)),L.FromQuaternionToRef(h,r.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const n=uc.FromArray(t.irradianceCoefficients);n.scaleInPlace(t.intensity),n.convertIrradianceToLambertianRadiance();const o=zo.FromHarmonics(n),l=(s.length-1)/Ne.Log2(t.specularImageSize);return r.updateRGBDAsync(s,o,l)})}return t._loaded.then(()=>t._babylonTexture)}}$e.RegisterExtension(gS,a=>new fQ(a));const xS="EXT_mesh_gpu_instancing";class pQ{constructor(e){this.name=xS,this._loader=e,this.enabled=this._loader.isExtensionUsed(xS)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{this._loader._disableInstancedMesh++;const n=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return n;const o=new Array;let l=0;const h=c=>{if(r.attributes[c]==null){o.push(Promise.resolve(null));return}const u=mt.Get(`${s}/attributes/${c}`,this._loader.gltf.accessors,r.attributes[c]);if(o.push(this._loader._loadFloatAccessorAsync(`/accessors/${u.bufferView}`,u)),l===0)l=u.count;else if(l!==u.count)throw new Error(`${s}/attributes: Instance buffer accessors do not have the same count.`)};return h("TRANSLATION"),h("ROTATION"),h("SCALE"),n.then(c=>Promise.all(o).then(([u,d,f])=>{const m=new Float32Array(l*16);W.Vector3[0].copyFromFloats(0,0,0),W.Quaternion[0].copyFromFloats(0,0,0,1),W.Vector3[1].copyFromFloats(1,1,1);for(let _=0;_new pQ(a));const TS="EXT_meshopt_compression";class _Q{constructor(e){this.name=TS,this.enabled=e.isExtensionUsed(TS),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return $e.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=mt.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then(o=>cl.Default.decodeGltfBufferAsync(o,s.count,s.byteStride,s.mode,s.filter)),r._meshOptData})}}$e.RegisterExtension(TS,a=>new _Q(a));const ES="EXT_texture_webp";class mQ{constructor(e){this.name=ES,this._loader=e,this.enabled=e.isExtensionUsed(ES)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?$e.DefaultSampler:mt.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mt.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}$e.RegisterExtension(ES,a=>new mQ(a));const SS="EXT_texture_avif";class gQ{constructor(e){this.name=SS,this._loader=e,this.enabled=e.isExtensionUsed(SS)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?$e.DefaultSampler:mt.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mt.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}$e.RegisterExtension(SS,a=>new gQ(a));const vS="KHR_draco_mesh_compression";class xQ{constructor(e){this.name=vS,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=zn.DecoderAvailable&&this._loader.isExtensionUsed(vS)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},l=(c,u)=>{const d=r.attributes[c];if(d!=null&&(i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(u)===-1&&i._delayInfo.push(u),n[u]=d,this.useNormalizedFlagFromAccessor)){const f=mt.TryGet(this._loader.gltf.accessors,t.attributes[c]);f&&(o[u]=f.normalized||!1)}};l("POSITION",P.PositionKind),l("NORMAL",P.NormalKind),l("TANGENT",P.TangentKind),l("TEXCOORD_0",P.UVKind),l("TEXCOORD_1",P.UV2Kind),l("TEXCOORD_2",P.UV3Kind),l("TEXCOORD_3",P.UV4Kind),l("TEXCOORD_4",P.UV5Kind),l("TEXCOORD_5",P.UV6Kind),l("JOINTS_0",P.MatricesIndicesKind),l("WEIGHTS_0",P.MatricesWeightsKind),l("COLOR_0",P.ColorKind);const h=mt.Get(s,this._loader.gltf.bufferViews,r.bufferView);return h._dracoBabylonGeometry||(h._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${h.index}`,h).then(c=>(this.dracoCompression||zn.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,c,n,o).catch(d=>{throw new Error(`${e}: ${d.message}`)}))),h._dracoBabylonGeometry})}}$e.RegisterExtension(vS,a=>new xQ(a));const CS="KHR_lights_punctual";class TQ{constructor(e){this.name=CS,this._loader=e,this.enabled=this._loader.isExtensionUsed(CS)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,mt.Assign(this._lights)}}loadNodeAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,n=>{let o;const l=mt.Get(s,this._lights,r.light),h=l.name||n.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,l.type){case"directional":{const c=new ga(h,T.Backward(),this._loader.babylonScene);c.position.setAll(0),o=c;break}case"point":{o=new mf(h,T.Zero(),this._loader.babylonScene);break}case"spot":{const c=new Cn(h,T.Zero(),T.Backward(),0,1,this._loader.babylonScene);c.angle=(l.spot&&l.spot.outerConeAngle||Math.PI/4)*2,c.innerAngle=(l.spot&&l.spot.innerConeAngle||0)*2,o=c;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${l.type})`)}o._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,l._babylonLight=o,o.falloffType=yt.FALLOFF_GLTF,o.diffuse=l.color?re.FromArray(l.color):re.White(),o.intensity=l.intensity==null?1:l.intensity,o.range=l.range==null?Number.MAX_VALUE:l.range,o.parent=n,this._loader._babylonLights.push(o),$e.AddPointerMetadata(o,s),i(n)})))}}$e.RegisterExtension(CS,a=>new TQ(a));const bS="KHR_materials_pbrSpecularGlossiness";class EQ{constructor(e){this.name=bS,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(bS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=re.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=re.White(),i.reflectivityColor=t.specularFactor?re.FromArray(t.specularFactor):re.White(),i.microSurface=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,r=>{r.name=`${i.name} (Diffuse)`,i.albedoTexture=r})),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,r=>{r.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=r,i.reflectivityTexture.hasAlpha=!0})),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then(()=>{})}}$e.RegisterExtension(bS,a=>new EQ(a));const yS="KHR_materials_unlit";class SQ{constructor(e){this.name=yS,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(yS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,()=>this._loadUnlitPropertiesAsync(e,t,i))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=re.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=re.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,n=>{n.name=`${i.name} (Base Color)`,i.albedoTexture=n}))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}}$e.RegisterExtension(yS,a=>new SQ(a));const AS="KHR_materials_clearcoat";class vQ{constructor(e){this.name=AS,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(AS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,t.clearcoatFactor!=null?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,r=>{r.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=r})),t.clearcoatRoughnessFactor!=null?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,r=>{r.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=r}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,r=>{r.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=r})),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,t.clearcoatNormalTexture.scale!=null&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then(()=>{})}}$e.RegisterExtension(AS,a=>new vQ(a));const RS="KHR_materials_iridescence";class CQ{constructor(e){this.name=RS,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(RS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,r=>{r.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=r})),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,r=>{r.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=r})),Promise.all(s).then(()=>{})}}$e.RegisterExtension(RS,a=>new CQ(a));const IS="KHR_materials_anisotropy";class bQ{constructor(e){this.name=IS,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(IS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,r=>{r.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=r})),Promise.all(s).then(()=>{})}}$e.RegisterExtension(IS,a=>new bQ(a));const PS="KHR_materials_emissive_strength";class yQ{constructor(e){this.name=PS,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(PS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then(()=>{this._loadEmissiveProperties(s,r,i)}))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);t.emissiveStrength!==void 0&&(i.emissiveIntensity=t.emissiveStrength)}}$e.RegisterExtension(PS,a=>new yQ(a));const MS="KHR_materials_sheen";class AQ{constructor(e){this.name=MS,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(MS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,t.sheenColorFactor!=null?i.sheen.color=re.FromArray(t.sheenColorFactor):i.sheen.color=re.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,r=>{r.name=`${i.name} (Sheen Color)`,i.sheen.texture=r})),t.sheenRoughnessFactor!==void 0?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,r=>{r.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=r}))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then(()=>{})}}$e.RegisterExtension(MS,a=>new AQ(a));const OS="KHR_materials_specular";class RQ{constructor(e){this.name=OS,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(OS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const s=new Array;return t.specularFactor!==void 0&&(i.metallicF0Factor=t.specularFactor),t.specularColorFactor!==void 0&&(i.metallicReflectanceColor=re.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,r=>{r.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=r,i.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,r=>{r.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=r})),Promise.all(s).then(()=>{})}}$e.RegisterExtension(OS,a=>new RQ(a));const DS="KHR_materials_ior";class Vx{constructor(e){this.name=DS,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(DS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);return t.ior!==void 0?i.indexOfRefraction=t.ior:i.indexOfRefraction=Vx._DEFAULT_IOR,Promise.resolve()}}Vx._DEFAULT_IOR=1.5;$e.RegisterExtension(DS,a=>new Vx(a));const mn="KHR_materials_variants";class Zl{constructor(e){this.name=mn,this._loader=e,this.enabled=this._loader.isExtensionUsed(mn)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return Zl.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${mn} extension`);const s=r=>{const n=i.variants[r];if(n)for(const o of n)o.mesh.material=o.material};if(t instanceof Array)for(const r of t)s(r);else s(t);i.lastSelected=t}selectVariant(e,t){Zl.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${mn} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){Zl.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${mn} extension`);return t.lastSelected}getLastSelectedVariant(e){return Zl.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return((i=(t=e==null?void 0:e._internalMetadata)==null?void 0:t.gltf)==null?void 0:i[mn])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return $e.LoadExtensionAsync(e,r,this.name,(o,l)=>{const h=new Array;return h.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,c=>{if(n(c),c instanceof q){const u=$e._GetDrawMode(e,r.mode),d=this._loader.rootBabylonMesh,f=d?d._internalMetadata=d._internalMetadata||{}:{},m=f.gltf=f.gltf||{},_=m[mn]=m[mn]||{lastSelected:null,original:[],variants:{}};_.original.push({mesh:c,material:c.material});for(let x=0;x{for(let y=0;y{const N=R;let k=null,B=N;do{if(B=B.parent,!B)return;k=Zl._GetExtensionMetadata(B)}while(k===null);if(d&&k===Zl._GetExtensionMetadata(d)){B._internalMetadata={};for(const Q in d._internalMetadata)B._internalMetadata[Q]=d._internalMetadata[Q];B._internalMetadata.gltf=[];for(const Q in d._internalMetadata.gltf)B._internalMetadata.gltf[Q]=d._internalMetadata.gltf[Q];B._internalMetadata.gltf[mn]={lastSelected:null,original:[],variants:{}};for(const Q of k.original)B._internalMetadata.gltf[mn].original.push({mesh:Q.mesh,material:Q.material});for(const Q in k.variants)if(Object.prototype.hasOwnProperty.call(k.variants,Q)){B._internalMetadata.gltf[mn].variants[Q]=[];for(const ne of k.variants[Q])B._internalMetadata.gltf[mn].variants[Q].push({mesh:ne.mesh,material:ne.material})}k=B._internalMetadata.gltf[mn]}for(const Q of k.original)Q.mesh===c&&(Q.mesh=N);for(const Q of k.variants[I.name])Q.mesh===c&&(Q.mesh=N)})}}))}}})),Promise.all(h).then(([c])=>c)})}}$e.RegisterExtension(mn,a=>new Zl(a));class FC{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:J.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...FC._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new K,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter(r=>this._options[r]!==e[r]).length)return;const i={...this._options,...e},s=this._options;this._options=i,i.renderSize!==s.renderSize||i.renderTargetTextureType!==s.renderTargetTextureType||i.generateMipmaps!==s.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=i.samples,this._opaqueRenderTarget.lodGenerationScale=i.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=i.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return e?!!(e instanceof Xe&&e.subSurface.isRefractionEnabled):!1}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Z.SetImmediate(()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e)):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e)})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Xe&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),i!==-1?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):t===-1&&this._transparentMeshesCache.push(e)):t!==-1?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):i===-1&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return((e=this._opaqueRenderTarget)==null?void 0:e.getInternalTexture())!==null}_setupRenderTargets(){var i;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new Yi("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=((i=this._options.clearColor)==null?void 0:i.clone())??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0;let e,t;this._opaqueRenderTarget.onBeforeBindObservable.add(s=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?s.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(s.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e}),this._transparentMeshesCache.forEach(s=>{this._shouldRenderAsTransmission(s.material)&&(s.material.refractionTexture=this._opaqueRenderTarget)})}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const NS="KHR_materials_transmission";class IQ{constructor(e){this.name=NS,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(NS),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,i,s){var n,o;if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,s.transmissionFactor!==void 0){r.subSurface.refractionIntensity=s.transmissionFactor;const l=r.getScene();r.subSurface.refractionIntensity&&!l._transmissionHelper?new FC({},r.getScene()):r.subSurface.refractionIntensity&&!((n=l._transmissionHelper)!=null&&n._isRenderTargetValid())&&((o=l._transmissionHelper)==null||o._setupRenderTargets())}else return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then(l=>{r.subSurface.refractionIntensityTexture=l,r.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}$e.RegisterExtension(NS,a=>new IQ(a));const wS="KHR_materials_diffuse_transmission";class PQ{constructor(e){this.name=wS,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(wS),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,s.diffuseTransmissionFactor!==void 0)r.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;else return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();const n=new Array;return r.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(o=>{r.subSurface.translucencyIntensityTexture=o}))),s.diffuseTransmissionColorFactor!==void 0?r.subSurface.translucencyColor=re.FromArray(s.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=re.White(),s.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(o=>{r.subSurface.translucencyColorTexture=o})),Promise.all(n).then(()=>{})}}$e.RegisterExtension(wS,a=>new PQ(a));const FS="KHR_materials_volume";class MQ{constructor(e){this.name=FS,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(FS),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=s.attenuationDistance!==void 0?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,s.attenuationColor!==void 0&&s.attenuationColor.length==3&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then(n=>{i.subSurface.thicknessTexture=n,i.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}$e.RegisterExtension(FS,a=>new MQ(a));const LS="KHR_materials_dispersion";class OQ{constructor(e){this.name=LS,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(LS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Xe))throw new Error(`${e}: Material type not supported`);return!i.subSurface.isRefractionEnabled||!s.dispersion||(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion),Promise.resolve()}}$e.RegisterExtension(LS,a=>new OQ(a));const BS="KHR_mesh_quantization";class DQ{constructor(e){this.name=BS,this.enabled=e.isExtensionUsed(BS)}dispose(){}}$e.RegisterExtension(BS,a=>new DQ(a));const US="KHR_texture_basisu";class NQ{constructor(e){this.name=US,this._loader=e,this.enabled=e.isExtensionUsed(US)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?$e.DefaultSampler:mt.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=mt.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)})}}$e.RegisterExtension(US,a=>new NQ(a));const VS="KHR_texture_transform";class wQ{constructor(e){this.name=VS,this._loader=e,this.enabled=this._loader.isExtensionUsed(VS)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadTextureInfoAsync(e,t,n=>{if(!(n instanceof X))throw new Error(`${s}: Texture type not supported`);r.offset&&(n.uOffset=r.offset[0],n.vOffset=r.offset[1]),n.uRotationCenter=0,n.vRotationCenter=0,r.rotation&&(n.wAng=-r.rotation),r.scale&&(n.uScale=r.scale[0],n.vScale=r.scale[1]),r.texCoord!=null&&(n.coordinatesIndex=r.texCoord),i(n)}))}}$e.RegisterExtension(VS,a=>new wQ(a));const kS="KHR_xmp_json_ld";class FQ{constructor(e){this.name=kS,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(kS)}dispose(){this._loader=null}onLoading(){var i,s,r;if(this._loader.rootBabylonMesh===null)return;const e=(i=this._loader.gltf.extensions)==null?void 0:i.KHR_xmp_json_ld,t=(r=(s=this._loader.gltf.asset)==null?void 0:s.extensions)==null?void 0:r.KHR_xmp_json_ld;if(e&&t){const n=+t.packet;e.packets&&nnew FQ(a));function Hh(a,e,t,i){return re.FromArray(e,t).scale(i)}function LQ(a,e,t,i){return e[t+3]*i}function Hi(a,e,t,i){return e[t]*i}function GS(a,e,t,i){return-e[t]*i}function wg(a,e,t,i){return e[t+1]*i}function BR(a,e,t,i){return e[t]*i*2}function Rr(a){return{scale:[new Mi(te.ANIMATIONTYPE_FLOAT,`${a}.uScale`,Hi,()=>2),new Mi(te.ANIMATIONTYPE_FLOAT,`${a}.vScale`,wg,()=>2)],offset:[new Mi(te.ANIMATIONTYPE_FLOAT,`${a}.uOffset`,Hi,()=>2),new Mi(te.ANIMATIONTYPE_FLOAT,`${a}.vOffset`,wg,()=>2)],rotation:[new Mi(te.ANIMATIONTYPE_FLOAT,`${a}.wAng`,GS,()=>1)]}}class nl extends N_{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class Mi extends N_{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class qf extends N_{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const BQ={__array__:{__target__:!0,...tp}},UQ={__array__:{__target__:!0,orthographic:{xmag:[new nl(te.ANIMATIONTYPE_FLOAT,"orthoLeft",GS,()=>1),new nl(te.ANIMATIONTYPE_FLOAT,"orthoRight",wg,()=>1)],ymag:[new nl(te.ANIMATIONTYPE_FLOAT,"orthoBottom",GS,()=>1),new nl(te.ANIMATIONTYPE_FLOAT,"orthoTop",wg,()=>1)],zfar:[new nl(te.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)],znear:[new nl(te.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]},perspective:{yfov:[new nl(te.ANIMATIONTYPE_FLOAT,"fov",Hi,()=>1)],zfar:[new nl(te.ANIMATIONTYPE_FLOAT,"maxZ",Hi,()=>1)],znear:[new nl(te.ANIMATIONTYPE_FLOAT,"minZ",Hi,()=>1)]}}},VQ={__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new Mi(te.ANIMATIONTYPE_COLOR3,"albedoColor",Hh,()=>4),new Mi(te.ANIMATIONTYPE_FLOAT,"alpha",LQ,()=>4)],metallicFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"metallic",Hi,()=>1)],roughnessFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"roughness",Hi,()=>1)],baseColorTexture:{extensions:{KHR_texture_transform:Rr("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Rr("metallicTexture")}}},emissiveFactor:[new Mi(te.ANIMATIONTYPE_COLOR3,"emissiveColor",Hh,()=>3)],normalTexture:{scale:[new Mi(te.ANIMATIONTYPE_FLOAT,"bumpTexture.level",Hi,()=>1)],extensions:{KHR_texture_transform:Rr("bumpTexture")}},occlusionTexture:{strength:[new Mi(te.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",Hi,()=>1)],extensions:{KHR_texture_transform:Rr("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Rr("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new Mi(te.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",Hi,()=>1)],anisotropyRotation:[new Mi(te.ANIMATIONTYPE_FLOAT,"anisotropy.angle",Hi,()=>1)],anisotropyTexture:{extensions:{KHR_texture_transform:Rr("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",Hi,()=>1)],clearcoatRoughnessFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",Hi,()=>1)],clearcoatTexture:{extensions:{KHR_texture_transform:Rr("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new Mi(te.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",Hi,()=>1)],extensions:{KHR_texture_transform:Rr("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Rr("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new Mi(te.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",Hi,()=>1)]},KHR_materials_emissive_strength:{emissiveStrength:[new Mi(te.ANIMATIONTYPE_FLOAT,"emissiveIntensity",Hi,()=>1)]},KHR_materials_ior:{ior:[new Mi(te.ANIMATIONTYPE_FLOAT,"indexOfRefraction",Hi,()=>1)]},KHR_materials_iridescence:{iridescenceFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"iridescence.intensity",Hi,()=>1)],iridescenceIor:[new Mi(te.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",Hi,()=>1)],iridescenceThicknessMinimum:[new Mi(te.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",Hi,()=>1)],iridescenceThicknessMaximum:[new Mi(te.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",Hi,()=>1)],iridescenceTexture:{extensions:{KHR_texture_transform:Rr("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Rr("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new Mi(te.ANIMATIONTYPE_COLOR3,"sheen.color",Hh,()=>3)],sheenRoughnessFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"sheen.roughness",Hi,()=>1)],sheenColorTexture:{extensions:{KHR_texture_transform:Rr("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Rr("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"metallicF0Factor",Hi,()=>1)],specularColorFactor:[new Mi(te.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Hh,()=>3)],specularTexture:{extensions:{KHR_texture_transform:Rr("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:Rr("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",Hi,()=>1)],transmissionTexture:{extensions:{KHR_texture_transform:Rr("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new Mi(te.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Hh,()=>3)],attenuationDistance:[new Mi(te.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",Hi,()=>1)],thicknessFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",Hi,()=>1)],thicknessTexture:{extensions:{KHR_texture_transform:Rr("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new Mi(te.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",Hi,()=>1)],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Rr("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new Mi(te.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Hh,()=>3)],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Rr("subSurface.translucencyColorTexture")}}}}}},kQ={KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new qf(te.ANIMATIONTYPE_COLOR3,"diffuse",Hh,()=>3)],intensity:[new qf(te.ANIMATIONTYPE_FLOAT,"intensity",Hi,()=>1)],range:[new qf(te.ANIMATIONTYPE_FLOAT,"range",Hi,()=>1)],spot:{innerConeAngle:[new qf(te.ANIMATIONTYPE_FLOAT,"innerAngle",BR,()=>1)],outerConeAngle:[new qf(te.ANIMATIONTYPE_FLOAT,"angle",BR,()=>1)]}}}}},GQ={nodes:BQ,materials:VQ,cameras:UQ,extensions:kQ};class mO{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,i=this._infoTree,s;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(i.__array__)i=i.__array__;else if(i=i[n],!i)throw new Error(`Path ${e} is invalid`);if(t===void 0)throw new Error(`Path ${e} is invalid`);t=t[n],i.__target__&&(s=t)}return{object:s,info:i}}}const zS="KHR_animation_pointer";class zQ extends mO{constructor(e){super(e,GQ)}}class WQ{constructor(e){this.name=zS,this._loader=e,this._pathToObjectConverter=new zQ(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(zS)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){var h;const n=(h=s.target.extensions)==null?void 0:h.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;s.target.path!=="pointer"&&U.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),s.target.node!=null&&U.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,l=n.pointer;if(!l)throw new Error(`${o}: Pointer is missing`);try{const c=this._pathToObjectConverter.convert(l);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,c,r)}catch{return U.Warn(`${o}/pointer: Invalid pointer (${l}) skipped`),null}}}$e.RegisterExtension(zS,a=>new WQ(a));const WS="MSFT_audio_emitter";class HQ{constructor(e){this.name=WS,this._loader=e,this.enabled=this._loader.isExtensionUsed(WS)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,mt.Assign(this._clips),mt.Assign(this._emitters)}}loadSceneAsync(e,t){return $e.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const n of s.emitters){const o=mt.Get(`${i}/emitters`,this._emitters,n);if(o.refDistance!=null||o.maxDistance!=null||o.rolloffFactor!=null||o.distanceModel!=null||o.innerAngle!=null||o.outerAngle!=null)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${o.index}`,o))}return Promise.all(r).then(()=>{})})}loadNodeAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return this._loader.loadNodeAsync(s,t,o=>{for(const l of r.emitters){const h=mt.Get(`${s}/emitters`,this._emitters,l);n.push(this._loadEmitterAsync(`${s}/emitters/${h.index}`,h).then(()=>{for(const c of h._babylonSounds)c.attachToMesh(o),(h.innerAngle!=null||h.outerAngle!=null)&&(c.setLocalDirectionToMesh(T.Forward()),c.setDirectionalCone(2*Z.ToDegrees(h.innerAngle==null?Math.PI:h.innerAngle),2*Z.ToDegrees(h.outerAngle==null?Math.PI:h.outerAngle),0))}))}i(o)}).then(o=>Promise.all(n).then(()=>o))})}loadAnimationAsync(e,t){return $e.LoadExtensionAsync(e,t,this.name,(i,s)=>this._loader.loadAnimationAsync(e,t).then(r=>{const n=new Array;mt.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then(()=>r)}))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=mt.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then(s=>URL.createObjectURL(new Blob([s],{type:t.mimeType}))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const i=new Array,s=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let o=0;o{const u=t._babylonSounds[o]=new no(s,c,this._loader.babylonScene,null,r);u.refDistance=t.refDistance||1,u.maxDistance=t.maxDistance||256,u.rolloffFactor=t.rolloffFactor||1,u.distanceModel=t.distanceModel||"exponential"}))}const n=Promise.all(i).then(()=>{const o=t.clips.map(h=>h.weight||1),l=new GV(t.loop||!1,t._babylonSounds,o);t.innerAngle&&(l.directionalConeInnerAngle=2*Z.ToDegrees(t.innerAngle)),t.outerAngle&&(l.directionalConeOuterAngle=2*Z.ToDegrees(t.outerAngle)),t.volume&&(l.volume=t.volume),t._babylonData.sound=l});t._babylonData={loaded:n}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return n=>{const o=(r||0)+(n-s);t.play(o)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(r.targetedAnimations.length==0)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,l=mt.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,l).then(()=>{const h=l._babylonData.sound;if(h){const c=new uv(s.time,this._getEventAction(e,h,s.action,s.time,s.startOffset));n.animation.addEvent(c),r.onAnimationGroupEndObservable.add(()=>{h.stop()}),r.onAnimationGroupPauseObservable.add(()=>{h.pause()})}})}}$e.RegisterExtension(WS,a=>new HQ(a));const HS="MSFT_lod";class XQ{constructor(e){this.name=HS,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new K,this.onMaterialLODsLoadedObservable=new K,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(HS)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return $e.LoadExtensionAsync(e,t,this.name,(s,r)=>{let n;const o=this._getLODs(s,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${s}`);for(let l=0;l{i(d),d.setEnabled(!1)},u=this._loader.loadNodeAsync(`/nodes/${h.index}`,h,c).then(d=>{if(l!==0){const f=o[l-1];f._babylonTransformNode&&(this._disposeTransformNode(f._babylonTransformNode),delete f._babylonTransformNode)}return d.setEnabled(!0),d});this._nodePromiseLODs[l]=this._nodePromiseLODs[l]||[],l===0?n=u:(this._nodeIndexLOD=null,this._nodePromiseLODs[l].push(u))}return this._loader.logClose(),n})}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:$e.LoadExtensionAsync(e,t,this.name,(n,o)=>{let l;const h=this._getLODs(n,t,this._loader.gltf.materials,o.ids);this._loader.logOpen(`${n}`);for(let c=0;c{c===0&&r(f)}).then(f=>{if(c!==0){r(f);const m=h[c-1]._data;m[s]&&(this._disposeMaterials([m[s].babylonMaterial]),delete m[s])}return f});this._materialPromiseLODs[c]=this._materialPromiseLODs[c]||[],c===0?l=d:(this._materialIndexLOD=null,this._materialPromiseLODs[c].push(d))}return this._loader.logClose(),l})}_loadUriAsync(e,t,i){if(this._nodeIndexLOD!==null){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new ep,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>this._loader.loadUriAsync(e,t,i))}else if(this._materialIndexLOD!==null){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new ep,this._materialSignalLODs[s].promise.then(()=>this._loader.loadUriAsync(e,t,i))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const r=(n,o)=>{const l=i,h=l+s-1;let c=n[o];return c?(c.start=Math.min(c.start,l),c.end=Math.max(c.end,h)):(c={start:l,end:h,loaded:new ep},n[o]=c),c.loaded.promise.then(u=>new Uint8Array(u.buffer,u.byteOffset+i-c.start,s))};return this._loader.log("deferred"),this._nodeIndexLOD!==null?r(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?r(this._materialBufferLODs,this._materialIndexLOD):r(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then(s=>{i.loaded.resolve(s)},s=>{i.loaded.reject(s)}))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let n=s.length-1;n>=0;n--)if(r.push(mt.Get(`${e}/ids/${s[n]}`,i,s[n])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const r of e.getChildMeshes())r.material&&t.push(r.material);e.dispose();const s=t.filter(r=>this._loader.babylonScene.meshes.every(n=>n.material!=r));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const s of i.getActiveTextures())t[s.uniqueId]=s;i.dispose()}for(const i in t)for(const s of this._loader.babylonScene.materials)s.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}$e.RegisterExtension(HS,a=>new XQ(a));const XS="MSFT_minecraftMesh";class YQ{constructor(e){this.name=XS,this._loader=e,this.enabled=this._loader.isExtensionUsed(XS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Xe))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,n}return null})}}$e.RegisterExtension(XS,a=>new YQ(a));const YS="MSFT_sRGBFactors";class $Q{constructor(e){this.name=YS,this._loader=e,this.enabled=this._loader.isExtensionUsed(YS)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $e.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Xe))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i),o=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,o),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,o),n}return null})}}$e.RegisterExtension(YS,a=>new $Q(a));const KQ={"lifecycle/onStart":D_.ClassName,"lifecycle/onTick":rf.ClassName,log:Fu.ClassName,"flow/delay":A_.ClassName,"customEvent/send":y_.ClassName,"customEvent/receive":sf.ClassName,"flow/sequence":Vu.ClassName,"world/get":Gu.ClassName,"world/set":b_.ClassName,"flow/doN":Bu.ClassName,"variable/get":ku.ClassName,"variable/set":Lu.ClassName,"flow/whileLoop":Uu.ClassName,"math/random":Yu.ClassName,"math/e":Ku.ClassName,"math/pi":ju.ClassName,"math/inf":qu.ClassName,"math/nan":Qu.ClassName,"math/abs":Zu.ClassName,"math/sign":Ju.ClassName,"math/trunc":ed.ClassName,"math/floor":td.ClassName,"math/ceil":id.ClassName,"math/fract":sd.ClassName,"math/neg":rd.ClassName,"math/add":zu.ClassName,"math/sub":Wu.ClassName,"math/mul":Hu.ClassName,"math/div":Xu.ClassName,"math/rem":nd.ClassName,"math/min":ad.ClassName,"math/max":od.ClassName,"math/clamp":ld.ClassName,"math/saturate":hd.ClassName,"math/mix":cd.ClassName,"math/eq":ud.ClassName,"math/lt":dd.ClassName,"math/le":Bx.ClassName,"math/gt":fd.ClassName,"math/ge":pd.ClassName,"math/isnan":_d.ClassName,"math/isinf":Ux.ClassName,"math/rad":md.ClassName,"math/deg":gd.ClassName,"math/sin":xd.ClassName,"math/cos":Td.ClassName,"math/tan":Ed.ClassName,"math/asin":Sd.ClassName,"math/acos":vd.ClassName,"math/atan":Cd.ClassName,"math/atan2":bd.ClassName,"math/sinh":yd.ClassName,"math/cosh":Ad.ClassName,"math/tanh":Rd.ClassName,"math/asinh":Id.ClassName,"math/acosh":Pd.ClassName,"math/atanh":Md.ClassName,"math/exp":Od.ClassName,"math/log":Dd.ClassName,"math/log2":Nd.ClassName,"math/log10":wd.ClassName,"math/sqrt":Fd.ClassName,"math/cbrt":Ld.ClassName,"math/pow":Bd.ClassName,"math/length":Ud.ClassName,"math/normalize":Vd.ClassName,"math/dot":$u.ClassName,"math/cross":kd.ClassName,"math/rotate2d":Gd.ClassName,"math/rotate3d":zd.ClassName,"math/transpose":Wd.ClassName,"math/determinant":Hd.ClassName,"math/inverse":Xd.ClassName,"math/matmul":Yd.ClassName,"math/not":$d.ClassName,"math/and":Kd.ClassName,"math/or":jd.ClassName,"math/xor":qd.ClassName,"math/asr":Zd.ClassName,"math/lsl":Qd.ClassName,"math/clz":Jd.ClassName,"math/ctz":ef.ClassName,"math/popcnt":tf.ClassName},jQ={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function $S(a,e,t){if(a.type!==void 0){const i=e.types&&e.types[a.type];if(!i)throw new Error(`${t}: Unknown type: ${a.type}`);const s=i.signature;if(!s)throw new Error(`${t}: Type ${a.type} has no signature`);const r=jQ[s];return{value:a.value,className:r}}else return a.value}function qQ(a,e,t){const i={},s=a.configuration??[];for(const r of s)if(r.id==="customEvent"){const n=e.customEvents&&e.customEvents[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown custom event: ${r.value}`);i.eventId=n.id,i.eventData=n.values.map(o=>o.id)}else if(r.id==="variable"){const n=e.variables&&e.variables[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown variable: ${r.value}`);i.variableName=n.id}else if(r.id==="path"){const n=r.value;i.path=n}else i[r.id]=$S(r,e,`/extensions/KHR_interactivity/nodes/${t}`);return i}function QQ(a,e,t){const i=KQ[e.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${a}: Unknown block type: ${e.type}`);const s=a.toString(),r=qQ(e,t,s),n=e.metadata;return{className:i,config:r,uniqueId:s,metadata:n,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}function ZQ(a){const e={uniqueId:La(),_userVariables:{},_connectionValues:{}},t=[e],i=[];for(let r=0;rE.name===m);x||(x={uniqueId:La(),name:m,_connectionType:Kn.Input,connectedPointIds:[]},_.signalInputs.push(x)),x.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(x.uniqueId)}const h=n.values??[];for(const c of h){const u=c.id,d={uniqueId:La(),name:u,_connectionType:Kn.Input,connectedPointIds:[]};if(o.dataInputs.push(d),c.value!==void 0){const f=$S(c,a,`/extensions/KHR_interactivity/nodes/${r}`);e._connectionValues[d.uniqueId]=f}else if(c.node!==void 0&&c.socket!==void 0){const f=c.node,m=c.socket,_=i[f];if(!_)throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Could not find node with id ${f} that connects its output with node${r}'s input ${u}`);let x=_.dataOutputs.find(E=>E.name===m);x||(x={uniqueId:La(),name:m,_connectionType:Kn.Output,connectedPointIds:[]},_.dataOutputs.push(x)),d.connectedPointIds.push(x.uniqueId),x.connectedPointIds.push(d.uniqueId)}else throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Invalid socket ${u} in node ${r}`)}}const s=a.variables??[];for(let r=0;ra._babylonTransformNode.position,set:(a,e)=>{const t=e._babylonTransformNode;t.position=a},getObject(a){return a._babylonTransformNode}}}},tZ={nodes:eZ},KS="KHR_interactivity";class iZ{constructor(e){this._loader=e,this.name=KS,this.enabled=this._loader.isExtensionUsed(KS),this._pathConverter=new JQ(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){var r;if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=(r=this._loader.gltf.extensions)==null?void 0:r.KHR_interactivity,i=ZQ(t),s=new mu({scene:e});wu.Parse(i,{coordinator:s,pathConverter:this._pathConverter}),s.start()}}$e.RegisterExtension(KS,a=>new iZ(a));const gO="ExtrasAsMetadata";class sZ{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{},s=i.gltf=i.gltf||{};s.extras=t.extras}}constructor(e){this.name=gO,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}$e.RegisterExtension(gO,a=>new sZ(a));class eo{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split(` +`),n=/\s+/;let o,l=null;for(let h=0;h=0?c.substring(0,u):c;d=d.toLowerCase();const f=u>=0?c.substring(u+1).trim():"";if(d==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!s,l=new Ie(f,e),l._parentContainer=s,e._blockEntityCollection=!1;else if(d==="kd"&&l)o=f.split(n,3).map(parseFloat),l.diffuseColor=re.FromArray(o);else if(d==="ka"&&l)o=f.split(n,3).map(parseFloat),l.ambientColor=re.FromArray(o);else if(d==="ks"&&l)o=f.split(n,3).map(parseFloat),l.specularColor=re.FromArray(o);else if(d==="ke"&&l)o=f.split(n,3).map(parseFloat),l.emissiveColor=re.FromArray(o);else if(d==="ns"&&l)l.specularPower=parseFloat(f);else if(d==="d"&&l)l.alpha=parseFloat(f);else if(d==="map_ka"&&l)l.ambientTexture=eo._GetTexture(i,f,e);else if(d==="map_kd"&&l)l.diffuseTexture=eo._GetTexture(i,f,e);else if(d==="map_ks"&&l)l.specularTexture=eo._GetTexture(i,f,e);else if(d!=="map_ns")if(d==="map_bump"&&l){const m=f.split(n),_=m.indexOf("-bm");let x=null;_>=0&&(x=m[_+1],m.splice(_,2)),l.bumpTexture=eo._GetTexture(i,m.join(" "),e),l.bumpTexture&&x!==null&&(l.bumpTexture.level=parseFloat(x))}else d==="map_d"&&l&&(l.opacityTexture=eo._GetTexture(i,f,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if(e==="file:"){let r=t.lastIndexOf("\\");r===-1&&(r=t.lastIndexOf("/")),r>-1?s+=t.substr(r+1):s+=t}else s+=t;return new X(s,i,!1,eo.INVERT_TEXTURE_Y)}}eo.INVERT_TEXTURE_Y=!0;class Ai{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new Oe(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let l;this._loadingOptions.optimizeWithUV?l=this._isInArrayUV(this._tuplePosNorm,[e,i,t]):l=this._isInArray(this._tuplePosNorm,[e,i]),l===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),o!==void 0&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(l)}_unwrapData(){for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(P.PositionKind),i=e.getVerticesData(P.NormalKind),s={};if(!t||!i)return;for(let n=0;nthis._triangles.push(l[0],l[h],l[h+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(l,h)=>this._triangles.push(l[0],l[h+1],l[h]),this._handednessSign=1):(this._pushTriangle=(l,h)=>this._triangles.push(l[0],l[h],l[h+1]),this._handednessSign=-1);const n=t.split(` +`);for(let l=0;l=7){const u=parseFloat(c[4]),d=parseFloat(c[5]),f=parseFloat(c[6]);this._colors.push(new Oe(u>1?u/255:u,d>1?d/255:d,f>1?f/255:f,c.length===7||c[7]===void 0?1:parseFloat(c[7])))}else this._colors.push(this._grayColor)}else if((c=Ai.NormalPattern.exec(h))!==null)this._normals.push(new T(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3])));else if((c=Ai.UVPattern.exec(h))!==null)this._uvs.push(new ce(parseFloat(c[1])*this._loadingOptions.UVScaling.x,parseFloat(c[2])*this._loadingOptions.UVScaling.y));else if((c=Ai.FacePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "),1);else if((c=Ai.FacePattern4.exec(h))!==null)this._setDataForCurrentFaceWithPattern4(c[1].trim().split(" "),1);else if((c=Ai.FacePattern5.exec(h))!==null)this._setDataForCurrentFaceWithPattern5(c[1].trim().split(" "),1);else if((c=Ai.FacePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "),1);else if((c=Ai.FacePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "),1);else if((c=Ai.LinePattern1.exec(h))!==null)this._setDataForCurrentFaceWithPattern1(c[1].trim().split(" "),0);else if((c=Ai.LinePattern2.exec(h))!==null)this._setDataForCurrentFaceWithPattern2(c[1].trim().split(" "),0);else if((c=Ai.LinePattern3.exec(h))!==null)this._setDataForCurrentFaceWithPattern3(c[1].trim().split(" "),0);else if(Ai.GroupDescriptor.test(h)||Ai.ObjectDescriptor.test(h)){const u={name:h.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:Ai.ObjectDescriptor.test(h)};this._addPreviousObjMesh(),this._meshesFromObj.push(u),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(Ai.UseMtlDescriptor.test(h)){if(this._materialNameFromObj=h.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const u={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(u),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else Ai.MtlLibGroupDescriptor.test(h)?r(h.substring(7).trim()):Ai.SmoothDescriptor.test(h)||U.Log("Unhandled expression at line : "+h)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let l=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const h of this._positions)this._unwrappedPositionsForBabylon.push(h.x,h.y,h.z);if(this._normals.length)for(const h of this._normals)this._unwrappedNormalsForBabylon.push(h.x,h.y,h.z);if(this._uvs.length)for(const h of this._uvs)this._unwrappedUVForBabylon.push(h.x,h.y);if(this._colors.length)for(const h of this._colors)this._unwrappedColorsForBabylon.push(h.r,h.g,h.b,h.a);this._materialNameFromObj||(l=new Ie(Is.RandomId(),i),l.pointsCloud=!0,this._materialNameFromObj=l.name,this._normals.length||(l.disableLighting=!0,l.emissiveColor=re.White()))}this._meshesFromObj.push({name:Is.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:l,isObject:!0})}for(let l=0;l=0;--u)if(this._meshesFromObj[u].isObject&&this._meshesFromObj[u]._babylonMesh){h.parent=this._meshesFromObj[u]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[l].materialName),((o=this._handledMesh.positions)==null?void 0:o.length)===0){this._babylonMeshesArray.push(h);continue}const c=new Se;if(c.uvs=this._handledMesh.uvs,c.indices=this._handledMesh.indices,c.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const u=new Array;Se.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,u),c.normals=u}else c.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(c.colors=this._handledMesh.colors),c.applyToMesh(h),this._loadingOptions.invertY&&(h.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(h),this._babylonMeshesArray.push(h),this._handledMesh.directMaterial&&(h.material=this._handledMesh.directMaterial)}}}Ai.ObjectDescriptor=/^o/;Ai.GroupDescriptor=/^g/;Ai.MtlLibGroupDescriptor=/^mtllib /;Ai.UseMtlDescriptor=/^usemtl /;Ai.SmoothDescriptor=/^s /;Ai.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Ai.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Ai.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Ai.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Ai.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Ai.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Ai.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Ai.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Ai.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Ai.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Ai.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class Rs{static get INVERT_TEXTURE_Y(){return eo.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){eo.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||Rs._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:Rs.COMPUTE_NORMALS,optimizeNormals:Rs.OPTIMIZE_NORMALS,importVertexColors:Rs.IMPORT_VERTEX_COLORS,invertY:Rs.INVERT_Y,invertTextureY:Rs.INVERT_TEXTURE_Y,UVScaling:Rs.UV_SCALING,materialLoadingFailsSilently:Rs.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:Rs.OPTIMIZE_WITH_UV,skipMaterials:Rs.SKIP_MATERIALS,useLegacyBehavior:Rs.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;Z.LoadFile(r,i,void 0,void 0,!1,(n,o)=>{s(r,o)})}createPlugin(){return new Rs(Rs._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then(r=>({meshes:r,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){const s=new Kg(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).then(r=>(r.meshes.forEach(n=>s.meshes.push(n)),r.meshes.forEach(n=>{const o=n.material;o&&s.materials.indexOf(o)==-1&&(s.materials.push(o),o.getActiveTextures().forEach(h=>{s.textures.indexOf(h)==-1&&s.textures.push(h)}))}),this._assetContainer=null,s)).catch(r=>{throw this._assetContainer=null,r})}_parseSolid(e,t,i,s){let r="";const n=new eo,o=[],l=[];new Ai(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,u=>{r=u});const c=[];return r!==""&&!this._loadingOptions.skipMaterials&&c.push(new Promise((u,d)=>{this._loadMTL(r,s,f=>{try{n.parseMTL(t,f,s,this._assetContainer);for(let m=0;m-1;)x.push(E),_=E+1;if(E===-1&&x.length===0)n.materials[m].dispose();else for(let S=0;S{Z.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?u():d(m)})})),Promise.all(c).then(()=>l)}}Rs.OPTIMIZE_WITH_UV=!0;Rs.INVERT_Y=!1;Rs.IMPORT_VERTEX_COLORS=!1;Rs.COMPUTE_NORMALS=!1;Rs.OPTIMIZE_NORMALS=!1;Rs.UV_SCALING=new ce(1,1);Rs.SKIP_MATERIALS=!1;Rs.MATERIAL_LOADING_FAILS_SILENTLY=!0;Rs.USE_LEGACY_BEHAVIOR=!1;ft&&ft.RegisterPlugin(new Rs);class ic{constructor(){this.solidPattern=/solid (\S*)([\S\s]*?)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,this.normalPattern=/normal[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.vertexPattern=/vertex[\s]+([-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+[\s]+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)+/g,this.name="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if(typeof i!="string"){if(this._isBinary(i)){const o=new q("stlmesh",t);return this._parseBinary(o,i),r&&r.push(o),!0}i=new TextDecoder().decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let o=n[1];const l=n[3];if(l&&o!=l)return Z.Error("Error in STL, solid name != endsolid name"),!1;if(e&&o){if(e instanceof Array){if(!e.indexOf(o))continue}else if(o!==e)continue}o=o||"stlmesh";const h=new q(o,t);this._parseASCII(h,n[2]),r&&r.push(h)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new Kg(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,s.meshes),e._blockEntityCollection=!1,s}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;const i=32/8*3+32/8*3*3+16/8,s=t.getUint32(80,!0);if(80+32/8+s*i===t.byteLength)return!0;const r=[115,111,108,105,100];for(let n=0;n<5;n++)if(t.getUint8(n)!==r[n])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0),r=84,n=12*4+2;let o=0;const l=new Float32Array(s*3*3),h=new Float32Array(s*3*3),c=new Uint32Array(s*3);let u=0;for(let d=0;d + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Fg.exports;(function(a,e){(function(){var t,i="4.17.21",s=200,r="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",n="Expected a function",o="Invalid `variable` option passed into `_.template`",l="__lodash_hash_undefined__",h=500,c="__lodash_placeholder__",u=1,d=2,f=4,m=1,_=2,x=1,E=2,S=4,C=8,y=16,A=32,I=64,R=128,N=256,k=512,B=30,Q="...",ne=800,de=16,ge=1,fe=2,Ee=3,De=1/0,Te=9007199254740991,ue=17976931348623157e292,oe=NaN,F=4294967295,ie=F-1,he=F>>>1,ke=[["ary",R],["bind",x],["bindKey",E],["curry",C],["curryRight",y],["flip",k],["partial",A],["partialRight",I],["rearg",N]],Ye="[object Arguments]",et="[object Array]",ye="[object AsyncFunction]",Ae="[object Boolean]",rt="[object Date]",Ze="[object DOMException]",Et="[object Error]",Re="[object Function]",St="[object GeneratorFunction]",Lt="[object Map]",Ci="[object Number]",ki="[object Null]",Ts="[object Object]",ar="[object Promise]",fo="[object Proxy]",Rn="[object RegExp]",br="[object Set]",qr="[object String]",po="[object Symbol]",Rl="[object Undefined]",Sa="[object WeakMap]",Il="[object WeakSet]",zr="[object ArrayBuffer]",Wr="[object DataView]",jn="[object Float32Array]",Ga="[object Float64Array]",xi="[object Int8Array]",_o="[object Int16Array]",mo="[object Int32Array]",In="[object Uint8Array]",un="[object Uint8ClampedArray]",Nr="[object Uint16Array]",va="[object Uint32Array]",L_=/\b__p \+= '';/g,yc=/\b(__p \+=) '' \+/g,Rf=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Dh=/&(?:amp|lt|gt|quot|#39);/g,pr=/[&<>"']/g,If=RegExp(Dh.source),B_=RegExp(pr.source),U_=/<%-([\s\S]+?)%>/g,V_=/<%([\s\S]+?)%>/g,Pf=/<%=([\s\S]+?)%>/g,Pl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ml=/^\w*$/,Ac=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Rc=/[\\^$.*+?()[\]{}|]/g,Ic=RegExp(Rc.source),go=/^\s+/,Pn=/\s/,Mf=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,kO=/\{\n\/\* \[wrapped with (.+)\] \*/,GO=/,? & /,zO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,WO=/[()=,{}\[\]\/\s]/,HO=/\\(\\)?/g,XO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,WC=/\w*$/,YO=/^[-+]0x[0-9a-f]+$/i,$O=/^0b[01]+$/i,KO=/^\[object .+?Constructor\]$/,jO=/^0o[0-7]+$/i,qO=/^(?:0|[1-9]\d*)$/,QO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,k_=/($^)/,ZO=/['\n\r\u2028\u2029\\]/g,G_="\\ud800-\\udfff",JO="\\u0300-\\u036f",eD="\\ufe20-\\ufe2f",tD="\\u20d0-\\u20ff",HC=JO+eD+tD,XC="\\u2700-\\u27bf",YC="a-z\\xdf-\\xf6\\xf8-\\xff",iD="\\xac\\xb1\\xd7\\xf7",sD="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rD="\\u2000-\\u206f",nD=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",$C="A-Z\\xc0-\\xd6\\xd8-\\xde",KC="\\ufe0e\\ufe0f",jC=iD+sD+rD+nD,Xx="['’]",aD="["+G_+"]",qC="["+jC+"]",z_="["+HC+"]",QC="\\d+",oD="["+XC+"]",ZC="["+YC+"]",JC="[^"+G_+jC+QC+XC+YC+$C+"]",Yx="\\ud83c[\\udffb-\\udfff]",lD="(?:"+z_+"|"+Yx+")",eb="[^"+G_+"]",$x="(?:\\ud83c[\\udde6-\\uddff]){2}",Kx="[\\ud800-\\udbff][\\udc00-\\udfff]",Pc="["+$C+"]",tb="\\u200d",ib="(?:"+ZC+"|"+JC+")",hD="(?:"+Pc+"|"+JC+")",sb="(?:"+Xx+"(?:d|ll|m|re|s|t|ve))?",rb="(?:"+Xx+"(?:D|LL|M|RE|S|T|VE))?",nb=lD+"?",ab="["+KC+"]?",cD="(?:"+tb+"(?:"+[eb,$x,Kx].join("|")+")"+ab+nb+")*",uD="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",dD="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",ob=ab+nb+cD,fD="(?:"+[oD,$x,Kx].join("|")+")"+ob,pD="(?:"+[eb+z_+"?",z_,$x,Kx,aD].join("|")+")",_D=RegExp(Xx,"g"),mD=RegExp(z_,"g"),jx=RegExp(Yx+"(?="+Yx+")|"+pD+ob,"g"),gD=RegExp([Pc+"?"+ZC+"+"+sb+"(?="+[qC,Pc,"$"].join("|")+")",hD+"+"+rb+"(?="+[qC,Pc+ib,"$"].join("|")+")",Pc+"?"+ib+"+"+sb,Pc+"+"+rb,dD,uD,QC,fD].join("|"),"g"),xD=RegExp("["+tb+G_+HC+KC+"]"),TD=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ED=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],SD=-1,Es={};Es[jn]=Es[Ga]=Es[xi]=Es[_o]=Es[mo]=Es[In]=Es[un]=Es[Nr]=Es[va]=!0,Es[Ye]=Es[et]=Es[zr]=Es[Ae]=Es[Wr]=Es[rt]=Es[Et]=Es[Re]=Es[Lt]=Es[Ci]=Es[Ts]=Es[Rn]=Es[br]=Es[qr]=Es[Sa]=!1;var ds={};ds[Ye]=ds[et]=ds[zr]=ds[Wr]=ds[Ae]=ds[rt]=ds[jn]=ds[Ga]=ds[xi]=ds[_o]=ds[mo]=ds[Lt]=ds[Ci]=ds[Ts]=ds[Rn]=ds[br]=ds[qr]=ds[po]=ds[In]=ds[un]=ds[Nr]=ds[va]=!0,ds[Et]=ds[Re]=ds[Sa]=!1;var vD={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},CD={"&":"&","<":"<",">":">",'"':""","'":"'"},bD={"&":"&","<":"<",">":">",""":'"',"'":"'"},yD={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},AD=parseFloat,RD=parseInt,lb=typeof Qf=="object"&&Qf&&Qf.Object===Object&&Qf,ID=typeof self=="object"&&self&&self.Object===Object&&self,Hr=lb||ID||Function("return this")(),qx=e&&!e.nodeType&&e,Nh=qx&&!0&&a&&!a.nodeType&&a,hb=Nh&&Nh.exports===qx,Qx=hb&&lb.process,Ca=function(){try{var me=Nh&&Nh.require&&Nh.require("util").types;return me||Qx&&Qx.binding&&Qx.binding("util")}catch{}}(),cb=Ca&&Ca.isArrayBuffer,ub=Ca&&Ca.isDate,db=Ca&&Ca.isMap,fb=Ca&&Ca.isRegExp,pb=Ca&&Ca.isSet,_b=Ca&&Ca.isTypedArray;function qn(me,Me,be){switch(be.length){case 0:return me.call(Me);case 1:return me.call(Me,be[0]);case 2:return me.call(Me,be[0],be[1]);case 3:return me.call(Me,be[0],be[1],be[2])}return me.apply(Me,be)}function PD(me,Me,be,Tt){for(var Xt=-1,Gi=me==null?0:me.length;++Xt-1}function Zx(me,Me,be){for(var Tt=-1,Xt=me==null?0:me.length;++Tt-1;);return be}function Cb(me,Me){for(var be=me.length;be--&&Mc(Me,me[be],0)>-1;);return be}function UD(me,Me){for(var be=me.length,Tt=0;be--;)me[be]===Me&&++Tt;return Tt}var VD=iT(vD),kD=iT(CD);function GD(me){return"\\"+yD[me]}function zD(me,Me){return me==null?t:me[Me]}function Oc(me){return xD.test(me)}function WD(me){return TD.test(me)}function HD(me){for(var Me,be=[];!(Me=me.next()).done;)be.push(Me.value);return be}function aT(me){var Me=-1,be=Array(me.size);return me.forEach(function(Tt,Xt){be[++Me]=[Xt,Tt]}),be}function bb(me,Me){return function(be){return me(Me(be))}}function Nl(me,Me){for(var be=-1,Tt=me.length,Xt=0,Gi=[];++be-1}function ON(p,g){var b=this.__data__,D=am(b,p);return D<0?(++this.size,b.push([p,g])):b[D][1]=g,this}Ko.prototype.clear=RN,Ko.prototype.delete=IN,Ko.prototype.get=PN,Ko.prototype.has=MN,Ko.prototype.set=ON;function jo(p){var g=-1,b=p==null?0:p.length;for(this.clear();++g=g?p:g)),p}function Ra(p,g,b,D,G,$){var se,le=g&u,xe=g&d,we=g&f;if(b&&(se=G?b(p,D,G,$):b(p)),se!==t)return se;if(!Ds(p))return p;var Le=jt(p);if(Le){if(se=Fw(p),!le)return Mn(p,se)}else{var Ge=Zr(p),dt=Ge==Re||Ge==St;if(Vl(p))return ay(p,le);if(Ge==Ts||Ge==Ye||dt&&!G){if(se=xe||dt?{}:yy(p),!le)return xe?bw(p,$N(se,p)):Cw(p,Lb(se,p))}else{if(!ds[Ge])return G?p:{};se=Lw(p,Ge,le)}}$||($=new Wa);var Rt=$.get(p);if(Rt)return Rt;$.set(p,se),eA(p)?p.forEach(function(Ut){se.add(Ra(Ut,g,b,Ut,p,$))}):Zy(p)&&p.forEach(function(Ut,fi){se.set(fi,Ra(Ut,g,b,fi,p,$))});var Bt=we?xe?DT:OT:xe?Dn:wr,ai=Le?t:Bt(p);return ba(ai||p,function(Ut,fi){ai&&(fi=Ut,Ut=p[fi]),Bf(se,fi,Ra(Ut,g,b,fi,p,$))}),se}function KN(p){var g=wr(p);return function(b){return Bb(b,p,g)}}function Bb(p,g,b){var D=b.length;if(p==null)return!D;for(p=as(p);D--;){var G=b[D],$=g[G],se=p[G];if(se===t&&!(G in p)||!$(se))return!1}return!0}function Ub(p,g,b){if(typeof p!="function")throw new ya(n);return Hf(function(){p.apply(t,b)},g)}function Uf(p,g,b,D){var G=-1,$=W_,se=!0,le=p.length,xe=[],we=g.length;if(!le)return xe;b&&(g=As(g,Qn(b))),D?($=Zx,se=!1):g.length>=s&&($=Of,se=!1,g=new Lh(g));e:for(;++GG?0:G+b),D=D===t||D>G?G:ii(D),D<0&&(D+=G),D=b>D?0:iA(D);b0&&b(le)?g>1?Xr(le,g-1,b,D,G):Dl(G,le):D||(G[G.length]=le)}return G}var fT=dy(),Gb=dy(!0);function xo(p,g){return p&&fT(p,g,wr)}function pT(p,g){return p&&Gb(p,g,wr)}function lm(p,g){return Ol(g,function(b){return el(p[b])})}function Uh(p,g){g=Bl(g,p);for(var b=0,D=g.length;p!=null&&bg}function QN(p,g){return p!=null&&Zi.call(p,g)}function ZN(p,g){return p!=null&&g in as(p)}function JN(p,g,b){return p>=Qr(g,b)&&p=120&&Le.length>=120)?new Lh(se&&Le):t}Le=p[0];var Ge=-1,dt=le[0];e:for(;++Ge-1;)le!==p&&J_.call(le,xe,1),J_.call(p,xe,1);return p}function Zb(p,g){for(var b=p?g.length:0,D=b-1;b--;){var G=g[b];if(b==D||G!==$){var $=G;Jo(G)?J_.call(p,G,1):bT(p,G)}}return p}function ST(p,g){return p+im(Db()*(g-p+1))}function dw(p,g,b,D){for(var G=-1,$=Ar(tm((g-p)/(b||1)),0),se=be($);$--;)se[D?$:++G]=p,p+=b;return se}function vT(p,g){var b="";if(!p||g<1||g>Te)return b;do g%2&&(b+=p),g=im(g/2),g&&(p+=p);while(g);return b}function li(p,g){return VT(Iy(p,g,Nn),p+"")}function fw(p){return Fb(zc(p))}function pw(p,g){var b=zc(p);return Tm(b,Bh(g,0,b.length))}function Gf(p,g,b,D){if(!Ds(p))return p;g=Bl(g,p);for(var G=-1,$=g.length,se=$-1,le=p;le!=null&&++G<$;){var xe=Eo(g[G]),we=b;if(xe==="__proto__"||xe==="constructor"||xe==="prototype")return p;if(G!=se){var Le=le[xe];we=D?D(Le,xe,le):t,we===t&&(we=Ds(Le)?Le:Jo(g[G+1])?[]:{})}Bf(le,xe,we),le=le[xe]}return p}var Jb=sm?function(p,g){return sm.set(p,g),p}:Nn,_w=em?function(p,g){return em(p,"toString",{configurable:!0,enumerable:!1,value:jT(g),writable:!0})}:Nn;function mw(p){return Tm(zc(p))}function Ia(p,g,b){var D=-1,G=p.length;g<0&&(g=-g>G?0:G+g),b=b>G?G:b,b<0&&(b+=G),G=g>b?0:b-g>>>0,g>>>=0;for(var $=be(G);++D>>1,se=p[$];se!==null&&!Jn(se)&&(b?se<=g:se=s){var we=g?null:Iw(p);if(we)return X_(we);se=!1,G=Of,xe=new Lh}else xe=g?[]:le;e:for(;++D<$;){var Le=p[D],Ge=g?g(Le):Le;if(Le=b||Le!==0?Le:0,se&&Ge===Ge){for(var dt=xe.length;dt--;)if(xe[dt]===Ge)continue e;g&&xe.push(Ge),le.push(Le)}else G(xe,Ge,b)||(xe!==le&&xe.push(Ge),le.push(Le))}return le}function bT(p,g){return g=Bl(g,p),p=Py(p,g),p==null||delete p[Eo(Pa(g))]}function iy(p,g,b,D){return Gf(p,g,b(Uh(p,g)),D)}function um(p,g,b,D){for(var G=p.length,$=D?G:-1;(D?$--:++$=D?p:Ia(p,g,b)}var ny=nN||function(p){return Hr.clearTimeout(p)};function ay(p,g){if(g)return p.slice();var b=p.length,D=Rb?Rb(b):new p.constructor(b);return p.copy(D),D}function IT(p){var g=new p.constructor(p.byteLength);return new Q_(g).set(new Q_(p)),g}function Tw(p,g){var b=g?IT(p.buffer):p.buffer;return new p.constructor(b,p.byteOffset,p.byteLength)}function Ew(p){var g=new p.constructor(p.source,WC.exec(p));return g.lastIndex=p.lastIndex,g}function Sw(p){return Lf?as(Lf.call(p)):{}}function oy(p,g){var b=g?IT(p.buffer):p.buffer;return new p.constructor(b,p.byteOffset,p.length)}function ly(p,g){if(p!==g){var b=p!==t,D=p===null,G=p===p,$=Jn(p),se=g!==t,le=g===null,xe=g===g,we=Jn(g);if(!le&&!we&&!$&&p>g||$&&se&&xe&&!le&&!we||D&&se&&xe||!b&&xe||!G)return 1;if(!D&&!$&&!we&&p=le)return xe;var we=b[D];return xe*(we=="desc"?-1:1)}}return p.index-g.index}function hy(p,g,b,D){for(var G=-1,$=p.length,se=b.length,le=-1,xe=g.length,we=Ar($-se,0),Le=be(xe+we),Ge=!D;++le1?b[G-1]:t,se=G>2?b[2]:t;for($=p.length>3&&typeof $=="function"?(G--,$):t,se&&fn(b[0],b[1],se)&&($=G<3?t:$,G=1),g=as(g);++D-1?G[$?g[se]:se]:t}}function _y(p){return Zo(function(g){var b=g.length,D=b,G=Aa.prototype.thru;for(p&&g.reverse();D--;){var $=g[D];if(typeof $!="function")throw new ya(n);if(G&&!se&&gm($)=="wrapper")var se=new Aa([],!0)}for(D=se?D:b;++D1&&bi.reverse(),Le&&xele))return!1;var we=$.get(p),Le=$.get(g);if(we&&Le)return we==g&&Le==p;var Ge=-1,dt=!0,Rt=b&_?new Lh:t;for($.set(p,g),$.set(g,p);++Ge1?"& ":"")+g[D],g=g.join(b>2?", ":" "),p.replace(Mf,`{ +/* [wrapped with `+g+`] */ +`)}function Uw(p){return jt(p)||Gh(p)||!!(Mb&&p&&p[Mb])}function Jo(p,g){var b=typeof p;return g=g??Te,!!g&&(b=="number"||b!="symbol"&&qO.test(p))&&p>-1&&p%1==0&&p0){if(++g>=ne)return arguments[0]}else g=0;return p.apply(t,arguments)}}function Tm(p,g){var b=-1,D=p.length,G=D-1;for(g=g===t?D:g;++b1?p[g-1]:t;return b=typeof b=="function"?(p.pop(),b):t,ky(p,b)});function Gy(p){var g=Y(p);return g.__chain__=!0,g}function jF(p,g){return g(p),p}function Em(p,g){return g(p)}var qF=Zo(function(p){var g=p.length,b=g?p[0]:0,D=this.__wrapped__,G=function($){return dT($,p)};return g>1||this.__actions__.length||!(D instanceof Ti)||!Jo(b)?this.thru(G):(D=D.slice(b,+b+(g?1:0)),D.__actions__.push({func:Em,args:[G],thisArg:t}),new Aa(D,this.__chain__).thru(function($){return g&&!$.length&&$.push(t),$}))});function QF(){return Gy(this)}function ZF(){return new Aa(this.value(),this.__chain__)}function JF(){this.__values__===t&&(this.__values__=tA(this.value()));var p=this.__index__>=this.__values__.length,g=p?t:this.__values__[this.__index__++];return{done:p,value:g}}function e1(){return this}function t1(p){for(var g,b=this;b instanceof nm;){var D=wy(b);D.__index__=0,D.__values__=t,g?G.__wrapped__=D:g=D;var G=D;b=b.__wrapped__}return G.__wrapped__=p,g}function i1(){var p=this.__wrapped__;if(p instanceof Ti){var g=p;return this.__actions__.length&&(g=new Ti(this)),g=g.reverse(),g.__actions__.push({func:Em,args:[kT],thisArg:t}),new Aa(g,this.__chain__)}return this.thru(kT)}function s1(){return sy(this.__wrapped__,this.__actions__)}var r1=dm(function(p,g,b){Zi.call(p,b)?++p[b]:qo(p,b,1)});function n1(p,g,b){var D=jt(p)?mb:jN;return b&&fn(p,g,b)&&(g=t),D(p,Nt(g,3))}function a1(p,g){var b=jt(p)?Ol:kb;return b(p,Nt(g,3))}var o1=py(Fy),l1=py(Ly);function h1(p,g){return Xr(Sm(p,g),1)}function c1(p,g){return Xr(Sm(p,g),De)}function u1(p,g,b){return b=b===t?1:ii(b),Xr(Sm(p,g),b)}function zy(p,g){var b=jt(p)?ba:Fl;return b(p,Nt(g,3))}function Wy(p,g){var b=jt(p)?MD:Vb;return b(p,Nt(g,3))}var d1=dm(function(p,g,b){Zi.call(p,b)?p[b].push(g):qo(p,b,[g])});function f1(p,g,b,D){p=On(p)?p:zc(p),b=b&&!D?ii(b):0;var G=p.length;return b<0&&(b=Ar(G+b,0)),Am(p)?b<=G&&p.indexOf(g,b)>-1:!!G&&Mc(p,g,b)>-1}var p1=li(function(p,g,b){var D=-1,G=typeof g=="function",$=On(p)?be(p.length):[];return Fl(p,function(se){$[++D]=G?qn(g,se,b):Vf(se,g,b)}),$}),_1=dm(function(p,g,b){qo(p,b,g)});function Sm(p,g){var b=jt(p)?As:Yb;return b(p,Nt(g,3))}function m1(p,g,b,D){return p==null?[]:(jt(g)||(g=g==null?[]:[g]),b=D?t:b,jt(b)||(b=b==null?[]:[b]),qb(p,g,b))}var g1=dm(function(p,g,b){p[b?0:1].push(g)},function(){return[[],[]]});function x1(p,g,b){var D=jt(p)?Jx:Eb,G=arguments.length<3;return D(p,Nt(g,4),b,G,Fl)}function T1(p,g,b){var D=jt(p)?OD:Eb,G=arguments.length<3;return D(p,Nt(g,4),b,G,Vb)}function E1(p,g){var b=jt(p)?Ol:kb;return b(p,bm(Nt(g,3)))}function S1(p){var g=jt(p)?Fb:fw;return g(p)}function v1(p,g,b){(b?fn(p,g,b):g===t)?g=1:g=ii(g);var D=jt(p)?HN:pw;return D(p,g)}function C1(p){var g=jt(p)?XN:mw;return g(p)}function b1(p){if(p==null)return 0;if(On(p))return Am(p)?Dc(p):p.length;var g=Zr(p);return g==Lt||g==br?p.size:xT(p).length}function y1(p,g,b){var D=jt(p)?eT:gw;return b&&fn(p,g,b)&&(g=t),D(p,Nt(g,3))}var A1=li(function(p,g){if(p==null)return[];var b=g.length;return b>1&&fn(p,g[0],g[1])?g=[]:b>2&&fn(g[0],g[1],g[2])&&(g=[g[0]]),qb(p,Xr(g,1),[])}),vm=aN||function(){return Hr.Date.now()};function R1(p,g){if(typeof g!="function")throw new ya(n);return p=ii(p),function(){if(--p<1)return g.apply(this,arguments)}}function Hy(p,g,b){return g=b?t:g,g=p&&g==null?p.length:g,Qo(p,R,t,t,t,t,g)}function Xy(p,g){var b;if(typeof g!="function")throw new ya(n);return p=ii(p),function(){return--p>0&&(b=g.apply(this,arguments)),p<=1&&(g=t),b}}var zT=li(function(p,g,b){var D=x;if(b.length){var G=Nl(b,kc(zT));D|=A}return Qo(p,D,g,b,G)}),Yy=li(function(p,g,b){var D=x|E;if(b.length){var G=Nl(b,kc(Yy));D|=A}return Qo(g,D,p,b,G)});function $y(p,g,b){g=b?t:g;var D=Qo(p,C,t,t,t,t,t,g);return D.placeholder=$y.placeholder,D}function Ky(p,g,b){g=b?t:g;var D=Qo(p,y,t,t,t,t,t,g);return D.placeholder=Ky.placeholder,D}function jy(p,g,b){var D,G,$,se,le,xe,we=0,Le=!1,Ge=!1,dt=!0;if(typeof p!="function")throw new ya(n);g=Ma(g)||0,Ds(b)&&(Le=!!b.leading,Ge="maxWait"in b,$=Ge?Ar(Ma(b.maxWait)||0,g):$,dt="trailing"in b?!!b.trailing:dt);function Rt(lr){var Xa=D,il=G;return D=G=t,we=lr,se=p.apply(il,Xa),se}function Bt(lr){return we=lr,le=Hf(fi,g),Le?Rt(lr):se}function ai(lr){var Xa=lr-xe,il=lr-we,pA=g-Xa;return Ge?Qr(pA,$-il):pA}function Ut(lr){var Xa=lr-xe,il=lr-we;return xe===t||Xa>=g||Xa<0||Ge&&il>=$}function fi(){var lr=vm();if(Ut(lr))return bi(lr);le=Hf(fi,ai(lr))}function bi(lr){return le=t,dt&&D?Rt(lr):(D=G=t,se)}function ea(){le!==t&&ny(le),we=0,D=xe=G=le=t}function pn(){return le===t?se:bi(vm())}function ta(){var lr=vm(),Xa=Ut(lr);if(D=arguments,G=this,xe=lr,Xa){if(le===t)return Bt(xe);if(Ge)return ny(le),le=Hf(fi,g),Rt(xe)}return le===t&&(le=Hf(fi,g)),se}return ta.cancel=ea,ta.flush=pn,ta}var I1=li(function(p,g){return Ub(p,1,g)}),P1=li(function(p,g,b){return Ub(p,Ma(g)||0,b)});function M1(p){return Qo(p,k)}function Cm(p,g){if(typeof p!="function"||g!=null&&typeof g!="function")throw new ya(n);var b=function(){var D=arguments,G=g?g.apply(this,D):D[0],$=b.cache;if($.has(G))return $.get(G);var se=p.apply(this,D);return b.cache=$.set(G,se)||$,se};return b.cache=new(Cm.Cache||jo),b}Cm.Cache=jo;function bm(p){if(typeof p!="function")throw new ya(n);return function(){var g=arguments;switch(g.length){case 0:return!p.call(this);case 1:return!p.call(this,g[0]);case 2:return!p.call(this,g[0],g[1]);case 3:return!p.call(this,g[0],g[1],g[2])}return!p.apply(this,g)}}function O1(p){return Xy(2,p)}var D1=xw(function(p,g){g=g.length==1&&jt(g[0])?As(g[0],Qn(Nt())):As(Xr(g,1),Qn(Nt()));var b=g.length;return li(function(D){for(var G=-1,$=Qr(D.length,b);++G<$;)D[G]=g[G].call(this,D[G]);return qn(p,this,D)})}),WT=li(function(p,g){var b=Nl(g,kc(WT));return Qo(p,A,t,g,b)}),qy=li(function(p,g){var b=Nl(g,kc(qy));return Qo(p,I,t,g,b)}),N1=Zo(function(p,g){return Qo(p,N,t,t,t,g)});function w1(p,g){if(typeof p!="function")throw new ya(n);return g=g===t?g:ii(g),li(p,g)}function F1(p,g){if(typeof p!="function")throw new ya(n);return g=g==null?0:Ar(ii(g),0),li(function(b){var D=b[g],G=Ul(b,0,g);return D&&Dl(G,D),qn(p,this,G)})}function L1(p,g,b){var D=!0,G=!0;if(typeof p!="function")throw new ya(n);return Ds(b)&&(D="leading"in b?!!b.leading:D,G="trailing"in b?!!b.trailing:G),jy(p,g,{leading:D,maxWait:g,trailing:G})}function B1(p){return Hy(p,1)}function U1(p,g){return WT(RT(g),p)}function V1(){if(!arguments.length)return[];var p=arguments[0];return jt(p)?p:[p]}function k1(p){return Ra(p,f)}function G1(p,g){return g=typeof g=="function"?g:t,Ra(p,f,g)}function z1(p){return Ra(p,u|f)}function W1(p,g){return g=typeof g=="function"?g:t,Ra(p,u|f,g)}function H1(p,g){return g==null||Bb(p,g,wr(g))}function Ha(p,g){return p===g||p!==p&&g!==g}var X1=mm(_T),Y1=mm(function(p,g){return p>=g}),Gh=Wb(function(){return arguments}())?Wb:function(p){return $s(p)&&Zi.call(p,"callee")&&!Pb.call(p,"callee")},jt=be.isArray,$1=cb?Qn(cb):tw;function On(p){return p!=null&&ym(p.length)&&!el(p)}function or(p){return $s(p)&&On(p)}function K1(p){return p===!0||p===!1||$s(p)&&dn(p)==Ae}var Vl=lN||eE,j1=ub?Qn(ub):iw;function q1(p){return $s(p)&&p.nodeType===1&&!Xf(p)}function Q1(p){if(p==null)return!0;if(On(p)&&(jt(p)||typeof p=="string"||typeof p.splice=="function"||Vl(p)||Gc(p)||Gh(p)))return!p.length;var g=Zr(p);if(g==Lt||g==br)return!p.size;if(Wf(p))return!xT(p).length;for(var b in p)if(Zi.call(p,b))return!1;return!0}function Z1(p,g){return kf(p,g)}function J1(p,g,b){b=typeof b=="function"?b:t;var D=b?b(p,g):t;return D===t?kf(p,g,t,b):!!D}function HT(p){if(!$s(p))return!1;var g=dn(p);return g==Et||g==Ze||typeof p.message=="string"&&typeof p.name=="string"&&!Xf(p)}function eL(p){return typeof p=="number"&&Ob(p)}function el(p){if(!Ds(p))return!1;var g=dn(p);return g==Re||g==St||g==ye||g==fo}function Qy(p){return typeof p=="number"&&p==ii(p)}function ym(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=Te}function Ds(p){var g=typeof p;return p!=null&&(g=="object"||g=="function")}function $s(p){return p!=null&&typeof p=="object"}var Zy=db?Qn(db):rw;function tL(p,g){return p===g||gT(p,g,wT(g))}function iL(p,g,b){return b=typeof b=="function"?b:t,gT(p,g,wT(g),b)}function sL(p){return Jy(p)&&p!=+p}function rL(p){if(Gw(p))throw new Xt(r);return Hb(p)}function nL(p){return p===null}function aL(p){return p==null}function Jy(p){return typeof p=="number"||$s(p)&&dn(p)==Ci}function Xf(p){if(!$s(p)||dn(p)!=Ts)return!1;var g=Z_(p);if(g===null)return!0;var b=Zi.call(g,"constructor")&&g.constructor;return typeof b=="function"&&b instanceof b&&K_.call(b)==iN}var XT=fb?Qn(fb):nw;function oL(p){return Qy(p)&&p>=-Te&&p<=Te}var eA=pb?Qn(pb):aw;function Am(p){return typeof p=="string"||!jt(p)&&$s(p)&&dn(p)==qr}function Jn(p){return typeof p=="symbol"||$s(p)&&dn(p)==po}var Gc=_b?Qn(_b):ow;function lL(p){return p===t}function hL(p){return $s(p)&&Zr(p)==Sa}function cL(p){return $s(p)&&dn(p)==Il}var uL=mm(TT),dL=mm(function(p,g){return p<=g});function tA(p){if(!p)return[];if(On(p))return Am(p)?za(p):Mn(p);if(Df&&p[Df])return HD(p[Df]());var g=Zr(p),b=g==Lt?aT:g==br?X_:zc;return b(p)}function tl(p){if(!p)return p===0?p:0;if(p=Ma(p),p===De||p===-De){var g=p<0?-1:1;return g*ue}return p===p?p:0}function ii(p){var g=tl(p),b=g%1;return g===g?b?g-b:g:0}function iA(p){return p?Bh(ii(p),0,F):0}function Ma(p){if(typeof p=="number")return p;if(Jn(p))return oe;if(Ds(p)){var g=typeof p.valueOf=="function"?p.valueOf():p;p=Ds(g)?g+"":g}if(typeof p!="string")return p===0?p:+p;p=Sb(p);var b=$O.test(p);return b||jO.test(p)?RD(p.slice(2),b?2:8):YO.test(p)?oe:+p}function sA(p){return To(p,Dn(p))}function fL(p){return p?Bh(ii(p),-Te,Te):p===0?p:0}function $i(p){return p==null?"":Zn(p)}var pL=Uc(function(p,g){if(Wf(g)||On(g)){To(g,wr(g),p);return}for(var b in g)Zi.call(g,b)&&Bf(p,b,g[b])}),rA=Uc(function(p,g){To(g,Dn(g),p)}),Rm=Uc(function(p,g,b,D){To(g,Dn(g),p,D)}),_L=Uc(function(p,g,b,D){To(g,wr(g),p,D)}),mL=Zo(dT);function gL(p,g){var b=Bc(p);return g==null?b:Lb(b,g)}var xL=li(function(p,g){p=as(p);var b=-1,D=g.length,G=D>2?g[2]:t;for(G&&fn(g[0],g[1],G)&&(D=1);++b1),$}),To(p,DT(p),b),D&&(b=Ra(b,u|d|f,Pw));for(var G=g.length;G--;)bT(b,g[G]);return b});function LL(p,g){return aA(p,bm(Nt(g)))}var BL=Zo(function(p,g){return p==null?{}:cw(p,g)});function aA(p,g){if(p==null)return{};var b=As(DT(p),function(D){return[D]});return g=Nt(g),Qb(p,b,function(D,G){return g(D,G[0])})}function UL(p,g,b){g=Bl(g,p);var D=-1,G=g.length;for(G||(G=1,p=t);++Dg){var D=p;p=g,g=D}if(b||p%1||g%1){var G=Db();return Qr(p+G*(g-p+AD("1e-"+((G+"").length-1))),g)}return ST(p,g)}var jL=Vc(function(p,g,b){return g=g.toLowerCase(),p+(b?hA(g):g)});function hA(p){return KT($i(p).toLowerCase())}function cA(p){return p=$i(p),p&&p.replace(QO,VD).replace(mD,"")}function qL(p,g,b){p=$i(p),g=Zn(g);var D=p.length;b=b===t?D:Bh(ii(b),0,D);var G=b;return b-=g.length,b>=0&&p.slice(b,G)==g}function QL(p){return p=$i(p),p&&B_.test(p)?p.replace(pr,kD):p}function ZL(p){return p=$i(p),p&&Ic.test(p)?p.replace(Rc,"\\$&"):p}var JL=Vc(function(p,g,b){return p+(b?"-":"")+g.toLowerCase()}),eB=Vc(function(p,g,b){return p+(b?" ":"")+g.toLowerCase()}),tB=fy("toLowerCase");function iB(p,g,b){p=$i(p),g=ii(g);var D=g?Dc(p):0;if(!g||D>=g)return p;var G=(g-D)/2;return _m(im(G),b)+p+_m(tm(G),b)}function sB(p,g,b){p=$i(p),g=ii(g);var D=g?Dc(p):0;return g&&D>>0,b?(p=$i(p),p&&(typeof g=="string"||g!=null&&!XT(g))&&(g=Zn(g),!g&&Oc(p))?Ul(za(p),0,b):p.split(g,b)):[]}var cB=Vc(function(p,g,b){return p+(b?" ":"")+KT(g)});function uB(p,g,b){return p=$i(p),b=b==null?0:Bh(ii(b),0,p.length),g=Zn(g),p.slice(b,b+g.length)==g}function dB(p,g,b){var D=Y.templateSettings;b&&fn(p,g,b)&&(g=t),p=$i(p),g=Rm({},g,D,Ey);var G=Rm({},g.imports,D.imports,Ey),$=wr(G),se=nT(G,$),le,xe,we=0,Le=g.interpolate||k_,Ge="__p += '",dt=oT((g.escape||k_).source+"|"+Le.source+"|"+(Le===Pf?XO:k_).source+"|"+(g.evaluate||k_).source+"|$","g"),Rt="//# sourceURL="+(Zi.call(g,"sourceURL")?(g.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++SD+"]")+` +`;p.replace(dt,function(Ut,fi,bi,ea,pn,ta){return bi||(bi=ea),Ge+=p.slice(we,ta).replace(ZO,GD),fi&&(le=!0,Ge+=`' + +__e(`+fi+`) + +'`),pn&&(xe=!0,Ge+=`'; +`+pn+`; +__p += '`),bi&&(Ge+=`' + +((__t = (`+bi+`)) == null ? '' : __t) + +'`),we=ta+Ut.length,Ut}),Ge+=`'; +`;var Bt=Zi.call(g,"variable")&&g.variable;if(!Bt)Ge=`with (obj) { +`+Ge+` +} +`;else if(WO.test(Bt))throw new Xt(o);Ge=(xe?Ge.replace(L_,""):Ge).replace(yc,"$1").replace(Rf,"$1;"),Ge="function("+(Bt||"obj")+`) { +`+(Bt?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(le?", __e = _.escape":"")+(xe?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+Ge+`return __p +}`;var ai=dA(function(){return Gi($,Rt+"return "+Ge).apply(t,se)});if(ai.source=Ge,HT(ai))throw ai;return ai}function fB(p){return $i(p).toLowerCase()}function pB(p){return $i(p).toUpperCase()}function _B(p,g,b){if(p=$i(p),p&&(b||g===t))return Sb(p);if(!p||!(g=Zn(g)))return p;var D=za(p),G=za(g),$=vb(D,G),se=Cb(D,G)+1;return Ul(D,$,se).join("")}function mB(p,g,b){if(p=$i(p),p&&(b||g===t))return p.slice(0,yb(p)+1);if(!p||!(g=Zn(g)))return p;var D=za(p),G=Cb(D,za(g))+1;return Ul(D,0,G).join("")}function gB(p,g,b){if(p=$i(p),p&&(b||g===t))return p.replace(go,"");if(!p||!(g=Zn(g)))return p;var D=za(p),G=vb(D,za(g));return Ul(D,G).join("")}function xB(p,g){var b=B,D=Q;if(Ds(g)){var G="separator"in g?g.separator:G;b="length"in g?ii(g.length):b,D="omission"in g?Zn(g.omission):D}p=$i(p);var $=p.length;if(Oc(p)){var se=za(p);$=se.length}if(b>=$)return p;var le=b-Dc(D);if(le<1)return D;var xe=se?Ul(se,0,le).join(""):p.slice(0,le);if(G===t)return xe+D;if(se&&(le+=xe.length-le),XT(G)){if(p.slice(le).search(G)){var we,Le=xe;for(G.global||(G=oT(G.source,$i(WC.exec(G))+"g")),G.lastIndex=0;we=G.exec(Le);)var Ge=we.index;xe=xe.slice(0,Ge===t?le:Ge)}}else if(p.indexOf(Zn(G),le)!=le){var dt=xe.lastIndexOf(G);dt>-1&&(xe=xe.slice(0,dt))}return xe+D}function TB(p){return p=$i(p),p&&If.test(p)?p.replace(Dh,KD):p}var EB=Vc(function(p,g,b){return p+(b?" ":"")+g.toUpperCase()}),KT=fy("toUpperCase");function uA(p,g,b){return p=$i(p),g=b?t:g,g===t?WD(p)?QD(p):wD(p):p.match(g)||[]}var dA=li(function(p,g){try{return qn(p,t,g)}catch(b){return HT(b)?b:new Xt(b)}}),SB=Zo(function(p,g){return ba(g,function(b){b=Eo(b),qo(p,b,zT(p[b],p))}),p});function vB(p){var g=p==null?0:p.length,b=Nt();return p=g?As(p,function(D){if(typeof D[1]!="function")throw new ya(n);return[b(D[0]),D[1]]}):[],li(function(D){for(var G=-1;++GTe)return[];var b=F,D=Qr(p,F);g=Nt(g),p-=F;for(var G=rT(D,g);++b0||g<0)?new Ti(b):(p<0?b=b.takeRight(-p):p&&(b=b.drop(p)),g!==t&&(g=ii(g),b=g<0?b.dropRight(-g):b.take(g-p)),b)},Ti.prototype.takeRightWhile=function(p){return this.reverse().takeWhile(p).reverse()},Ti.prototype.toArray=function(){return this.take(F)},xo(Ti.prototype,function(p,g){var b=/^(?:filter|find|map|reject)|While$/.test(g),D=/^(?:head|last)$/.test(g),G=Y[D?"take"+(g=="last"?"Right":""):g],$=D||/^find/.test(g);G&&(Y.prototype[g]=function(){var se=this.__wrapped__,le=D?[1]:arguments,xe=se instanceof Ti,we=le[0],Le=xe||jt(se),Ge=function(fi){var bi=G.apply(Y,Dl([fi],le));return D&&dt?bi[0]:bi};Le&&b&&typeof we=="function"&&we.length!=1&&(xe=Le=!1);var dt=this.__chain__,Rt=!!this.__actions__.length,Bt=$&&!dt,ai=xe&&!Rt;if(!$&&Le){se=ai?se:new Ti(this);var Ut=p.apply(se,le);return Ut.__actions__.push({func:Em,args:[Ge],thisArg:t}),new Aa(Ut,dt)}return Bt&&ai?p.apply(this,le):(Ut=this.thru(Ge),Bt?D?Ut.value()[0]:Ut.value():Ut)})}),ba(["pop","push","shift","sort","splice","unshift"],function(p){var g=Y_[p],b=/^(?:push|sort|unshift)$/.test(p)?"tap":"thru",D=/^(?:pop|shift)$/.test(p);Y.prototype[p]=function(){var G=arguments;if(D&&!this.__chain__){var $=this.value();return g.apply(jt($)?$:[],G)}return this[b](function(se){return g.apply(jt(se)?se:[],G)})}}),xo(Ti.prototype,function(p,g){var b=Y[g];if(b){var D=b.name+"";Zi.call(Lc,D)||(Lc[D]=[]),Lc[D].push({name:g,func:b})}}),Lc[fm(t,E).name]=[{name:"wrapper",func:t}],Ti.prototype.clone=TN,Ti.prototype.reverse=EN,Ti.prototype.value=SN,Y.prototype.at=qF,Y.prototype.chain=QF,Y.prototype.commit=ZF,Y.prototype.next=JF,Y.prototype.plant=t1,Y.prototype.reverse=i1,Y.prototype.toJSON=Y.prototype.valueOf=Y.prototype.value=s1,Y.prototype.first=Y.prototype.head,Df&&(Y.prototype[Df]=e1),Y},Nc=ZD();Nh?((Nh.exports=Nc)._=Nc,qx._=Nc):Hr._=Nc}).call(Qf)})(Fg,Fg.exports);var jc=Fg.exports;function hZ(a){return a.sort((e,t)=>a.filter(i=>i===e).length-a.filter(i=>i===t).length).pop()}function cZ(a,e){const t=a.map((r=>n=>r+=n)(0)),i=t[t.length-1];return Array.from({length:e},()=>Math.random()*i).sort((r,n)=>r-n).map((r=>n=>{for(;n>t[r];)r+=1;return r})(0))}function uZ(){let a=Math.random(),e=Math.random();return a+e>1&&(a=1-a,e=1-e),[1-a-e,a,e]}class dZ{constructor(e){So(this,"areas");So(this,"meshIdx");So(this,"triangleIdx");So(this,"vertices");So(this,"triangles");So(this,"uvs");this.meshes=e,this.vertices=[],this.triangles=[],this.uvs=[],e.forEach(t=>{const i=Se.ExtractFromMesh(t),s=jc.chunk(i.positions||[],3).map(o=>{const l=new T(...o);return l.multiply(t.absoluteScaling).rotateByQuaternionToRef(t.absoluteRotationQuaternion,l).add(t.absolutePosition)});this.vertices.push(s);const r=jc.chunk(i.indices||[],3);this.triangles.push(r);const n=jc.chunk(i.uvs||[],2);this.uvs.push(n)}),this.areas=[],this.meshIdx=[],this.triangleIdx=[],this.computeTriangleAreas()}computeTriangleAreas(){this.areas=[],this.meshIdx=[],this.triangles.forEach((e,t)=>{const i=this.vertices[t];e.map(([s,r,n],o)=>{const l=i[r].clone().subtract(i[s]),h=i[n].clone().subtract(i[s]);this.areas.push(l.cross(h).length()),this.meshIdx.push(t),this.triangleIdx.push(o)})})}async sampleAtLeastOnce(e){const t=Array(jc.sum(this.triangles.map(u=>u.length))).fill(1);cZ(this.areas,e).forEach(u=>{t[u]+=1});const i=[],s=[],r=[],n=[];let o=[];t.forEach((u,d)=>{const f=this.meshIdx[d],m=this.triangleIdx[d],[_,x,E]=this.triangles[f][m],S=this.vertices[f][_],C=this.vertices[f][x],y=this.vertices[f][E];[...Array(u)].forEach(()=>{var k,B,Q;const[A,I,R]=uZ(),N=C.clone().scale(I).add(y.clone().scale(R)).add(S.clone().scale(A));i.push(f),s.push(m),r.push(N);{const[ne,de]=((k=this.uvs[f])==null?void 0:k[_])||[0,0],[ge,fe]=((B=this.uvs[f])==null?void 0:B[x])||[0,0],[Ee,De]=((Q=this.uvs[f])==null?void 0:Q[E])||[0,0];n.push([ne*A+ge*I+Ee*R,de*A+fe*I+De*R])}})});const l=[],h=[],c=[];for(let u of this.meshes){if(u.material instanceof Xe){const d=u.material;if(d.albedoTexture){const{width:f,height:m}=d.albedoTexture.getSize(),_=await d.albedoTexture.readPixels();if(_&&_.constructor==Uint8Array){l.push(_),h.push(f),c.push(m);continue}}else{l.push(d.albedoColor),h.push(0),c.push(0);continue}}l.push(null),h.push(0),c.push(0)}return o=i.map((u,d)=>{const[f,m]=n[d],_=l[u],x=h[u],E=c[u];if(!_)return new re(.8,.8,.8);if(_ instanceof re)return _;const S=_[Math.floor(f*(x-1))*4+Math.floor(m*(E-1))*x*4],C=_[Math.floor(f*(x-1))*4+Math.floor(m*(E-1))*x*4+1],y=_[Math.floor(f*(x-1))*4+Math.floor(m*(E-1))*x*4+2];return new re(S/255,C/255,y/255)}),{points:r,faces:s,meshes:i,uvs:n,colors:o}}pointLabelToFaces(e,t,i){const s=this.meshes.map((r,n)=>Array.from({length:jc.sum(this.triangles[n].map(o=>o.length))},()=>[]));return jc.zip(e,t,i).map(([r,n,o])=>{s[r][n].push(o)}),s.map(r=>r.map(n=>hZ(n)))}}function TO(a,e){return function(){return a.apply(e,arguments)}}const{toString:fZ}=Object.prototype,{getPrototypeOf:BC}=Object,kx=(a=>e=>{const t=fZ.call(e);return a[t]||(a[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),$o=a=>(a=a.toLowerCase(),e=>kx(e)===a),Gx=a=>e=>typeof e===a,{isArray:Af}=Array,Jp=Gx("undefined");function pZ(a){return a!==null&&!Jp(a)&&a.constructor!==null&&!Jp(a.constructor)&&Ua(a.constructor.isBuffer)&&a.constructor.isBuffer(a)}const EO=$o("ArrayBuffer");function _Z(a){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(a):e=a&&a.buffer&&EO(a.buffer),e}const mZ=Gx("string"),Ua=Gx("function"),SO=Gx("number"),zx=a=>a!==null&&typeof a=="object",gZ=a=>a===!0||a===!1,ig=a=>{if(kx(a)!=="object")return!1;const e=BC(a);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in a)&&!(Symbol.iterator in a)},xZ=$o("Date"),TZ=$o("File"),EZ=$o("Blob"),SZ=$o("FileList"),vZ=a=>zx(a)&&Ua(a.pipe),CZ=a=>{let e;return a&&(typeof FormData=="function"&&a instanceof FormData||Ua(a.append)&&((e=kx(a))==="formdata"||e==="object"&&Ua(a.toString)&&a.toString()==="[object FormData]"))},bZ=$o("URLSearchParams"),yZ=a=>a.trim?a.trim():a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function w_(a,e,{allOwnKeys:t=!1}={}){if(a===null||typeof a>"u")return;let i,s;if(typeof a!="object"&&(a=[a]),Af(a))for(i=0,s=a.length;i0;)if(s=t[i],e===s.toLowerCase())return s;return null}const CO=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,bO=a=>!Jp(a)&&a!==CO;function jS(){const{caseless:a}=bO(this)&&this||{},e={},t=(i,s)=>{const r=a&&vO(e,s)||s;ig(e[r])&&ig(i)?e[r]=jS(e[r],i):ig(i)?e[r]=jS({},i):Af(i)?e[r]=i.slice():e[r]=i};for(let i=0,s=arguments.length;i(w_(e,(s,r)=>{t&&Ua(s)?a[r]=TO(s,t):a[r]=s},{allOwnKeys:i}),a),RZ=a=>(a.charCodeAt(0)===65279&&(a=a.slice(1)),a),IZ=(a,e,t,i)=>{a.prototype=Object.create(e.prototype,i),a.prototype.constructor=a,Object.defineProperty(a,"super",{value:e.prototype}),t&&Object.assign(a.prototype,t)},PZ=(a,e,t,i)=>{let s,r,n;const o={};if(e=e||{},a==null)return e;do{for(s=Object.getOwnPropertyNames(a),r=s.length;r-- >0;)n=s[r],(!i||i(n,a,e))&&!o[n]&&(e[n]=a[n],o[n]=!0);a=t!==!1&&BC(a)}while(a&&(!t||t(a,e))&&a!==Object.prototype);return e},MZ=(a,e,t)=>{a=String(a),(t===void 0||t>a.length)&&(t=a.length),t-=e.length;const i=a.indexOf(e,t);return i!==-1&&i===t},OZ=a=>{if(!a)return null;if(Af(a))return a;let e=a.length;if(!SO(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=a[e];return t},DZ=(a=>e=>a&&e instanceof a)(typeof Uint8Array<"u"&&BC(Uint8Array)),NZ=(a,e)=>{const i=(a&&a[Symbol.iterator]).call(a);let s;for(;(s=i.next())&&!s.done;){const r=s.value;e.call(a,r[0],r[1])}},wZ=(a,e)=>{let t;const i=[];for(;(t=a.exec(e))!==null;)i.push(t);return i},FZ=$o("HTMLFormElement"),LZ=a=>a.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,i,s){return i.toUpperCase()+s}),UR=(({hasOwnProperty:a})=>(e,t)=>a.call(e,t))(Object.prototype),BZ=$o("RegExp"),yO=(a,e)=>{const t=Object.getOwnPropertyDescriptors(a),i={};w_(t,(s,r)=>{let n;(n=e(s,r,a))!==!1&&(i[r]=n||s)}),Object.defineProperties(a,i)},UZ=a=>{yO(a,(e,t)=>{if(Ua(a)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const i=a[t];if(Ua(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},VZ=(a,e)=>{const t={},i=s=>{s.forEach(r=>{t[r]=!0})};return Af(a)?i(a):i(String(a).split(e)),t},kZ=()=>{},GZ=(a,e)=>(a=+a,Number.isFinite(a)?a:e),OE="abcdefghijklmnopqrstuvwxyz",VR="0123456789",AO={DIGIT:VR,ALPHA:OE,ALPHA_DIGIT:OE+OE.toUpperCase()+VR},zZ=(a=16,e=AO.ALPHA_DIGIT)=>{let t="";const{length:i}=e;for(;a--;)t+=e[Math.random()*i|0];return t};function WZ(a){return!!(a&&Ua(a.append)&&a[Symbol.toStringTag]==="FormData"&&a[Symbol.iterator])}const HZ=a=>{const e=new Array(10),t=(i,s)=>{if(zx(i)){if(e.indexOf(i)>=0)return;if(!("toJSON"in i)){e[s]=i;const r=Af(i)?[]:{};return w_(i,(n,o)=>{const l=t(n,s+1);!Jp(l)&&(r[o]=l)}),e[s]=void 0,r}}return i};return t(a,0)},XZ=$o("AsyncFunction"),YZ=a=>a&&(zx(a)||Ua(a))&&Ua(a.then)&&Ua(a.catch),Be={isArray:Af,isArrayBuffer:EO,isBuffer:pZ,isFormData:CZ,isArrayBufferView:_Z,isString:mZ,isNumber:SO,isBoolean:gZ,isObject:zx,isPlainObject:ig,isUndefined:Jp,isDate:xZ,isFile:TZ,isBlob:EZ,isRegExp:BZ,isFunction:Ua,isStream:vZ,isURLSearchParams:bZ,isTypedArray:DZ,isFileList:SZ,forEach:w_,merge:jS,extend:AZ,trim:yZ,stripBOM:RZ,inherits:IZ,toFlatObject:PZ,kindOf:kx,kindOfTest:$o,endsWith:MZ,toArray:OZ,forEachEntry:NZ,matchAll:wZ,isHTMLForm:FZ,hasOwnProperty:UR,hasOwnProp:UR,reduceDescriptors:yO,freezeMethods:UZ,toObjectSet:VZ,toCamelCase:LZ,noop:kZ,toFiniteNumber:GZ,findKey:vO,global:CO,isContextDefined:bO,ALPHABET:AO,generateString:zZ,isSpecCompliantForm:WZ,toJSONObject:HZ,isAsyncFn:XZ,isThenable:YZ};function Di(a,e,t,i,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=a,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),s&&(this.response=s)}Be.inherits(Di,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:Be.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const RO=Di.prototype,IO={};["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","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(a=>{IO[a]={value:a}});Object.defineProperties(Di,IO);Object.defineProperty(RO,"isAxiosError",{value:!0});Di.from=(a,e,t,i,s,r)=>{const n=Object.create(RO);return Be.toFlatObject(a,n,function(l){return l!==Error.prototype},o=>o!=="isAxiosError"),Di.call(n,a.message,e,t,i,s),n.cause=a,n.name=a.name,r&&Object.assign(n,r),n};const $Z=null;function qS(a){return Be.isPlainObject(a)||Be.isArray(a)}function PO(a){return Be.endsWith(a,"[]")?a.slice(0,-2):a}function kR(a,e,t){return a?a.concat(e).map(function(s,r){return s=PO(s),!t&&r?"["+s+"]":s}).join(t?".":""):e}function KZ(a){return Be.isArray(a)&&!a.some(qS)}const jZ=Be.toFlatObject(Be,{},null,function(e){return/^is[A-Z]/.test(e)});function Wx(a,e,t){if(!Be.isObject(a))throw new TypeError("target must be an object");e=e||new FormData,t=Be.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,x){return!Be.isUndefined(x[_])});const i=t.metaTokens,s=t.visitor||c,r=t.dots,n=t.indexes,l=(t.Blob||typeof Blob<"u"&&Blob)&&Be.isSpecCompliantForm(e);if(!Be.isFunction(s))throw new TypeError("visitor must be a function");function h(m){if(m===null)return"";if(Be.isDate(m))return m.toISOString();if(!l&&Be.isBlob(m))throw new Di("Blob is not supported. Use a Buffer instead.");return Be.isArrayBuffer(m)||Be.isTypedArray(m)?l&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function c(m,_,x){let E=m;if(m&&!x&&typeof m=="object"){if(Be.endsWith(_,"{}"))_=i?_:_.slice(0,-2),m=JSON.stringify(m);else if(Be.isArray(m)&&KZ(m)||(Be.isFileList(m)||Be.endsWith(_,"[]"))&&(E=Be.toArray(m)))return _=PO(_),E.forEach(function(C,y){!(Be.isUndefined(C)||C===null)&&e.append(n===!0?kR([_],y,r):n===null?_:_+"[]",h(C))}),!1}return qS(m)?!0:(e.append(kR(x,_,r),h(m)),!1)}const u=[],d=Object.assign(jZ,{defaultVisitor:c,convertValue:h,isVisitable:qS});function f(m,_){if(!Be.isUndefined(m)){if(u.indexOf(m)!==-1)throw Error("Circular reference detected in "+_.join("."));u.push(m),Be.forEach(m,function(E,S){(!(Be.isUndefined(E)||E===null)&&s.call(e,E,Be.isString(S)?S.trim():S,_,d))===!0&&f(E,_?_.concat(S):[S])}),u.pop()}}if(!Be.isObject(a))throw new TypeError("data must be an object");return f(a),e}function GR(a){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(a).replace(/[!'()~]|%20|%00/g,function(i){return e[i]})}function UC(a,e){this._pairs=[],a&&Wx(a,this,e)}const MO=UC.prototype;MO.append=function(e,t){this._pairs.push([e,t])};MO.toString=function(e){const t=e?function(i){return e.call(this,i,GR)}:GR;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function qZ(a){return encodeURIComponent(a).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function OO(a,e,t){if(!e)return a;const i=t&&t.encode||qZ,s=t&&t.serialize;let r;if(s?r=s(e,t):r=Be.isURLSearchParams(e)?e.toString():new UC(e,t).toString(i),r){const n=a.indexOf("#");n!==-1&&(a=a.slice(0,n)),a+=(a.indexOf("?")===-1?"?":"&")+r}return a}class zR{constructor(){this.handlers=[]}use(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}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Be.forEach(this.handlers,function(i){i!==null&&e(i)})}}const DO={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},QZ=typeof URLSearchParams<"u"?URLSearchParams:UC,ZZ=typeof FormData<"u"?FormData:null,JZ=typeof Blob<"u"?Blob:null,eJ={isBrowser:!0,classes:{URLSearchParams:QZ,FormData:ZZ,Blob:JZ},protocols:["http","https","file","blob","url","data"]},NO=typeof window<"u"&&typeof document<"u",tJ=(a=>NO&&["ReactNative","NativeScript","NS"].indexOf(a)<0)(typeof navigator<"u"&&navigator.product),iJ=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sJ=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:NO,hasStandardBrowserEnv:tJ,hasStandardBrowserWebWorkerEnv:iJ},Symbol.toStringTag,{value:"Module"})),Bo={...sJ,...eJ};function rJ(a,e){return Wx(a,new Bo.classes.URLSearchParams,Object.assign({visitor:function(t,i,s,r){return Bo.isNode&&Be.isBuffer(t)?(this.append(i,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))}function nJ(a){return Be.matchAll(/\w+|\[(\w*)]/g,a).map(e=>e[0]==="[]"?"":e[1]||e[0])}function aJ(a){const e={},t=Object.keys(a);let i;const s=t.length;let r;for(i=0;i=t.length;return n=!n&&Be.isArray(s)?s.length:n,l?(Be.hasOwnProp(s,n)?s[n]=[s[n],i]:s[n]=i,!o):((!s[n]||!Be.isObject(s[n]))&&(s[n]=[]),e(t,i,s[n],r)&&Be.isArray(s[n])&&(s[n]=aJ(s[n])),!o)}if(Be.isFormData(a)&&Be.isFunction(a.entries)){const t={};return Be.forEachEntry(a,(i,s)=>{e(nJ(i),s,t,0)}),t}return null}function oJ(a,e,t){if(Be.isString(a))try{return(e||JSON.parse)(a),Be.trim(a)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(a)}const VC={transitional:DO,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",s=i.indexOf("application/json")>-1,r=Be.isObject(e);if(r&&Be.isHTMLForm(e)&&(e=new FormData(e)),Be.isFormData(e))return s?JSON.stringify(wO(e)):e;if(Be.isArrayBuffer(e)||Be.isBuffer(e)||Be.isStream(e)||Be.isFile(e)||Be.isBlob(e))return e;if(Be.isArrayBufferView(e))return e.buffer;if(Be.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return rJ(e,this.formSerializer).toString();if((o=Be.isFileList(e))||i.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return Wx(o?{"files[]":e}:e,l&&new l,this.formSerializer)}}return r||s?(t.setContentType("application/json",!1),oJ(e)):e}],transformResponse:[function(e){const t=this.transitional||VC.transitional,i=t&&t.forcedJSONParsing,s=this.responseType==="json";if(e&&Be.isString(e)&&(i&&!this.responseType||s)){const n=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(o){if(n)throw o.name==="SyntaxError"?Di.from(o,Di.ERR_BAD_RESPONSE,this,null,this.response):o}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Bo.classes.FormData,Blob:Bo.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Be.forEach(["delete","get","head","post","put","patch"],a=>{VC.headers[a]={}});const kC=VC,lJ=Be.toObjectSet(["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"]),hJ=a=>{const e={};let t,i,s;return a&&a.split(` +`).forEach(function(n){s=n.indexOf(":"),t=n.substring(0,s).trim().toLowerCase(),i=n.substring(s+1).trim(),!(!t||e[t]&&lJ[t])&&(t==="set-cookie"?e[t]?e[t].push(i):e[t]=[i]:e[t]=e[t]?e[t]+", "+i:i)}),e},WR=Symbol("internals");function Zf(a){return a&&String(a).trim().toLowerCase()}function sg(a){return a===!1||a==null?a:Be.isArray(a)?a.map(sg):String(a)}function cJ(a){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(a);)e[i[1]]=i[2];return e}const uJ=a=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(a.trim());function DE(a,e,t,i,s){if(Be.isFunction(i))return i.call(this,e,t);if(s&&(e=t),!!Be.isString(e)){if(Be.isString(i))return e.indexOf(i)!==-1;if(Be.isRegExp(i))return i.test(e)}}function dJ(a){return a.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function fJ(a,e){const t=Be.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(a,i+t,{value:function(s,r,n){return this[i].call(this,e,s,r,n)},configurable:!0})})}class Hx{constructor(e){e&&this.set(e)}set(e,t,i){const s=this;function r(o,l,h){const c=Zf(l);if(!c)throw new Error("header name must be a non-empty string");const u=Be.findKey(s,c);(!u||s[u]===void 0||h===!0||h===void 0&&s[u]!==!1)&&(s[u||l]=sg(o))}const n=(o,l)=>Be.forEach(o,(h,c)=>r(h,c,l));return Be.isPlainObject(e)||e instanceof this.constructor?n(e,t):Be.isString(e)&&(e=e.trim())&&!uJ(e)?n(hJ(e),t):e!=null&&r(t,e,i),this}get(e,t){if(e=Zf(e),e){const i=Be.findKey(this,e);if(i){const s=this[i];if(!t)return s;if(t===!0)return cJ(s);if(Be.isFunction(t))return t.call(this,s,i);if(Be.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Zf(e),e){const i=Be.findKey(this,e);return!!(i&&this[i]!==void 0&&(!t||DE(this,this[i],i,t)))}return!1}delete(e,t){const i=this;let s=!1;function r(n){if(n=Zf(n),n){const o=Be.findKey(i,n);o&&(!t||DE(i,i[o],o,t))&&(delete i[o],s=!0)}}return Be.isArray(e)?e.forEach(r):r(e),s}clear(e){const t=Object.keys(this);let i=t.length,s=!1;for(;i--;){const r=t[i];(!e||DE(this,this[r],r,e,!0))&&(delete this[r],s=!0)}return s}normalize(e){const t=this,i={};return Be.forEach(this,(s,r)=>{const n=Be.findKey(i,r);if(n){t[n]=sg(s),delete t[r];return}const o=e?dJ(r):String(r).trim();o!==r&&delete t[r],t[o]=sg(s),i[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Be.forEach(this,(i,s)=>{i!=null&&i!==!1&&(t[s]=e&&Be.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach(s=>i.set(s)),i}static accessor(e){const i=(this[WR]=this[WR]={accessors:{}}).accessors,s=this.prototype;function r(n){const o=Zf(n);i[o]||(fJ(s,n),i[o]=!0)}return Be.isArray(e)?e.forEach(r):r(e),this}}Hx.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Be.reduceDescriptors(Hx.prototype,({value:a},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>a,set(i){this[t]=i}}});Be.freezeMethods(Hx);const El=Hx;function NE(a,e){const t=this||kC,i=e||t,s=El.from(i.headers);let r=i.data;return Be.forEach(a,function(o){r=o.call(t,r,s.normalize(),e?e.status:void 0)}),s.normalize(),r}function FO(a){return!!(a&&a.__CANCEL__)}function F_(a,e,t){Di.call(this,a??"canceled",Di.ERR_CANCELED,e,t),this.name="CanceledError"}Be.inherits(F_,Di,{__CANCEL__:!0});function pJ(a,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?a(t):e(new Di("Request failed with status code "+t.status,[Di.ERR_BAD_REQUEST,Di.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}const _J=Bo.hasStandardBrowserEnv?{write(a,e,t,i,s,r){const n=[a+"="+encodeURIComponent(e)];Be.isNumber(t)&&n.push("expires="+new Date(t).toGMTString()),Be.isString(i)&&n.push("path="+i),Be.isString(s)&&n.push("domain="+s),r===!0&&n.push("secure"),document.cookie=n.join("; ")},read(a){const e=document.cookie.match(new RegExp("(^|;\\s*)("+a+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(a){this.write(a,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function mJ(a){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(a)}function gJ(a,e){return e?a.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):a}function LO(a,e){return a&&!mJ(e)?gJ(a,e):e}const xJ=Bo.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function s(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return i=s(window.location.href),function(n){const o=Be.isString(n)?s(n):n;return o.protocol===i.protocol&&o.host===i.host}}():function(){return function(){return!0}}();function TJ(a){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(a);return e&&e[1]||""}function EJ(a,e){a=a||10;const t=new Array(a),i=new Array(a);let s=0,r=0,n;return e=e!==void 0?e:1e3,function(l){const h=Date.now(),c=i[r];n||(n=h),t[s]=l,i[s]=h;let u=r,d=0;for(;u!==s;)d+=t[u++],u=u%a;if(s=(s+1)%a,s===r&&(r=(r+1)%a),h-n{const r=s.loaded,n=s.lengthComputable?s.total:void 0,o=r-t,l=i(o),h=r<=n;t=r;const c={loaded:r,total:n,progress:n?r/n:void 0,bytes:o,rate:l||void 0,estimated:l&&n&&h?(n-r)/l:void 0,event:s};c[e?"download":"upload"]=!0,a(c)}}const SJ=typeof XMLHttpRequest<"u",vJ=SJ&&function(a){return new Promise(function(t,i){let s=a.data;const r=El.from(a.headers).normalize();let{responseType:n,withXSRFToken:o}=a,l;function h(){a.cancelToken&&a.cancelToken.unsubscribe(l),a.signal&&a.signal.removeEventListener("abort",l)}let c;if(Be.isFormData(s)){if(Bo.hasStandardBrowserEnv||Bo.hasStandardBrowserWebWorkerEnv)r.setContentType(!1);else if((c=r.getContentType())!==!1){const[_,...x]=c?c.split(";").map(E=>E.trim()).filter(Boolean):[];r.setContentType([_||"multipart/form-data",...x].join("; "))}}let u=new XMLHttpRequest;if(a.auth){const _=a.auth.username||"",x=a.auth.password?unescape(encodeURIComponent(a.auth.password)):"";r.set("Authorization","Basic "+btoa(_+":"+x))}const d=LO(a.baseURL,a.url);u.open(a.method.toUpperCase(),OO(d,a.params,a.paramsSerializer),!0),u.timeout=a.timeout;function f(){if(!u)return;const _=El.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),E={data:!n||n==="text"||n==="json"?u.responseText:u.response,status:u.status,statusText:u.statusText,headers:_,config:a,request:u};pJ(function(C){t(C),h()},function(C){i(C),h()},E),u=null}if("onloadend"in u?u.onloadend=f:u.onreadystatechange=function(){!u||u.readyState!==4||u.status===0&&!(u.responseURL&&u.responseURL.indexOf("file:")===0)||setTimeout(f)},u.onabort=function(){u&&(i(new Di("Request aborted",Di.ECONNABORTED,a,u)),u=null)},u.onerror=function(){i(new Di("Network Error",Di.ERR_NETWORK,a,u)),u=null},u.ontimeout=function(){let x=a.timeout?"timeout of "+a.timeout+"ms exceeded":"timeout exceeded";const E=a.transitional||DO;a.timeoutErrorMessage&&(x=a.timeoutErrorMessage),i(new Di(x,E.clarifyTimeoutError?Di.ETIMEDOUT:Di.ECONNABORTED,a,u)),u=null},Bo.hasStandardBrowserEnv&&(o&&Be.isFunction(o)&&(o=o(a)),o||o!==!1&&xJ(d))){const _=a.xsrfHeaderName&&a.xsrfCookieName&&_J.read(a.xsrfCookieName);_&&r.set(a.xsrfHeaderName,_)}s===void 0&&r.setContentType(null),"setRequestHeader"in u&&Be.forEach(r.toJSON(),function(x,E){u.setRequestHeader(E,x)}),Be.isUndefined(a.withCredentials)||(u.withCredentials=!!a.withCredentials),n&&n!=="json"&&(u.responseType=a.responseType),typeof a.onDownloadProgress=="function"&&u.addEventListener("progress",HR(a.onDownloadProgress,!0)),typeof a.onUploadProgress=="function"&&u.upload&&u.upload.addEventListener("progress",HR(a.onUploadProgress)),(a.cancelToken||a.signal)&&(l=_=>{u&&(i(!_||_.type?new F_(null,a,u):_),u.abort(),u=null)},a.cancelToken&&a.cancelToken.subscribe(l),a.signal&&(a.signal.aborted?l():a.signal.addEventListener("abort",l)));const m=TJ(d);if(m&&Bo.protocols.indexOf(m)===-1){i(new Di("Unsupported protocol "+m+":",Di.ERR_BAD_REQUEST,a));return}u.send(s||null)})},QS={http:$Z,xhr:vJ};Be.forEach(QS,(a,e)=>{if(a){try{Object.defineProperty(a,"name",{value:e})}catch{}Object.defineProperty(a,"adapterName",{value:e})}});const XR=a=>`- ${a}`,CJ=a=>Be.isFunction(a)||a===null||a===!1,BO={getAdapter:a=>{a=Be.isArray(a)?a:[a];const{length:e}=a;let t,i;const s={};for(let r=0;r`adapter ${o} `+(l===!1?"is not supported by the environment":"is not available in the build"));let n=e?r.length>1?`since : +`+r.map(XR).join(` +`):" "+XR(r[0]):"as no adapter specified";throw new Di("There is no suitable adapter to dispatch the request "+n,"ERR_NOT_SUPPORT")}return i},adapters:QS};function wE(a){if(a.cancelToken&&a.cancelToken.throwIfRequested(),a.signal&&a.signal.aborted)throw new F_(null,a)}function YR(a){return wE(a),a.headers=El.from(a.headers),a.data=NE.call(a,a.transformRequest),["post","put","patch"].indexOf(a.method)!==-1&&a.headers.setContentType("application/x-www-form-urlencoded",!1),BO.getAdapter(a.adapter||kC.adapter)(a).then(function(i){return wE(a),i.data=NE.call(a,a.transformResponse,i),i.headers=El.from(i.headers),i},function(i){return FO(i)||(wE(a),i&&i.response&&(i.response.data=NE.call(a,a.transformResponse,i.response),i.response.headers=El.from(i.response.headers))),Promise.reject(i)})}const $R=a=>a instanceof El?{...a}:a;function af(a,e){e=e||{};const t={};function i(h,c,u){return Be.isPlainObject(h)&&Be.isPlainObject(c)?Be.merge.call({caseless:u},h,c):Be.isPlainObject(c)?Be.merge({},c):Be.isArray(c)?c.slice():c}function s(h,c,u){if(Be.isUndefined(c)){if(!Be.isUndefined(h))return i(void 0,h,u)}else return i(h,c,u)}function r(h,c){if(!Be.isUndefined(c))return i(void 0,c)}function n(h,c){if(Be.isUndefined(c)){if(!Be.isUndefined(h))return i(void 0,h)}else return i(void 0,c)}function o(h,c,u){if(u in e)return i(h,c);if(u in a)return i(void 0,h)}const l={url:r,method:r,data:r,baseURL:n,transformRequest:n,transformResponse:n,paramsSerializer:n,timeout:n,timeoutMessage:n,withCredentials:n,withXSRFToken:n,adapter:n,responseType:n,xsrfCookieName:n,xsrfHeaderName:n,onUploadProgress:n,onDownloadProgress:n,decompress:n,maxContentLength:n,maxBodyLength:n,beforeRedirect:n,transport:n,httpAgent:n,httpsAgent:n,cancelToken:n,socketPath:n,responseEncoding:n,validateStatus:o,headers:(h,c)=>s($R(h),$R(c),!0)};return Be.forEach(Object.keys(Object.assign({},a,e)),function(c){const u=l[c]||s,d=u(a[c],e[c],c);Be.isUndefined(d)&&u!==o||(t[c]=d)}),t}const UO="1.6.8",GC={};["object","boolean","number","function","string","symbol"].forEach((a,e)=>{GC[a]=function(i){return typeof i===a||"a"+(e<1?"n ":" ")+a}});const KR={};GC.transitional=function(e,t,i){function s(r,n){return"[Axios v"+UO+"] Transitional option '"+r+"'"+n+(i?". "+i:"")}return(r,n,o)=>{if(e===!1)throw new Di(s(n," has been removed"+(t?" in "+t:"")),Di.ERR_DEPRECATED);return t&&!KR[n]&&(KR[n]=!0,console.warn(s(n," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(r,n,o):!0}};function bJ(a,e,t){if(typeof a!="object")throw new Di("options must be an object",Di.ERR_BAD_OPTION_VALUE);const i=Object.keys(a);let s=i.length;for(;s-- >0;){const r=i[s],n=e[r];if(n){const o=a[r],l=o===void 0||n(o,r,a);if(l!==!0)throw new Di("option "+r+" must be "+l,Di.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Di("Unknown option "+r,Di.ERR_BAD_OPTION)}}const ZS={assertOptions:bJ,validators:GC},Hl=ZS.validators;class Lg{constructor(e){this.defaults=e,this.interceptors={request:new zR,response:new zR}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const r=s.stack?s.stack.replace(/^.+\n/,""):"";i.stack?r&&!String(i.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(i.stack+=` +`+r):i.stack=r}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=af(this.defaults,t);const{transitional:i,paramsSerializer:s,headers:r}=t;i!==void 0&&ZS.assertOptions(i,{silentJSONParsing:Hl.transitional(Hl.boolean),forcedJSONParsing:Hl.transitional(Hl.boolean),clarifyTimeoutError:Hl.transitional(Hl.boolean)},!1),s!=null&&(Be.isFunction(s)?t.paramsSerializer={serialize:s}:ZS.assertOptions(s,{encode:Hl.function,serialize:Hl.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=r&&Be.merge(r.common,r[t.method]);r&&Be.forEach(["delete","get","head","post","put","patch","common"],m=>{delete r[m]}),t.headers=El.concat(n,r);const o=[];let l=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(t)===!1||(l=l&&_.synchronous,o.unshift(_.fulfilled,_.rejected))});const h=[];this.interceptors.response.forEach(function(_){h.push(_.fulfilled,_.rejected)});let c,u=0,d;if(!l){const m=[YR.bind(this),void 0];for(m.unshift.apply(m,o),m.push.apply(m,h),d=m.length,c=Promise.resolve(t);u{if(!i._listeners)return;let r=i._listeners.length;for(;r-- >0;)i._listeners[r](s);i._listeners=null}),this.promise.then=s=>{let r;const n=new Promise(o=>{i.subscribe(o),r=o}).then(s);return n.cancel=function(){i.unsubscribe(r)},n},e(function(r,n,o){i.reason||(i.reason=new F_(r,n,o),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}static source(){let e;return{token:new zC(function(s){e=s}),cancel:e}}}const yJ=zC;function AJ(a){return function(t){return a.apply(null,t)}}function RJ(a){return Be.isObject(a)&&a.isAxiosError===!0}const JS={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(JS).forEach(([a,e])=>{JS[e]=a});const IJ=JS;function VO(a){const e=new rg(a),t=TO(rg.prototype.request,e);return Be.extend(t,rg.prototype,e,{allOwnKeys:!0}),Be.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return VO(af(a,s))},t}const rr=VO(kC);rr.Axios=rg;rr.CanceledError=F_;rr.CancelToken=yJ;rr.isCancel=FO;rr.VERSION=UO;rr.toFormData=Wx;rr.AxiosError=Di;rr.Cancel=rr.CanceledError;rr.all=function(e){return Promise.all(e)};rr.spread=AJ;rr.isAxiosError=RJ;rr.mergeConfig=af;rr.AxiosHeaders=El;rr.formToJSON=a=>wO(Be.isHTMLForm(a)?new FormData(a):a);rr.getAdapter=BO.getAdapter;rr.HttpStatusCode=IJ;rr.default=rr;async function PJ(a,e){return await rr.post("/set_pointcloud",{points:a,colors:e})}async function MJ(a,e){const t=a.map(r=>r.point),i=a.map(r=>r.label),s=a.map(r=>r.instance);return(await rr.post("/set_prompts",{prompt_coords:t,prompt_labels:i,instance_id:s,user_id:e})).data}async function OJ(a){return(await rr.post("/set_candidate",{index:a})).data}const DJ=a=>(_2("data-v-b6c6eeab"),a=a(),m2(),a),NJ={style:{position:"absolute",left:"5px",top:"5px",background:"white",padding:"1rem","border-radius":"5px","max-height":"98%",overflow:"auto"}},wJ={style:{display:"flex","flex-direction":"row","align-items":"center"}},FJ=DJ(()=>ro("label",{for:"pcToggle"},"Show Points",-1)),LJ={style:{display:"flex","flex-direction":"row","align-items":"center"}},BJ={style:{position:"absolute",right:"5px",top:"5px",display:"flex"}},UJ={style:{display:"flex","flex-direction":"row","align-items":"center"}},VJ=QR({__name:"SegmentViewer",props:{file:{}},emits:["onsave"],setup(a,{emit:e}){class t{constructor(ue){So(this,"name","LoadSceneMetadata");So(this,"enabled",!0);So(this,"extras");this.loader=ue}dispose(){}loadSceneAsync(ue,oe){return this.loader.babylonScene.metadata={gltf:{extras:oe.extras}},this.loader.loadSceneAsync(ue,oe)}}let i=[0,0];function s(Te){i=[Te.layerX,Te.layerY]}$e.RegisterExtension("LoadSceneMetadata",Te=>new t(Te));const r=ZR(),n=Xl(!1),o=Xl(!1),l=a,h=Xl(),c=Xl();let u,d,f,m=[],_;const x=Xl(),E=Xl([]);let S,C,y;const A=u2({get(){return x.value?x.value.isVisible:!1},set(Te){S!=null&&S[0]&&S.forEach(ue=>ue.isVisible=!Te),x.value&&(x.value.isVisible=Te)}});let I=0;const R=Xl([]);function N(){m.forEach(Te=>Te.dispose()),m=[]}function k(Te,ue,oe){const F=new q("highlight",Te.getScene());F.overrideMaterialSideOrientation=Te.overrideMaterialSideOrientation,F.position=Te.absolutePosition,F.rotationQuaternion=Te.absoluteRotationQuaternion,F.scaling=Te.absoluteScaling;const ie=Se.ExtractFromMesh(Te);if(ue){const et=ie.indices||[];ie.indices=ue.map(ye=>[et[3*ye],et[3*ye+1],et[3*ye+2]]).flat()}ie.applyToMesh(F);const he=new Ie("__Point-SAM.overlay",d);he.disableLighting=!0,he.backFaceCulling=!1,he.emissiveColor=new re(1-(1-oe[0])*.5,1-(1-oe[1])*.5,1-(1-oe[2])*.5),he.zOffset=-.1,he.alpha=.5,F.material=he;const ke=F.clone(),Ye=new Ie("__Point-SAM.overlay",d);Ye.wireframe=!0,Ye.disableLighting=!0,Ye.backFaceCulling=!1,Ye.emissiveColor=new re(oe[0],oe[1],oe[2]),Ye.zOffset=-.15,Ye.alpha=.5,ke.material=Ye,ke.setParent(F),m.push(F)}async function B(){if(u&&c.value){R.value=[];try{n.value=!0,d&&d.dispose(),d=new Ue(u),d.useRightHandedSystem=!0,f=new Ii("__Point-SAM.camera__",0,0,1,new T,d,!0),f.attachControl(c,!1),f.inputs.attached.pointers.buttons=[1],f.inputs.attached.pointers.onTouch=function(et,ye,Ae){if(f&&!this._ctrlKey)if(this.panningSensibility!==0&&(this._shiftKey||this._isPanClick)){let rt=T.TransformCoordinates(new T(0,0,-f.radius),f.getProjectionMatrix());rt=T.TransformCoordinates(new T(ye*2/c.value.width,Ae*2/c.value.height,rt.z),f.getProjectionMatrix().clone().invert()),this.camera.inertialPanningX-=rt.x,this.camera.inertialPanningY+=rt.y}else this.camera.inertialAlphaOffset-=ye/this.angularSensibilityX,this.camera.inertialBetaOffset-=Ae/this.angularSensibilityY};const Te=new Rh("__Point-SAM.light__",new T(0,1,0),d);if(Te.groundColor=new re(.3,.3,.3),d.clearColor=new Oe(.75,.75,.75,1),!l.file)return;await ft.ImportMeshAsync("","",l.file,d),S=d.meshes.filter(et=>et instanceof q&&et.getTotalVertices()),C=new dZ(S),y=await C.sampleAtLeastOnce(1e3),o.value=!0,await fe(),o.value=!1,_=new PK("__Point-SAM.pcd",0,d),_.addPoints(y.points.length,(et,ye)=>{var Ae;et.position=y.points[ye],et.color=((Ae=y.colors[ye])==null?void 0:Ae.toColor4())||new Oe(.8,.8,.8,1)}),_.buildMeshAsync().then(et=>{et.material.pointSize=2,et.isVisible=!1,et.isPickable=!1,x.value=et});const oe=d.rootNodes.filter(et=>et.name=="__root__")[0],F=d.getWorldExtends(),ie=F.min,he=F.max,ke=ie.add(he).scale(.5),Ye=he.subtract(ie).length()/2;f.target=ke,f.radius=Ye*3,f.minZ=Ye*.1,f.maxZ=Ye*1e3,f.beta=Math.PI/4,f.alpha=Math.PI*1/4,f.lowerRadiusLimit=Ye*.1,f.upperRadiusLimit=Ye*100,f.wheelDeltaPercentage=.1,f.angularSensibilityX=100,f.angularSensibilityY=100,f.panningSensibility=200/Ye,f.panningInertia=0,f.inertialAlphaOffset=0,f.inertia=0}catch(Te){console.log(Te),r.add({severity:"error",summary:"Failed to load model",group:"br",life:3e3})}finally{n.value=!1}}}d2(l,()=>{B()},{immediate:!0,deep:!0});function Q(){u==null||u.resize()}async function ne(Te,ue,oe){const F=Go("point",void 0,d),ie=((f==null?void 0:f.radius)||1)*.005;F.scaling=new T(ie,ie,ie),F.position=Te;const he=new Ie("prompt_mat",d);ue?he.diffuseColor=new re(1,.8,.1):he.diffuseColor=new re(.1,.8,.8),F.material=he,R.value.push({point:[Te.x,Te.y,Te.z],label:ue,instance:oe,mesh:F}),await Ee()}async function de(Te){var ue,oe;if(Te===void 0){R.value.forEach(F=>{var ie;return(ie=F.mesh)==null?void 0:ie.dispose()}),R.value=[],await Ee();return}console.log(Te),(oe=(ue=R.value[Te])==null?void 0:ue.mesh)==null||oe.dispose(),R.value.splice(Te,1),await Ee()}async function ge(Te){if(!d)return;const ue=d.pick(i[0],i[1],oe=>oe.isEnabled()&&oe.isPickable);ue.hit&&ue.pickedMesh instanceof q&&ue.pickedPoint&&(Te.button==0?(console.log("pick"),await ne(ue.pickedPoint,1,1)):Te.button==2&&(console.log("pick"),await ne(ue.pickedPoint,0,1)))}async function fe(){const Te=y.points.map(F=>[F.x,F.y,F.z]),ue=y.colors.map(F=>[F.r,F.g,F.b]);I=(await PJ(Te,ue)).data.user_id}async function Ee(){const{mask:Te}=await MJ(R.value,I);E.value=Te,De(0)}async function De(Te){N();const ue=E.value[Te];if(!E.value[Te])return;await OJ(Te);const oe=S.map(()=>[]);C.pointLabelToFaces(y.meshes,y.faces,ue.map(F=>F?1:0)).forEach((F,ie)=>{F.forEach((he,ke)=>{he&&oe[ie].push(ke)})}),S.forEach((F,ie)=>k(F,oe[ie],[.8,.5,.1])),ue.forEach((F,ie)=>{F?_.particles[ie].color=new Oe(1,0,0,1):_.particles[ie].color=new Oe(0,0,1,1)}),_.setParticles()}return JR(()=>{c.value&&(u=new ee(c.value,!0,{stencil:!0}),u.runRenderLoop(function(){d==null||d.render()}),window.addEventListener("resize",Q))}),f2(()=>{u==null||u.stopRenderLoop(),window.removeEventListener("resize",Q)}),(Te,ue)=>(dr(),$r("div",{ref_key:"container",ref:h,id:"canvas_container"},[qR(ro("canvas",{ref_key:"canvas",ref:c,style:{width:"100%",height:"100%"},onMousemove:s,onPointerdown:ge},null,544),[[p2,!o.value&&!n.value]]),ro("div",NJ,[ro("div",wJ,[Wm(Yf(nI),{modelValue:A.value,"onUpdate:modelValue":ue[0]||(ue[0]=oe=>A.value=oe),inputId:"pcToggle",style:{margin:"3px"}},null,8,["modelValue"]),FJ]),(dr(!0),$r(gA,null,xA(R.value,(oe,F)=>(dr(),$r("div",LJ,[Wm(Yf(Xm),{text:"",icon:"pi pi-trash",onClick:()=>de(F)},null,8,["onClick"]),jR(" Prompt "+ng(F)+" "+ng(oe.label?"+":"-"),1)]))),256)),R.value.length?(dr(),ag(Yf(Xm),{key:0,icon:"pi pi-trash",label:"Clear Prompts",onClick:ue[1]||(ue[1]=()=>de())})):sc("",!0)]),ro("div",BJ,[(dr(!0),$r(gA,null,xA(E.value,(oe,F)=>(dr(),$r("div",UJ,[Wm(Yf(Xm),{label:"Candidate "+F,onClick:()=>De(F),style:{width:"150px",margin:"5px"}},null,8,["label","onClick"])]))),256))]),o.value?(dr(),ag(Yf(xO),{key:0,strokeWidth:"4",style:{position:"absolute",width:"20%",height:"20%",right:"50%",top:"50%"}})):sc("",!0)],512))}}),kJ=g2(VJ,[["__scopeId","data-v-b6c6eeab"]]),GJ={key:0},zJ={key:1},WJ={key:2},HJ={style:{height:"calc(100vh - 84px)"}},KJ=QR({__name:"PlaygroundView",setup(a){const e=Xl();ZR();const t=x2();function i(n){var l,h;const o=(h=(l=n.dataTransfer)==null?void 0:l.files)==null?void 0:h[0];o&&o.name.endsWith(".glb")&&(e.value=o)}function s(){}function r(){}return JR(()=>{t.query.url&&(e.value=t.query.url.toString())}),(n,o)=>(dr(),$r("div",{id:"drop_zone",onDrop:tE(i,["prevent"]),onDragover:tE(s,["prevent"]),onDragenter:tE(r,["prevent"])},[e.value?sc("",!0):(dr(),$r("p",GJ,"Drag glb file here.")),e.value?sc("",!0):(dr(),$r("p",zJ,"Since the GPU performance limitation of huggingface, please try meshes with less than 50k faces")),e.value?sc("",!0):(dr(),$r("p",WJ,"If you want to annotate a mesh with more than 50k points, please use our local demo.")),ro("div",HJ,[Wm(kJ,{file:e.value},null,8,["file"])])],32))}});export{KJ as default};